gxd-vue-library
Version:
依赖与element Ui插件库,聚福宝福利PC端插件库
191 lines (165 loc) • 5.51 kB
JavaScript
;
const settings = require('../../settings');
const path = require('path');
const basePath = require('./../path');
const OSS = require('ali-oss');
const fileHelper = require('./../fileHepler');
const ProgressBar = require('progress');
const clog = require('./../clog');
const utils = require('./../lib/utils');
const os = require('os');
const {
getArgv
} = utils;
class Oss {
constructor(callback, ossConfig) {
this.bucket = process.env.bucket;
this.region = process.env.region;
this.fileDir = basePath.buildDistDirectory;
this.config = ossConfig;
this.checkConfig();
this.client = new OSS({
region: this.region,
bucket: this.bucket,
accessKeyId: this.config['account'],
accessKeySecret: this.config['password']
});
this.callback = callback;
//获取上传文件
this.progressBar = null; //上传进度条
this.error = []; //上传失败
this.success = 0; //上传成功数量
this.files = [];
this.getFiles();
this.upload()
}
/**
* @description 检查配置是否存在
*/
checkConfig() {
if (!this.config || !this.config['account'] || !this.config['password']) {
throw new Error('OSS配置错误');
}
}
/**
* @description 上传文件
*/
upload() {
clog('---开始上传--------------', 'green');
let result = [];
this.files.map((item) => {
let meta = {};
if(item.isHtml) meta = { headers: {'Cache-Control': 'max-age=10'} }
result.push(new Promise((resolve, reject) => {
result.push(
this.client['put'](item.source, path.normalize(item.target),meta)
.then(res => {
this.progressBar['tick']();
this.success = this.success + 1;
resolve(res)
})
.catch(error => {
this.progressBar['tick']();
this.error.push(item);
resolve(
error
)
})
)
}))
});
Promise.all(result)
.then(res => {
clog(`---上传文件结束,共(${this.success})文件--------------`, 'green');
if (this.error.length > 0) {
clog(`---上传文件失败,共(${this.error.length})文件--------------`, 'red');
console.log(this.error)
}
this.callback()
})
.catch(res => {
})
}
/**
* @description 获取需要上传到文件
*/
getFiles() {
let files = fileHelper.getDirFiles(this.fileDir, ['ico', 'js', 'html', 'css', 'png', 'gif', 'jpg', 'jpeg', 'woff', 'ttf']);
let temp = [];
Object.keys(files).map((key) => {
let isHtml = /^.+(\.html)$/.test(files[key].fullName);
let url = '';
//根据路由规则,使用系统标识作为上传根目录
if(settings.routerMode === 'hash' && settings.showTopNavMenu === true) {
url = `${settings.system}/`
}
//根据配置自定义上传跟目录
if(settings.custom_project_root) {
url = `${settings.custom_project_root}/`
}
temp.push({
source: `${url}${files[key]['fullName']}`.replace(/(\\)/g, '/'),
target: fileHelper.getPlatformSurePath(`${this.fileDir}/${files[key]['fullName']}`),
isHtml
});
});
this.files = temp;
if (this.files.length === 0) {
clog(`---上传文件失败,共(${this.error.length})文件--------------`, 'red');
throw new Error('此次上传不包含上传文件');
return
}
//设置进度条
this.progressBar = new ProgressBar('Uploading [:bar] :rate/bps :percent :etas', {
complete: '=',
incomplete: ' ',
width: 20,
total: temp.length
});
}
}
let params = getArgv();
let platform = process.env.platform || 'jufubao';
if (params.length === 1) {
let pathEnv = basePath.rootDir + 'env.current.json';
if(!fileHelper.existFileSync(pathEnv)) {
clog(`配置文件不存在,path=${pathEnv} \n`, 'red');
process.exit(0)
}
let pathEnvData = require(pathEnv);
let bucket = process.env.bucket;
let isBuild = /(sandbox-)/.test(bucket)? 'test': 'build';
if (pathEnvData.type === 'sandbox') pathEnvData.type = 'test';
if(pathEnvData.type !== isBuild) {
clog(`打包生成代码环境不是当前部署环境代码,请确认再操作\n`, 'red');
process.exit(0)
}
//发布代码环境判断
if(platform !== pathEnvData.platform) {
clog(`打包代码与发布环境不同,请确认再操作\n`, 'red');
process.exit(0)
}
let ossPath = params[0] + 'oss_config.js';
if (!fileHelper.existFileSync(ossPath)) {
clog(`Oss Config配置文件路径不存在,path=${ossPath}\n`, 'red');
process.exit(0)
}
const ossConfig = require(params[0] + 'oss_config.js');
clog(`正在使用阿里云OSS服务上传文件,当前使用桶:${process.env.bucket},项目名称:${process.env.name}\n`, 'green');
process.stdin.setEncoding('utf8');
process.stdout.write("确认执行吗(y/n)?");
process.stdin.on('data', (input) => {
input = input.toString().trim();
if (['Y', 'y', 'YES', 'yes'].indexOf(input) > -1) {
new Oss(() => {
process.exit();
}, ossConfig);
}
if (['N', 'n', 'NO', 'no'].indexOf(input) > -1) process.exit(0);
});
}
else {
let ossPath = '/Users/shiyonggao/home/root/oss.dev/';
if(os.type() === 'Windows_NT') ossPath = 'D:\\\\root\\\\oss.dev\\\\';
clog(`例如:npm run oss.dev ${ossPath} `, 'red');
}