UNPKG

5.58 kBJavaScriptView Raw
1#!/usr/bin/env node
2"use strict";
3Object.defineProperty(exports, "__esModule", { value: true });
4const cac = require("cac");
5const fs_1 = require("./fs");
6const pathLib = require("path");
7const logger_1 = require("./logger");
8const utils_1 = require("./utils");
9const task_manager_1 = require("./task-manager");
10const defaultCli = cac();
11let defaultArgv = [];
12let taskArgv = [];
13{
14 const argv = process.argv.slice(2);
15 const defaultOptions = new Map([
16 ['--config', 1],
17 ['-c', 1],
18 ['--require', 1],
19 ['-r', 1],
20 ['--init', 1],
21 ['-i', 1],
22 ]);
23 let i = 0;
24 for (i = 0; i < argv.length; i++) {
25 const arg = argv[i];
26 let valLen = defaultOptions.get(arg);
27 if (utils_1.Is.defed(valLen)) {
28 let end = i + valLen;
29 defaultArgv.push(...argv.slice(i, end + 1));
30 i = end;
31 }
32 else {
33 break;
34 }
35 }
36 taskArgv = argv.slice(i);
37}
38defaultArgv = process.argv.slice(0, 2).concat(defaultArgv);
39taskArgv = process.argv.slice(0, 2).concat(taskArgv);
40function addDefaultOptions(cli) {
41 return cli
42 .option(`--config, -c <...files>`, 'The Foyfiles')
43 .option(`--require, -r <...names>`, 'Require the given modules')
44 .option(`--init, -i [ext]`, 'Generate the Foyfile, [ext] can be "ts" | "js", default is "js"');
45}
46addDefaultOptions(defaultCli)
47 .parse(defaultArgv);
48if (defaultCli.options.init) {
49 let ext = defaultCli.options.init;
50 if (!utils_1.Is.str(ext)) {
51 ext = 'js';
52 }
53 ext = ext.replace(/^\./, '');
54 const file = `./Foyfile.${ext}`;
55 if (fs_1.fs.existsSync(file)) {
56 throw new Error(`Foyfile already exists: ${pathLib.resolve(file)}`);
57 }
58 fs_1.fs.writeFileSync(file, `${ext === 'js'
59 ? `const { task, desc, option, fs } = require('foy')`
60 : `import { task, desc, option, fs } from 'foy'`}
61
62task('build', async ctx => {
63 // Your build tasks
64 await ctx.exec('tsc')
65})
66
67`);
68 process.exit();
69}
70let foyFiles = arrify(defaultCli.options.config);
71let registers = arrify(defaultCli.options.require);
72function arrify(arr) {
73 if (!Array.isArray(arr)) {
74 return arr == null ? [] : [arr];
75 }
76 return arr;
77}
78if (foyFiles.length) {
79 foyFiles = foyFiles.map(c => pathLib.resolve(process.cwd(), c));
80}
81else {
82 let findFoyfiles = (baseDir) => {
83 let cwdFoyfiles = fs_1.fs.readdirSync(baseDir).filter(f => f.startsWith('Foyfile.'));
84 if (cwdFoyfiles.length) {
85 if (cwdFoyfiles.length > 1) {
86 logger_1.logger.warn(`Find more than 1 Foyfile in current directory, only first one will be used: \n${cwdFoyfiles.join('\n')}`);
87 }
88 foyFiles = [pathLib.join(baseDir, cwdFoyfiles[0])];
89 }
90 };
91 findFoyfiles(process.cwd());
92 if (!foyFiles.length) {
93 let maxDepth = 5;
94 let dir = process.cwd();
95 while (maxDepth-- && dir !== '/' && dir && !foyFiles.length) {
96 dir = pathLib.dirname(dir);
97 findFoyfiles(dir);
98 }
99 }
100}
101for (const file of foyFiles) {
102 if (!fs_1.fs.existsSync(file)) {
103 throw new TypeError(`Cannot find Foyfile: ${file}`);
104 }
105}
106if (registers.length) {
107 for (const mod of registers) {
108 require(mod);
109 }
110}
111try {
112 if (!require.extensions['.ts']) {
113 require('ts-node/register');
114 }
115}
116catch (error) {
117 // ignore
118}
119{ // Add global installed foy to module.paths
120 const Module = require('module');
121 const nodeModulePaths = Module._nodeModulePaths;
122 const globalFoyPath = pathLib.join(__dirname, '..', '..');
123 if (nodeModulePaths) {
124 Module._nodeModulePaths = (...args) => {
125 let paths = nodeModulePaths.apply(Module, args);
126 if (Array.isArray(paths)) {
127 paths.push(globalFoyPath);
128 }
129 return paths;
130 };
131 }
132}
133for (const file of foyFiles) {
134 require(file);
135}
136const taskCli = cac();
137let taskManager = task_manager_1.getGlobalTaskManager();
138taskManager.getTasks().forEach(t => {
139 let strict = taskManager.globalOptions.strict || t.strict;
140 let cmd = taskCli
141 .command(t.name, t.desc, { allowUnknownOptions: !strict });
142 if (t.optionDefs) {
143 t.optionDefs.forEach(def => cmd.option(...def));
144 }
145 cmd.action((...args) => {
146 let options = args.pop();
147 taskManager.globalOptions.rawArgs = taskCli.rawArgs;
148 taskManager.globalOptions.options = options;
149 taskManager.run(t.name, {
150 options,
151 rawArgs: taskCli.rawArgs.slice(3),
152 });
153 });
154});
155taskCli.on('command:*', () => {
156 console.error(`error: Unknown command \`${taskCli.args.join(' ')}\`\n\n`);
157 process.exit(1);
158});
159taskCli.help(sections => {
160 if (!taskCli.matchedCommand) {
161 let last = sections[sections.length - 1];
162 let lines = last.body.split('\n');
163 lines.pop();
164 last.body =
165 lines.concat(' -h, --help Display this message', ' --init, -i [ext] Generate the Foyfile, <ext> can be "ts" | "js", default is "js"', ' --config, -c <...files> The Foyfiles', ' --require, -r <...names> Require the given modules')
166 .join('\n');
167 }
168 console.log(sections
169 .map(section => {
170 return section.title
171 ? `${section.title}:\n${section.body}`
172 : section.body;
173 })
174 .join('\n\n'));
175 process.exit(0);
176});
177taskCli.parse(taskArgv);
178if (process.argv.length === 2) {
179 taskCli.outputHelp();
180}
181//# sourceMappingURL=cli.js.map
\No newline at end of file