-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp-manager.js
344 lines (310 loc) · 9.09 KB
/
app-manager.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
require('colors');
const fs = require('fs');
const readline = require('readline');
const pja = require('./personal-json-accessor');
const log = (obj) => console.log(obj);
const exists = (filePath) => {
try {
fs.statSync(filePath);
return true;
} catch (err) {
if (err.code === 'ENOENT') return false;
}
return false;
};
const modeNewDelegator = () => {
const yynOptions = () => ({
'': true,
y: true,
n: false,
});
const directoryNames = {
b: 'bookmarklets',
u: 'userscripts',
};
const answers = {
directory: '',
appFileName: '',
subDirectory: false,
subModule: false,
mockupTempula: false,
userscriptTempula: false,
};
const answerOptions = {
directory: {
b: 'b',
u: 'u',
},
subDirectory: yynOptions(),
subModule: yynOptions(),
mockupTempula: yynOptions(),
userscriptTempula: yynOptions(),
};
const toAppNamePath = (appFileName) =>
`./source/${directoryNames[answers.directory]}/${appFileName}`;
const toAppFilePath = (appFileName) => `${toAppNamePath(appFileName)}.js`;
const yynScenatio = ({ ask, myKey, nextKey }) => ({
ask: `${ask} (y)/n`,
valid: (answer) => {
if (Object.keys(answerOptions[myKey]).includes(answer.toLowerCase()))
return true;
log('Empty or requires y or n'.yellow);
return false;
},
nextKey,
});
const scenario = {
directory: {
ask: 'Which is type bookmarklet or userscript? b/u',
valid: (answer) => {
if (answerOptions.directory[answer.toLowerCase()]) return true;
log('Requires b or u.'.yellow);
return false;
},
nextKey: () => 'appFileName',
},
appFileName: {
ask: 'What file name is(without extension)?',
valid: (answer) => {
const filePath = toAppFilePath(answer);
if (!exists(filePath)) return true;
log(`Exists ${filePath}.`.yellow);
return false;
},
nextKey: () => 'subDirectory',
},
subDirectory: yynScenatio({
ask: 'Generate sub directory?',
myKey: 'subDirectory',
nextKey: () => (answers.subDirectory ? 'subModule' : 'mockupTempula'),
}),
subModule: yynScenatio({
ask: 'Generate sample sub module and import?',
myKey: 'subModule',
nextKey: () => 'mockupTempula',
}),
mockupTempula: yynScenatio({
ask: 'Generate mockup using tempula?',
myKey: 'mockupTempula',
nextKey: () =>
answers.directory === answerOptions.directory.b
? null
: 'userscriptTempula',
}),
userscriptTempula: yynScenatio({
ask: 'Generate doc.js using tempula?',
myKey: 'userscriptTempula',
nextKey: () => null,
}),
};
const reader = readline.createInterface({
input: process.stdin, // 標準入力
output: process.stdout, // 標準出力
});
let currentKey = 'directory';
const subFileName = 'sub';
const createFiles = () => {
const toFileBodyLogStatement = (...fileNames) =>
`console.log('${fileNames.join('.')}')`;
const appFileName = answers.appFileName;
const appFilePath = toAppFilePath(appFileName);
const appFileNameLogStatement = toFileBodyLogStatement(appFileName);
const appFileBodyLines = answers.subModule
? [
`import { ${subFileName} } from './${appFileName}/${subFileName}';`,
'',
`${appFileNameLogStatement};`,
`${subFileName}();`,
'',
]
: [`${appFileNameLogStatement};`, ''];
fs.writeFileSync(appFilePath, appFileBodyLines.join('\n'));
if (answers.subDirectory) {
const appNamePath = toAppNamePath(appFileName);
fs.mkdirSync(appNamePath);
if (answers.subModule) {
const subFileBodyLines = [
`export const ${subFileName} = () => ${toFileBodyLogStatement(
appFileName,
subFileName
)};`,
'',
`export default ${subFileName};`,
'',
];
fs.writeFileSync(
`${appNamePath}/${subFileName}.js`,
subFileBodyLines.join('\n')
);
}
}
if (answers.mockupTempula || answers.userscriptTempula) {
const projectRootPath = process.cwd();
const directoryName = directoryNames[answers.directory];
const replaceTempula = (templateFileName, outputFilePath) => {
const templateFilePath = `${projectRootPath}/.tempula/${templateFileName}`;
const src = fs.readFileSync(templateFilePath, 'utf-8');
const dst = src
.replace(/@file.?name@/gi, appFileName)
.replace(/@timestamp@/g, new Date().getTime());
fs.writeFileSync(outputFilePath, dst);
};
if (answers.mockupTempula) {
replaceTempula(
'mockup.html',
`./mockup/${directoryName}/${appFileName}.html`
);
}
if (answers.userscriptTempula) {
replaceTempula(
'userscript.doc.js',
`./source/${directoryName}/${appFileName}.doc.js`
);
}
}
};
// Enterキー押下で読み込み
reader.on('line', (line) => {
const current = scenario[currentKey];
const valid = current.valid;
if (valid && !valid(line)) {
log(current.ask.yellow);
reader.prompt();
return;
}
const answerOption = answerOptions[currentKey];
answers[currentKey] = answerOption ? answerOption[line] : line;
// log(answers);
const nextKey = current.nextKey();
if (!nextKey) {
createFiles();
log('generated.'.green);
process.exit(0);
}
const next = scenario[nextKey];
currentKey = nextKey;
log(next.ask.cyan);
reader.prompt();
});
// ctrl+Cで終了
reader.on('close', () => {
log('canceled.'.yellow);
});
// コマンドプロンプトを表示
const current = scenario[currentKey];
log(current.ask.cyan);
reader.prompt();
};
const getAppModuleNames = () => {
const expects = ['_util'];
const source = 'source';
const directories = fs.readdirSync(source);
const list = [];
directories
.filter((directory) => !expects.includes(directory))
.forEach((directory) => {
fs.readdirSync(`${source}/${directory}`)
.filter((name) => name.match(/\..+$/) && !name.match(/\.doc\.js$/))
.map((name) => name.replace(/\..+$/, ''))
.forEach((name) => list.push(`${directory}/${name}`));
});
return list;
};
const literals = {
specifiedAppNames: 'specified app names -> ',
};
const storeAppNames = (appNames) => {
const personalJson = pja.get();
personalJson.appNames = appNames;
pja.put(personalJson);
};
const getAppNamesStored = () => pja.get().appNames || [];
const abort = (...messages) => {
log('Error: '.white.bgRed);
messages.forEach((message) => log(message.white.bgRed));
process.exit(0);
};
const addSet = () => {
const core = (doingText) => (storeFunc) => {
const args = process.argv.filter((arg, i) => i > 2);
if (args.length === 0) abort('specify app names.');
log(`${doingText} app names -> `.cyan);
args.forEach((arg) => log(arg.green));
log();
log('existing app names -> '.cyan);
const appModuleNames = getAppModuleNames();
appModuleNames.forEach((appName) => log(appName));
log();
const invalids = args.filter((arg) => !appModuleNames.includes(arg));
if (invalids.length > 0) abort('invalid app names -> ', ...invalids);
const storedAppNames = storeFunc(args);
log(literals.specifiedAppNames.cyan);
storedAppNames.forEach((appName) => log(appName.green));
log();
log(`done ${doingText} app names.`.green);
};
return {
add: core('adding'),
set: core('setting'),
};
};
const modeNew = () => {
modeNewDelegator();
};
const modeNow = () => {
const appNames = getAppNamesStored();
if (appNames.length > 0) {
log(literals.specifiedAppNames.cyan);
log(appNames.join(' ').green);
process.exit(0);
}
log('nothing specified app names.'.yellow);
log('specify app names below using npm run app:set'.yellow);
const appModuleNames = getAppModuleNames();
log(appModuleNames.join(' ').yellow);
};
const modeAdd = () => {
addSet().add((args) => {
const appNames = getAppNamesStored();
args
.filter((adding) => !appNames.includes(adding))
.forEach((adding) => appNames.push(adding));
storeAppNames(appNames);
return appNames;
});
};
const modeSet = () => {
addSet().set((args) => {
storeAppNames(args);
return args;
});
};
const modeHas = () => {
const appModuleNames = getAppModuleNames();
log(appModuleNames.join(' ').magenta);
};
const modeFuncs = {
new: modeNew, // new は関数名に使えない予約語なので、そこに合わせてmodeつけた
now: modeNow,
add: modeAdd,
set: modeSet,
has: modeHas,
};
const argToMode = (arg) => {
const modes = Object.keys(modeFuncs);
const exit = () => {
log('app-manager'.magenta);
abort(`Error: Pass arg one of [${modes.join(', ')}].`);
};
if (!arg) exit();
const mode = arg.replace(/^-+/, '');
if (!modes.includes(mode)) exit();
return mode;
};
const main = () => {
const arg = process.argv[2];
const mode = argToMode(arg);
log(`app-manager[${mode}]`.magenta);
modeFuncs[mode]();
};
main();