add.js 1.5 KB
const moment = require('moment');
const shelljs = require('shelljs');
const chalk = require('chalk');
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const argv = require('optimist').argv

const time = moment();
const author = shelljs.exec('git config --get user.email', {
    silent: true
}).stdout.trim();
const authorName = shelljs.exec('git config --get user.name', {
    silent: true
}).stdout.trim();
const comment = process.env.npm_config_comment || argv.comment;

if (!comment) {
    console.log(chalk.red('缺少-comment(备注)参数'));
    return;
}

const migrationPath = path.join(__dirname, '../../migrations');
const fileName = time.format('YYYYMMDDkkmmss');
let migrationTemplate = fs.readFileSync(path.join(__dirname, './migration.sql'), 'utf-8');

migrationTemplate = migrationTemplate
    .replace('${author}', author)
    .replace('${time}', time.format('YYYY-MM-DD kk:mm:ss'))
    .replace('${comment}', comment)
    .replace('${authorName}', authorName);

fs.writeFileSync(path.join(migrationPath, `${fileName}.sql`), migrationTemplate, {
    encoding: 'utf8'
});

let migrations = require('../../migrations');

migrations.push(fileName);

let migrationStr = _.join(_.map(migrations, m => {
    return `'${m}'`;
}), ', ');

fs.writeFileSync(path.join(migrationPath, 'index.js'), `module.exports = [${migrationStr}];
`, {
    encoding: 'utf8'
});
console.log(chalk.yellow('注意:GO;分割执行块'));
console.log(chalk.green(`新增迁移记录:${fileName}.sql`));