gulpfile.js 2.76 KB
const gulp = require('gulp');
const {
    series
} = require('gulp');
const GulpSSH = require('gulp-ssh');
var through = require('through2');

/**
 * 获取参数,目前支持--env和--moudle
 * @param {Array} argv
 */
const params = (argv) => {
    console.log(argv);
    const obj = {};
    if (!argv && argv.length < 3) {
        return obj;
    }
    for (let i = 2; i < argv.length; i++) {
        console.log(argv[i]);
        if (argv[i].indexOf('--') === 0 && argv[i + 1].indexOf('--') === -1) {
            obj[argv[i].substring(2)] = argv[i + 1];
        }
    }
    return obj;
};
/**
 * 读取配置文件信息 .env.dev 、.env.pro、.env.test
 * @param {String} content
 */
const filesToConfig = (content) => {
    const lines = content.split('\n');
    const obj = {};
    for (let i = 0; i < lines.length; i++) {
        const item = lines[i];
        if (item.indexOf('#') === 0 || !item) {
            continue;
        }
        const KeyValue = item.split('=');
        if (KeyValue !== 2 && !KeyValue[0].trim() && !KeyValue[1].trim()) {
            continue;
        }
        const value = KeyValue[1].trim();
        const key = KeyValue[0].trim().toLocaleLowerCase();
        console.log(value.indexOf('\''), value.lastIndexOf('\''), value.length - 1);
        if (value.indexOf('\'') === 0 && value.lastIndexOf('\'') === value.length - 1) {
            obj[key] = value.substring(1, value.length - 1);
            continue;
        }
        obj[key] = '';
    }
    console.log(obj);
    return obj;
};

let gulpSSH = null;
let staticPath = '';
let distPath = '';

function getGupSSH(cb) {
    const PARAMS = params(process.argv);
    const ENV = PARAMS.env;
    const QGMODULE = PARAMS.qgModule;
    return gulp.src(`./.env.${ENV}`).pipe(through.obj(function(file, encode, callback) {
        const obj = filesToConfig(file.contents.toString());
        gulpSSH = new GulpSSH({
            ignoreErrors: false,
            sshConfig: obj
        });
        staticPath = obj[QGMODULE + '_remote_path'];
        distPath = obj[QGMODULE + '_dist_path'];

        callback();
    })).on('data', (data) => {
    }).on('end', () => {
        if (!distPath || !staticPath) {
            // TODO
            console.log('获取路径失败', distPath, staticPath);
            return new Error('获取路径失败');
        }
        console.log('获取路径成功', distPath, staticPath);
    });
}

/**
 * 将远程服务器代码清除
 */
function clean(cb) {
    return gulpSSH.shell(`rm -rf ${staticPath}`);
}

/**
 * 根据环境和模块获取相应配置文件后,将打包后的代码部署到服务器上
 * @param {*} cb
 */
function deploy(cb) {
    return gulp
        .src([`${distPath}/**`])
        .pipe(gulpSSH.dest(staticPath));
}

exports.default = series(getGupSSH, clean, deploy);