-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
cli.js
executable file
·464 lines (424 loc) · 13.5 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#!/usr/bin/env node
const rechoir = require('rechoir');
const merge = require('lodash/merge');
const interpret = require('interpret');
const resolveFrom = require('resolve-from');
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 {
parseConfigObj,
mkConfigObj,
resolveEnvironmentConfig,
exit,
success,
checkLocalModule,
checkConfigurationOptions,
getMigrationExtension,
getSeedExtension,
getStubPath,
findUpModulePath,
findUpConfig,
} = require('./utils/cli-config-utils');
const {
existsSync,
readFile,
writeFile,
} = require('../lib/migrations/util/fs');
const { listMigrations } = require('./utils/migrationsLister');
async function openKnexfile(configPath) {
const importFile = require('../lib/migrations/util/import-file'); // require me late!
let config = await importFile(configPath);
if (config && config.default) {
config = config.default;
}
if (typeof config === 'function') {
config = await config();
}
return config;
}
async function initKnex(env, opts, useDefaultClientIfNotSpecified) {
checkLocalModule(env);
if (process.cwd() !== env.cwd) {
process.chdir(env.cwd);
console.log(
'Working directory changed to',
color.magenta(tildify(env.cwd))
);
}
if (!useDefaultClientIfNotSpecified) {
checkConfigurationOptions(env, opts);
}
env.configuration = env.configPath
? await openKnexfile(env.configPath)
: mkConfigObj(opts);
const resolvedConfig = resolveEnvironmentConfig(
opts,
env.configuration,
env.configPath
);
const optionsConfig = parseConfigObj(opts);
const config = merge(resolvedConfig, optionsConfig);
// Migrations directory gets defaulted if it is undefined.
if (!env.configPath && !config.migrations.directory) {
config.migrations.directory = null;
}
// Client gets defaulted if undefined and it's allowed
if (useDefaultClientIfNotSpecified && config.client === undefined) {
config.client = 'sqlite3';
}
const knex = require(env.modulePath);
return knex(config);
}
function invoke() {
const filetypes = ['js', 'coffee', 'ts', 'eg', 'ls'];
const cwd = argv.knexfile
? path.dirname(path.resolve(argv.knexfile))
: process.cwd();
// TODO add knexpath here eventually
const modulePath =
resolveFrom.silent(cwd, 'knex') ||
findUpModulePath(cwd, 'knex') ||
process.env.KNEX_PATH;
const configPath =
argv.knexfile && existsSync(argv.knexfile)
? path.resolve(argv.knexfile)
: findUpConfig(cwd, 'knexfile', filetypes);
if (configPath) {
const autoloads = rechoir.prepare(
interpret.jsVariants,
configPath,
cwd,
true
);
if (autoloads instanceof Error) {
// Only errors
autoloads.failures.forEach(function (failed) {
console.log(
color.red('Failed to load external module'),
color.magenta(failed.moduleName)
);
});
} else if (Array.isArray(autoloads)) {
const succeeded = autoloads[autoloads.length - 1];
console.log(
'Requiring external module',
color.magenta(succeeded.moduleName)
);
}
}
const env = {
cwd,
modulePath,
configPath,
configuration: null,
};
let modulePackage = {};
try {
modulePackage = require(path.join(
path.dirname(env.modulePath),
'package.json'
));
} catch (e) {}
const cliVersion = [
color.blue('Knex CLI version:'),
color.green(cliPkg.version),
].join(' ');
const localVersion = [
color.blue('Knex Local version:'),
color.green(modulePackage.version || 'None'),
].join(' ');
commander
.version(`${cliVersion}\n${localVersion}`)
.option('--debug', 'Run with debugging.')
.option('--knexfile [path]', 'Specify the knexfile path.')
.option('--knexpath [path]', 'Specify the path to knex instance.')
.option('--cwd [path]', 'Specify the working directory.')
.option('--client [name]', 'Set DB client.')
.option('--connection [address]', 'Set DB connection.')
.option('--migrations-directory [path]', 'Set migrations directory.')
.option('--migrations-table-name [path]', 'Set migrations table name.')
.option(
'--env [name]',
'environment, default: process.env.NODE_ENV || development'
)
.option('--esm', 'Enable ESM interop.')
.option('--specific [path]', 'Specify one seed file to execute.')
.option(
'--timestamp-filename-prefix',
'Enable a timestamp prefix on name of generated seed files.'
);
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();
if (filetypes.indexOf(type) === -1) {
exit(`Invalid filetype specified: ${type}`);
}
if (env.configuration) {
exit(`Error: ${env.knexfile} already exists`);
}
checkLocalModule(env);
const stubPath = `./knexfile.${type}`;
readFile(
path.dirname(env.modulePath) +
'/lib/migrations/migrate/stub/knexfile-' +
type +
'.stub'
)
.then((code) => {
return writeFile(stubPath, code);
})
.then(() => {
success(color.green(`Created ${stubPath}`));
})
.catch(exit);
});
commander
.command('migrate:make <name>')
.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();
const instance = await initKnex(env, opts, true); // Skip config check, we don't really care about client when creating migrations
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);
});
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);
});
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);
});
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]) => {
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);
});
commander
.command('migrate:currentVersion')
.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);
});
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);
});
commander
.command('seed:make <name>')
.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'
)
.option(
'--timestamp-filename-prefix',
'Enable a timestamp prefix on name of generated seed files.',
false
)
.action(async (name) => {
const opts = commander.opts();
const instance = await initKnex(env, opts, true); // Skip config check, we don't really care about client when creating seeds
const ext = getSeedExtension(env, opts);
const configOverrides = { extension: ext };
const stub = getStubPath('seeds', env, opts);
if (stub) {
configOverrides.stub = stub;
}
if (opts.timestampFilenamePrefix) {
configOverrides.timestampFilenamePrefix = opts.timestampFilenamePrefix;
}
instance.seed
.make(name, configOverrides)
.then((name) => {
success(color.green(`Created seed file: ${name}`));
})
.catch(exit);
});
commander
.command('seed:run')
.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);
});
commander.parse(process.argv);
}
// 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 path.resolve will then resolve the path to `--knexfile` correctly.
if (argv.cwd) {
process.chdir(argv.cwd);
}
// Initialize 'esm' before cli.launch
if (argv.esm) {
// enable esm interop via 'esm' module
// eslint-disable-next-line no-global-assign
require = require('esm')(module);
// https://github.com/standard-things/esm/issues/868
const ext = require.extensions['.js'];
require.extensions['.js'] = (m, fileName) => {
try {
// default to the original extension
// this fails if target file parent is of type='module'
return ext(m, fileName);
} catch (err) {
if (err && err.code === 'ERR_REQUIRE_ESM') {
return m._compile(
require('fs').readFileSync(fileName, 'utf8'),
fileName
);
}
throw err;
}
};
}
invoke();