knex/bin/cli.js

390 lines
12 KiB
JavaScript
Raw Normal View History

2015-05-09 13:58:18 -04:00
#!/usr/bin/env node
/* eslint no-console:0, no-var:0 */
const Liftoff = require('liftoff');
const interpret = require('interpret');
const path = require('path');
const tildify = require('tildify');
const commander = require('commander');
const color = require('colorette');
const argv = require('getopts')(process.argv.slice(2));
const cliPkg = require('../package');
const {
mkConfigObj,
resolveEnvironmentConfig,
exit,
success,
checkLocalModule,
getMigrationExtension,
getSeedExtension,
getStubPath,
} = require('./utils/cli-config-utils');
const { readFile, writeFile } = require('./../lib/util/fs');
const { listMigrations } = require('./utils/migrationsLister');
2015-05-09 13:58:18 -04:00
async function openKnexfile(configPath) {
const importFile = require('../lib/util/import-file'); // require me late!
let config = await importFile(configPath);
2020-04-19 00:40:23 +02:00
if (typeof config === 'function') {
config = await config();
}
return config;
}
async function initKnex(env, opts) {
2015-05-09 13:58:18 -04:00
checkLocalModule(env);
if (process.cwd() !== env.cwd) {
process.chdir(env.cwd);
console.log(
'Working directory changed to',
color.magenta(tildify(env.cwd))
);
2015-05-09 13:58:18 -04:00
}
if (opts.esm) {
// enable esm interop via 'esm' module
require = require('esm')(module);
// https://github.com/standard-things/esm/issues/868
// complete the hack: enabling requiring esm from 'module' type package
require.extensions['.js'] = (m, fileName) =>
m._compile(require('fs').readFileSync(fileName, 'utf8'), fileName);
}
env.configuration = env.configPath
? await openKnexfile(env.configPath)
: mkConfigObj(opts);
const resolvedConfig = resolveEnvironmentConfig(
opts,
env.configuration,
env.configPath
);
const knex = require(env.modulePath);
return knex(resolvedConfig);
}
2015-05-09 13:58:18 -04:00
function invoke(env) {
env.modulePath = env.modulePath || env.knexpath || process.env.KNEX_PATH;
const filetypes = ['js', 'coffee', 'ts', 'eg', 'ls'];
2015-05-09 13:58:18 -04:00
const cliVersion = [
color.blue('Knex CLI version:'),
color.green(cliPkg.version),
].join(' ');
const localVersion = [
color.blue('Knex Local version:'),
color.green(env.modulePackage.version || 'None'),
].join(' ');
2015-05-09 13:58:18 -04:00
commander
.version(`${cliVersion}\n${localVersion}`)
2015-05-09 13:58:18 -04:00
.option('--debug', 'Run with debugging.')
.option('--knexfile [path]', 'Specify the knexfile path.')
.option('--knexpath [path]', 'Specify the path to knex instance.')
2015-05-09 13:58:18 -04:00
.option('--cwd [path]', 'Specify the working directory.')
.option('--client [name]', 'Set DB client without a knexfile.')
.option('--connection [address]', 'Set DB connection without a knexfile.')
.option(
'--migrations-directory [path]',
'Set migrations directory without a knexfile.'
)
.option(
'--migrations-table-name [path]',
'Set migrations table name without a knexfile.'
)
.option(
'--env [name]',
'environment, default: process.env.NODE_ENV || development'
2020-01-14 22:01:31 +02:00
)
2020-04-19 00:40:23 +02:00
.option('--esm', 'Enable ESM interop.')
.option('--specific [path]', 'Specify one seed file to execute.');
2015-05-09 13:58:18 -04:00
commander
.command('init')
.description(' Create a fresh knexfile.')
.option(
`-x [${filetypes.join('|')}]`,
'Specify the knexfile extension (default js)'
)
.action(() => {
const type = (argv.x || 'js').toLowerCase();
2015-05-09 13:58:18 -04:00
if (filetypes.indexOf(type) === -1) {
exit(`Invalid filetype specified: ${type}`);
2015-05-09 13:58:18 -04:00
}
if (env.configuration) {
exit(`Error: ${env.knexfile} already exists`);
2015-05-09 13:58:18 -04:00
}
checkLocalModule(env);
const stubPath = `./knexfile.${type}`;
readFile(
path.dirname(env.modulePath) +
'/lib/migrate/stub/knexfile-' +
type +
'.stub'
)
.then((code) => {
return writeFile(stubPath, code);
})
.then(() => {
success(color.green(`Created ${stubPath}`));
})
.catch(exit);
2015-05-09 13:58:18 -04:00
});
commander
.command('migrate:make <name>')
2017-01-11 18:47:24 +05:45
.description(' Create a named migration file.')
.option(
`-x [${filetypes.join('|')}]`,
'Specify the stub extension (default js)'
)
.option(
`--stub [<relative/path/from/knexfile>|<name>]`,
'Specify the migration stub to use. If using <name> the file must be located in config.migrations.directory'
)
.action(async (name) => {
const opts = commander.opts();
opts.client = opts.client || 'sqlite3'; // We don't really care about client when creating migrations
const instance = await initKnex(env, opts);
const ext = getMigrationExtension(env, opts);
const configOverrides = { extension: ext };
const stub = getStubPath('migrations', env, opts);
if (stub) {
configOverrides.stub = stub;
}
instance.migrate
.make(name, configOverrides)
.then((name) => {
success(color.green(`Created Migration: ${name}`));
})
.catch(exit);
2015-05-09 13:58:18 -04:00
});
commander
.command('migrate:latest')
.description(' Run all migrations that have not yet been run.')
.option('--verbose', 'verbose')
.action(async () => {
try {
const instance = await initKnex(env, commander.opts());
const [batchNo, log] = await instance.migrate.latest();
if (log.length === 0) {
success(color.cyan('Already up to date'));
}
success(
color.green(`Batch ${batchNo} run: ${log.length} migrations`) +
(argv.verbose ? `\n${color.cyan(log.join('\n'))}` : '')
);
} catch (err) {
exit(err);
}
});
commander
.command('migrate:up [<name>]')
.description(
' Run the next or the specified migration that has not yet been run.'
)
.action((name) => {
initKnex(env, commander.opts())
.then((instance) => instance.migrate.up({ name }))
.then(([batchNo, log]) => {
if (log.length === 0) {
success(color.cyan('Already up to date'));
}
success(
color.green(
`Batch ${batchNo} ran the following migrations:\n${log.join(
'\n'
)}`
)
);
})
.catch(exit);
2015-05-09 13:58:18 -04:00
});
commander
.command('migrate:rollback')
.description(' Rollback the last batch of migrations performed.')
.option('--all', 'rollback all completed migrations')
.option('--verbose', 'verbose')
.action((cmd) => {
const { all } = cmd;
initKnex(env, commander.opts())
.then((instance) => instance.migrate.rollback(null, all))
.then(([batchNo, log]) => {
if (log.length === 0) {
success(color.cyan('Already at the base migration'));
}
success(
color.green(
`Batch ${batchNo} rolled back: ${log.length} migrations`
) + (argv.verbose ? `\n${color.cyan(log.join('\n'))}` : '')
);
})
.catch(exit);
2015-05-09 13:58:18 -04:00
});
2019-05-29 18:37:18 -04:00
commander
.command('migrate:down [<name>]')
.description(
' Undo the last or the specified migration that was already run.'
)
.action((name) => {
initKnex(env, commander.opts())
.then((instance) => instance.migrate.down({ name }))
.then(([batchNo, log]) => {
2019-05-29 18:37:18 -04:00
if (log.length === 0) {
success(color.cyan('Already at the base migration'));
}
success(
color.green(
`Batch ${batchNo} rolled back the following migrations:\n${log.join(
'\n'
)}`
)
);
})
.catch(exit);
});
2015-05-09 13:58:18 -04:00
commander
.command('migrate:currentVersion')
2017-01-11 18:47:24 +05:45
.description(' View the current version for the migration.')
.action(() => {
initKnex(env, commander.opts())
.then((instance) => instance.migrate.currentVersion())
.then((version) => {
success(color.green('Current Version: ') + color.blue(version));
})
.catch(exit);
});
commander
.command('migrate:list')
.alias('migrate:status')
.description(' List all migrations files with status.')
.action(() => {
initKnex(env, commander.opts())
.then((instance) => {
return instance.migrate.list();
})
.then(([completed, newMigrations]) => {
listMigrations(completed, newMigrations);
})
.catch(exit);
2015-05-09 13:58:18 -04:00
});
commander
.command('migrate:unlock')
.description(' Forcibly unlocks the migrations lock table.')
.action(() => {
initKnex(env, commander.opts())
.then((instance) => instance.migrate.forceFreeMigrationsLock())
.then(() => {
success(
color.green(`Succesfully unlocked the migrations lock table`)
);
})
.catch(exit);
});
2015-05-09 13:58:18 -04:00
commander
.command('seed:make <name>')
2017-01-11 18:47:24 +05:45
.description(' Create a named seed file.')
.option(
`-x [${filetypes.join('|')}]`,
'Specify the stub extension (default js)'
)
.option(
`--stub [<relative/path/from/knexfile>|<name>]`,
'Specify the seed stub to use. If using <name> the file must be located in config.seeds.directory'
)
.action(async (name) => {
const opts = commander.opts();
opts.client = opts.client || 'sqlite3'; // We don't really care about client when creating seeds
const instance = await initKnex(env, opts);
const ext = getSeedExtension(env, opts);
const configOverrides = { extension: ext };
const stub = getStubPath('seeds', env, opts);
if (stub) {
configOverrides.stub = stub;
}
instance.seed
.make(name, configOverrides)
.then((name) => {
success(color.green(`Created seed file: ${name}`));
})
.catch(exit);
2015-05-09 13:58:18 -04:00
});
commander
.command('seed:run')
2017-01-11 18:47:24 +05:45
.description(' Run seed files.')
.option('--verbose', 'verbose')
.option('--specific', 'run specific seed file')
.action(() => {
initKnex(env, commander.opts())
.then((instance) => instance.seed.run({ specific: argv.specific }))
.then(([log]) => {
if (log.length === 0) {
success(color.cyan('No seed files exist'));
}
success(
color.green(`Ran ${log.length} seed files`) +
(argv.verbose ? `\n${color.cyan(log.join('\n'))}` : '')
);
})
.catch(exit);
2015-05-09 13:58:18 -04:00
});
if (!process.argv.slice(2).length) {
commander.outputHelp();
}
commander.parse(process.argv);
2015-05-09 13:58:18 -04:00
}
const cli = new Liftoff({
2015-05-09 13:58:18 -04:00
name: 'knex',
extensions: interpret.jsVariants,
v8flags: require('v8flags'),
moduleName: require('../package.json').name,
2015-05-09 13:58:18 -04:00
});
2020-04-19 00:40:23 +02:00
cli.on('require', function (name) {
console.log('Requiring external module', color.magenta(name));
2015-05-09 13:58:18 -04:00
});
2020-04-19 00:40:23 +02:00
cli.on('requireFail', function (name) {
console.log(color.red('Failed to load external module'), color.magenta(name));
2015-05-09 13:58:18 -04:00
});
// FYI: The handling for the `--cwd` and `--knexfile` arguments is a bit strange,
// but we decided to retain the behavior for backwards-compatibility. In
// particular: if `--knexfile` is a relative path, then it will be resolved
// relative to `--cwd` instead of the shell's CWD.
//
// So, the easiest way to replicate this behavior is to have the CLI change
// its CWD to `--cwd` immediately before initializing everything else. This
// ensures that Liftoff will then resolve the path to `--knexfile` correctly.
if (argv.cwd) {
process.chdir(argv.cwd);
}
cli.launch(
{
configPath: argv.knexfile,
require: argv.require,
completion: argv.completion,
},
invoke
);