-
Notifications
You must be signed in to change notification settings - Fork 2
/
cli
executable file
·355 lines (313 loc) · 10.3 KB
/
cli
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
#!/usr/bin/env node
const userDirectory = process.cwd();
const fs = require('fs');
const cpp = require('child-process-promise');
const copy = require('recursive-copy');
const rimraf = require('rimraf');
const tmp = require('tmp');
const path = require('path');
const modulePath = require('npm-module-path');
const which = require('npm-which')(userDirectory);
const unique = require('array-unique').immutable;
const state = {
inModuleDir : false,
ielmModulePath: undefined,
runLocally: false,
commandToRun: 'run',
ielmUserPath: undefined
};
if (process.argv && process.argv.length) {
process.argv.forEach((arg) => {
if ((arg === 'build') ||
(arg === 'run') ||
(arg === 'clean-run') ||
(arg === 'run-dev') ||
(arg === 'clean-run-dev') ||
(arg === 'test')) {
state.commandToRun = arg;
};
if (arg === 'local') {
state.runLocally = true;
}
if (arg.startsWith('path=')) {
state.ielmUserPath = arg.substring(5);
}
})
}
const outputDir = state.runLocally ? `${userDirectory}/output` : tmp.dirSync().name;
console.log(`:: ${state.commandToRun}`);
const serverDir = 'src/server';
const npmBinLocalDir = `${userDirectory}/node_modules/.bin`;
const ielmBinary = 'ielm.js';
const componentsDir = `${serverDir}/Component`;
const serverScript = `${serverDir}/server.js`;
const simpleHttpServerBin = state.runLocally
? `${npmBinLocalDir}/node-simplehttpserver`
: getModulePath('node-simplehttpserver');
const simpleHttpServerPort = 8080;
const webpackDevServerBin = state.runLocally
? `${npmBinLocalDir}/webpack-dev-server`
: getModulePath('webpack-dev-server');
const elmPackageSource = `${serverDir}/elm-package.sample.json`;
const elmPackageDest = `${outputDir}/elm-package.json`;
const componentsDest = `${outputDir}/Component`;
const elmStuffDest = `${outputDir}/elm-stuff`;
const iElmJsDest = `${outputDir}/ielm.js`;
const iElmHtmlDest = `${outputDir}/index.html`;
function build() {
// webpack
return goToModuleDir()
.then(() => execInPromise('webpack'))
.then(goBackToOriginalDir)
.catch(reportError);
}
function run() {
return goToModuleDir()
.then(buildIfNotExists)
.then(createOutputDir)
.then(copyComponents)
.then(copyElmPackage)
.then(copyIElmStaticFiles)
.then(goBackToOriginalDir)
.then(copyElmStuff)
.then(() => chdirInPromise(state.ielmModulePath))
.then(() => { startServer(); return null; })
.then(() => chdirInPromise(outputDir))
.then(installPackages)
.then(() => startClient())
.catch(reportError);
}
function cleanRun() {
return goToModuleDir()
.then(cleanOutput)
.then(run)
.catch(reportError);
}
function runDev() {
return goToModuleDir()
.then(createOutputDir)
.then(copyComponents)
.then(copyElmPackage)
.then(() => chdirInPromise(outputDir))
.then(installPackages)
.then(goBackToOriginalDir)
.then(() => {
return Promise.all([ startServer(), startDevClient() ]);
})
.catch(reportError);
}
function cleanRunDev() {
return goToModuleDir()
.then(cleanOutput)
.then(runDev)
.catch(reportError);
}
function test() {
throw new Error("Error: no test specified");
}
function goToModuleDir() {
return chdirInPromise(state.ielmModulePath);
}
function goBackToOriginalDir() {
return chdirInPromise(userDirectory);
}
function createOutputDir() {
// mkdir ./output
return logAs(`create output directory ${outputDir}`)
.then(() => new Promise((resolve, reject) => {
try {
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
resolve();
} catch(e) {
reject(e);
}
}));
}
function cleanOutput() {
// rm -Rf ./output
return rimrafInPromise(outputDir);
}
function copyComponents() {
// cp -R ./src/server/Component ./output
return logAs('copy components')
.then(() =>
copy(`${state.ielmModulePath}/${componentsDir}`,
componentsDest, { overwrite: true })
);
}
function copyElmStuff() {
// cp -R ./elm-stuff ./output
return logAs('copy elm-stuff')
.then(() => new Promise((resolve, reject) => {
if (!state.runLocally && fs.existsSync('./elm-stuff')) {
copy('./elm-stuff', elmStuffDest, { overwrite: true }).then(resolve);
} else {
resolve();
}
}));
}
function copyIElmStaticFiles() {
// cp ./ielm.js ./output
// cp ./index.html ./output
return logAs('copy ielm.js & ielm.html')
.then(() => new Promise((resolve, reject) => {
const iElmJsSrc = `${state.ielmModulePath}/ielm.js`;
const iElmHtmlSrc = `${state.ielmModulePath}/index.html`;
if (fs.existsSync(iElmJsSrc) && fs.existsSync(iElmHtmlSrc)) {
copy(iElmJsSrc, iElmJsDest, { overwrite: true })
.then(() => copy(iElmHtmlSrc, iElmHtmlDest, { overwrite: true }))
.then(resolve);
} else {
resolve();
}
}));
}
function copyElmPackage() {
// cp ./src/server/elm-package.sample.json ./output/elm-package.json
return logAs('copy elm-package.json').then(new Promise((resolve, reject) => {
const sample = require(`./${elmPackageSource}`);
if (!sample['source-directories']) sample['source-directories'] = [];
sample['source-directories'] = sample['source-directories'].map((relPath) => {
return path.resolve(relPath);
});
sample['source-directories'].push('.');
sample['source-directories'].push(userDirectory);
sample['source-directories'] = unique(sample['source-directories']);
let sourceDependencies = sample.dependencies;
let userDependencies = {};
try {
userDependencies = require(`${userDirectory}/elm-package.json`).dependencies || {};
} catch(e) {}
Object.keys(userDependencies).forEach((dependencyName) => {
sourceDependencies[dependencyName] = userDependencies[dependencyName];
});
fs.writeFile(elmPackageDest, JSON.stringify(sample, null, '\t'), 'utf8', (err) => {
if (!err) {
resolve();
} else {
reject(err);
}
});
}));
}
function installPackages() {
// cd ./output && elm-package install --yes && cd ..
return logAs('install Elm packages')
.then(() => {
return execInPromise('elm-package', [ 'install', '--yes' ])
});
}
function startServer() {
// node ./src/server/server.js
return logAs('start server at http://localhost:3000')
.then(() => execInPromise('node',
[ `${state.ielmModulePath}/${serverScript}`, `--path=${outputDir}` ]));
}
function startClient() {
// ./node_modules/.bin/node-simplehttpserver . 8080
return logAs('start client at http://localhost:8080')
.then(() => execInPromise(simpleHttpServerBin, [ outputDir, simpleHttpServerPort ]));
}
function startDevClient() {
// ./node_modules/.bin/webpack-dev-server
return logAs('start development client at http://localhost:8080.')
.then(() => execInPromise(webpackDevServerBin));
}
function buildIfNotExists() {
return new Promise((resolve, reject) => {
try {
if (!fs.existsSync(`${outputDir}/${ielmBinary}`)) {
resolve(build());
}
resolve();
} catch(e) {
reject(e);
}
});
}
function execInPromise(command, args) {
//console.log(`:: execute '${command}' with arguments: '${args}'.`);
const promise = cpp.spawn(command, args || []);
const childProcess = promise.childProcess;
childProcess.stdout.on('data', function (data) {
//console.log(`${command} :: ${data.toString()}`);
});
childProcess.stderr.on('data', function (data) {
console.log(`${command} error :: ${data.toString()}`);
});
return promise;
}
function chdirInPromise(path) {
return new Promise((resolve, reject) => {
try {
//console.log(`:: change directory to '${path}'.`);
//console.log(process.cwd());
process.chdir(path);
resolve();
} catch(e) {
reject(e);
}
});
}
function rimrafInPromise(path) {
return new Promise((resolve, reject) => {
console.log(`:: clean '${path}'.`);
rimraf(path, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
function logAs(string) {
return new Promise((resolve, reject) => {
console.log(`:: ${string}.`);
resolve();
});
}
function reportError(err) {
console.error(`xx Error: ${err}`);
}
function getModulePath(moduleName) {
try {
return which.sync(moduleName);
} catch(e) {
return moduleName;
}
}
function runCommand(commandToRun) {
if (commandToRun === 'build') {
build();
} else if (commandToRun === 'run') {
run();
} else if (commandToRun === 'clean-run') {
cleanRun();
} else if (commandToRun === 'run-dev') {
runDev();
} else if (commandToRun === 'clean-run-dev') {
cleanRunDev();
} else if (commandToRun === 'test') {
test();
}
}
if (state.runLocally || state.ielmUserPath) {
state.ielmModulePath = state.ielmUserPath || './';
console.log(`:: iElm module path: ${state.ielmModulePath}.`);
runCommand(state.commandToRun);
} else {
modulePath.resolveOne('ielm').then((ielmModulePath) => {
state.ielmModulePath =
ielmModulePath.startsWith('/') ? ielmModulePath : `${process.cwd()}/${ielmModulePath}`;
if (!ielmModulePath) {
return Promise.reject('iElm module path was not found. Ensure iElm is installed (globally or locally, no matter) or provide custom path with `path=` argument');
}
console.log(`:: iElm module path: ${state.ielmModulePath}`);
runCommand(state.commandToRun);
}).catch((err) => {
reportError(err);
});
}