lincd-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js ADDED
@@ -0,0 +1,1238 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
+ return new (P || (P = Promise))(function (resolve, reject) {
6
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10
+ });
11
+ };
12
+ var __generator = (this && this.__generator) || function (thisArg, body) {
13
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
14
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
15
+ function verb(n) { return function (v) { return step([n, v]); }; }
16
+ function step(op) {
17
+ if (f) throw new TypeError("Generator is already executing.");
18
+ while (_) try {
19
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
20
+ if (y = 0, t) op = [op[0] & 2, t.value];
21
+ switch (op[0]) {
22
+ case 0: case 1: t = op; break;
23
+ case 4: _.label++; return { value: op[1], done: false };
24
+ case 5: _.label++; y = op[1]; op = [0]; continue;
25
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
26
+ default:
27
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
28
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
29
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
30
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
31
+ if (t[2]) _.ops.pop();
32
+ _.trys.pop(); continue;
33
+ }
34
+ op = body.call(thisArg, _);
35
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
36
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
37
+ }
38
+ };
39
+ exports.__esModule = true;
40
+ var lib_1 = require("lincd/lib");
41
+ var JSONLDWriter_1 = require("lincd-jsonld/lib/JSONLDWriter");
42
+ var program = require('commander');
43
+ var exec = require('child_process').exec;
44
+ var chalk = require('chalk');
45
+ var fs = require('fs-extra');
46
+ var path = require('path');
47
+ var glob = require('glob');
48
+ var variables = {};
49
+ function log() {
50
+ var messages = [];
51
+ for (var _i = 0; _i < arguments.length; _i++) {
52
+ messages[_i] = arguments[_i];
53
+ }
54
+ messages.forEach(function (message) {
55
+ console.log(chalk.cyan(message));
56
+ });
57
+ }
58
+ function warn() {
59
+ var messages = [];
60
+ for (var _i = 0; _i < arguments.length; _i++) {
61
+ messages[_i] = arguments[_i];
62
+ }
63
+ messages.forEach(function (message) {
64
+ console.log(message);
65
+ // console.log(chalk.red(message));
66
+ });
67
+ }
68
+ function checkModulePath(modulePath, res) {
69
+ var packagePath = path.join(modulePath, 'package.json');
70
+ if (fs.existsSync(packagePath)) {
71
+ var pack = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
72
+ if (pack && pack.lincd === true) {
73
+ res.push({
74
+ path: modulePath,
75
+ moduleName: pack.name,
76
+ packageName: pack.name
77
+ });
78
+ }
79
+ }
80
+ }
81
+ /**
82
+ * Returns a map of the modules that this repository manages (so no modules found through the workspaces who's path contains ../ )
83
+ * @param rootPath
84
+ */
85
+ function getLocalLincdModuleMap(rootPath) {
86
+ if (rootPath === void 0) { rootPath = './'; }
87
+ var map = new Map();
88
+ getLincdModules(rootPath).forEach(function (module) {
89
+ if (module.path.indexOf('../') === -1 &&
90
+ module.path.indexOf('..\\') === -1) {
91
+ // console.log(module.path);
92
+ map.set(module.moduleName, module);
93
+ }
94
+ });
95
+ return map;
96
+ }
97
+ function getLocalLincdModules(rootPath) {
98
+ if (rootPath === void 0) { rootPath = './'; }
99
+ return getLincdModules(rootPath).filter(function (module) {
100
+ return module.path.indexOf('..\\') === -1;
101
+ });
102
+ }
103
+ function getLincdModules(rootPath) {
104
+ if (rootPath === void 0) { rootPath = './'; }
105
+ //TODO: read from package.json what the workspaces are. for each, follow up all the folders inside that path
106
+ //TODO: then return an array with objects that have both the module name + the path. And then use that path across this whenever this function is called
107
+ //TODO: this way it will work with websites as well, instead of just from the main LINCD repository
108
+ var pack = getPackageJSON();
109
+ var res = [];
110
+ if (!pack.workspaces) {
111
+ warn(chalk.red('Could not find package workspaces. Make sure you run this command from a yarn workspace.'));
112
+ logHelp();
113
+ process.exit();
114
+ }
115
+ //TODO: filter with package.lincd = true?
116
+ pack.workspaces.forEach(function (workspace) {
117
+ var workspacePath = path.join(rootPath, workspace.replace('/*', ''));
118
+ if (workspace.indexOf('/*') !== -1) {
119
+ // console.log(workspacePath);
120
+ if (fs.existsSync(workspacePath)) {
121
+ var folders = fs.readdirSync(workspacePath);
122
+ folders.forEach(function (folder) {
123
+ if (folder !== './' && folder !== '../') {
124
+ checkModulePath(path.join(workspacePath, folder), res);
125
+ }
126
+ });
127
+ }
128
+ }
129
+ else {
130
+ checkModulePath(workspacePath, res);
131
+ }
132
+ });
133
+ // console.log(res);
134
+ return res;
135
+ }
136
+ function setVariable(name, replacement) {
137
+ //prepare name for regexp
138
+ name = name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
139
+ variables[name] = replacement;
140
+ }
141
+ function execp(cmd, log, allowError, options) {
142
+ if (log === void 0) { log = false; }
143
+ if (allowError === void 0) { allowError = false; }
144
+ if (options === void 0) { options = {}; }
145
+ // opts || (opts = {});
146
+ if (log)
147
+ console.log(chalk.cyan(cmd));
148
+ return new Promise(function (resolve, reject) {
149
+ var child = exec(cmd, options);
150
+ child.stdout.pipe(process.stdout);
151
+ child.stderr.pipe(process.stderr);
152
+ // process.stdin.pipe(child.stdin);
153
+ child.on('close', function (code) {
154
+ if (code === 0) {
155
+ resolve(null);
156
+ }
157
+ else {
158
+ reject();
159
+ }
160
+ // console.log('killing child');
161
+ // child.kill('SIGHUP');
162
+ // resolve(code);
163
+ });
164
+ // child.on('data', function (result) {
165
+ // // if (log)
166
+ // // {
167
+ // // console.log(result);
168
+ // // }
169
+ // resolve(result);
170
+ // console.log('resolve data');
171
+ //
172
+ // });
173
+ child.on('error', function (err) {
174
+ if (!allowError) {
175
+ // console.log('reject err');
176
+ reject(err);
177
+ return;
178
+ }
179
+ else if (log) {
180
+ console.warn(err);
181
+ }
182
+ // console.log('resolve err');
183
+ resolve(null);
184
+ });
185
+ child.on('exit', function (code, signal) {
186
+ if (code !== 0) {
187
+ reject('Child process exited with error code ' + code);
188
+ return;
189
+ }
190
+ // console.log('resolve exit');
191
+ resolve(null);
192
+ });
193
+ });
194
+ }
195
+ function replaceVariables(string) {
196
+ for (var key in variables) {
197
+ string = string.replace(new RegExp(key, 'g'), variables[key]);
198
+ }
199
+ return string;
200
+ }
201
+ function execPromise(command, log, allowError, options) {
202
+ if (log === void 0) { log = false; }
203
+ if (allowError === void 0) { allowError = false; }
204
+ return new Promise(function (resolve, reject) {
205
+ if (log)
206
+ console.log(chalk.cyan(command));
207
+ exec(command, options, function (error, stdout, stderr) {
208
+ if (error) {
209
+ if (!allowError) {
210
+ reject(error.message);
211
+ return;
212
+ }
213
+ else if (log) {
214
+ console.warn(error);
215
+ }
216
+ }
217
+ var result = stdout.trim();
218
+ if (log) {
219
+ // console.log(chalk"RESOLVING "+command);
220
+ console.log(result);
221
+ // console.log('ERRORS:'+(result.indexOf('Aborted due to warnings') !== -1));
222
+ // console.log('stderr:'+stderr);
223
+ }
224
+ resolve(result);
225
+ });
226
+ });
227
+ }
228
+ var updateFile = function (filePath) { return __awaiter(void 0, void 0, void 0, function () {
229
+ var fileContent, newContent;
230
+ return __generator(this, function (_a) {
231
+ switch (_a.label) {
232
+ case 0: return [4 /*yield*/, fs.readFile(filePath, 'utf8')];
233
+ case 1:
234
+ fileContent = _a.sent();
235
+ newContent = replaceCurlyVariables(fileContent);
236
+ return [2 /*return*/, fs.writeFile(filePath, newContent)];
237
+ }
238
+ });
239
+ }); };
240
+ var replaceCurlyVariables = function (string) {
241
+ // var reg = new RegExp('\\$\\{'+key+'\\}','g');
242
+ for (var key in variables) {
243
+ string = string.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), variables[key]);
244
+ }
245
+ return string;
246
+ };
247
+ var capitalize = function (str) {
248
+ return str.charAt(0).toUpperCase() + str.toLowerCase().slice(1);
249
+ };
250
+ var camelCase = function (str) {
251
+ var string = str
252
+ .toLowerCase()
253
+ .replace(/[^A-Za-z0-9]/g, ' ')
254
+ .split(' ')
255
+ .reduce(function (result, word) { return result + capitalize(word.toLowerCase()); });
256
+ return string.charAt(0).toLowerCase() + string.slice(1);
257
+ };
258
+ // program.command('init [name] [uribase]').action((name, uriBase) => {
259
+ // return initModule(name, uriBase);
260
+ // });
261
+ /*const initModule = (
262
+ name,
263
+ uriBase,
264
+ basePath = process.cwd(),
265
+ defaultModule = false,
266
+ ) => {
267
+ let pack;
268
+ if (!fs.existsSync(path.join(basePath, 'package.json'))) {
269
+ if (name) {
270
+ pack = require('./defaults/package.json');
271
+ pack.name = name;
272
+ fs.writeFileSync(
273
+ path.join(basePath, 'package.json'),
274
+ JSON.stringify(pack, null, 2),
275
+ );
276
+ } else {
277
+ log(
278
+ 'either provide a name as argument, or first run `npm init` and then run lincd init again',
279
+ );
280
+ process.exit();
281
+ }
282
+ } else {
283
+ pack = require(path.join(basePath, 'package.json'));
284
+ }
285
+ if (!uriBase) {
286
+ uriBase = '[INSERT_URI_BASE]';
287
+ }
288
+ var moduleName = pack.name;
289
+
290
+ let camelCaseModuleName = camelCase(moduleName); //some-module --> someModule
291
+ let underscoreModuleName = moduleName.replace(/[-\s]+/g, '_');
292
+
293
+ setVariable('uri_base', uriBase);
294
+ //longer similar variables names should come before the shorter ones
295
+ setVariable('camel_module_name', camelCaseModuleName);
296
+ setVariable('underscore_module_name', underscoreModuleName);
297
+ setVariable('module_name', moduleName);
298
+ setVariable('camel_ontology_name', camelCaseModuleName);
299
+ setVariable('underscore_ontology_name', underscoreModuleName);
300
+ setVariable('ontology_name', moduleName);
301
+
302
+ // log('setting up files for module ' + moduleName+ ' from '+process.cwd());
303
+ // log('remember to add this module to the package.json main workspace')
304
+
305
+ log('Creating new module at ' + basePath);
306
+
307
+ return new Promise<void>((resolve, reject) => {
308
+ if (!fs.existsSync(path.join(basePath, 'tsconfig.json'))) {
309
+ var tsConfigEs6Default = fs.readFileSync(
310
+ path.join(__dirname, 'defaults', 'tsconfig.json'),
311
+ );
312
+ fs.writeFileSync(
313
+ path.join(basePath, 'tsconfig.json'),
314
+ tsConfigEs6Default,
315
+ );
316
+ }
317
+ if (!fs.existsSync(path.join(basePath, 'tsconfig-es5.json'))) {
318
+ var tsConfigEs5Default = fs.readFileSync(
319
+ path.join(__dirname, 'defaults', 'tsconfig-es5.json'),
320
+ );
321
+ fs.writeFileSync(
322
+ path.join(basePath, 'tsconfig-es5.json'),
323
+ tsConfigEs5Default,
324
+ );
325
+ }
326
+ if (!fs.existsSync(path.join(basePath, '.gitignore'))) {
327
+ var gitIgnore = fs.readFileSync(
328
+ path.join(__dirname, 'defaults', 'gitignorefile'),
329
+ {encoding: 'utf-8'},
330
+ );
331
+ fs.writeFileSync(path.join(basePath, '.gitignore'), gitIgnore);
332
+ }
333
+ if (!fs.existsSync(path.join(basePath, '.npmignore'))) {
334
+ var npmIgnore = fs.readFileSync(
335
+ path.join(__dirname, 'defaults', '.npmignore'),
336
+ {encoding: 'utf-8'},
337
+ );
338
+ fs.writeFileSync(path.join(basePath, '.npmignore'), npmIgnore);
339
+ }
340
+ if (!fs.existsSync(path.join(basePath, 'Gruntfile.js'))) {
341
+ var gruntFile = replaceCurlyVariables(
342
+ fs.readFileSync(path.join(__dirname, 'defaults', 'Gruntfile.js'), {
343
+ encoding: 'utf-8',
344
+ }),
345
+ );
346
+ fs.writeFileSync(path.join(basePath, 'Gruntfile.js'), gruntFile);
347
+ }
348
+
349
+ if (!fs.existsSync(path.join(basePath, 'src'))) {
350
+ fs.mkdirSync(path.join(basePath, 'src'));
351
+ fs.mkdirSync(path.join(basePath, 'src', 'ontologies'));
352
+ fs.mkdirSync(path.join(basePath, 'src', 'shapes'));
353
+ fs.mkdirSync(path.join(basePath, 'src', 'views'));
354
+ fs.mkdirSync(path.join(basePath, 'data'));
355
+ fs.mkdirSync(path.join(basePath, 'data', 'ontologies'));
356
+ fs.writeFileSync(
357
+ path.join(basePath, 'src', 'index.ts'),
358
+ replaceCurlyVariables(
359
+ fs.readFileSync(
360
+ defaultModule
361
+ ? path.join(__dirname, 'defaults', 'defaultModule', 'index.ts')
362
+ : path.join(__dirname, 'defaults', 'index.ts'),
363
+ {encoding: 'utf-8'},
364
+ ),
365
+ ),
366
+ );
367
+
368
+ fs.writeFileSync(
369
+ path.join(basePath, 'src', 'ontologies', moduleName + '.ts'),
370
+ replaceCurlyVariables(
371
+ fs.readFileSync(
372
+ defaultModule
373
+ ? path.join(__dirname, 'defaults', 'defaultModule', 'ontology.ts')
374
+ : path.join(__dirname, 'defaults', 'ontology.ts'),
375
+ {encoding: 'utf-8'},
376
+ ),
377
+ ),
378
+ );
379
+ }
380
+
381
+ if (defaultModule) {
382
+ if (!fs.existsSync(path.join(basePath, 'data', 'data.json'))) {
383
+ var moduleData = replaceCurlyVariables(
384
+ fs.readFileSync(
385
+ path.join(__dirname, 'defaults', 'defaultModule', 'data.json'),
386
+ {encoding: 'utf-8'},
387
+ ),
388
+ );
389
+ fs.writeFileSync(path.join(basePath, 'data', 'data.json'), moduleData);
390
+ }
391
+ if (
392
+ !fs.existsSync(
393
+ path.join(
394
+ basePath,
395
+ 'data',
396
+ 'ontologies',
397
+ camelCaseModuleName + '.json',
398
+ ),
399
+ )
400
+ ) {
401
+ let ontologyData = replaceCurlyVariables(
402
+ fs.readFileSync(
403
+ path.join(
404
+ __dirname,
405
+ 'defaults',
406
+ 'defaultModule',
407
+ 'defaultOntology.json',
408
+ ),
409
+ {encoding: 'utf-8'},
410
+ ),
411
+ );
412
+ fs.writeFileSync(
413
+ path.join(
414
+ basePath,
415
+ 'data',
416
+ 'ontologies',
417
+ camelCaseModuleName + '.json',
418
+ ),
419
+ ontologyData,
420
+ );
421
+ }
422
+ let indexView = replaceCurlyVariables(
423
+ fs.readFileSync(
424
+ path.join(__dirname, 'defaults', 'defaultModule', 'Index.tsx'),
425
+ {encoding: 'utf-8'},
426
+ ),
427
+ );
428
+ fs.writeFileSync(
429
+ path.join(basePath, 'src', 'views', 'Index.tsx'),
430
+ indexView,
431
+ );
432
+
433
+ let indexSCSS = fs.readFileSync(
434
+ path.join(__dirname, 'defaults', 'defaultModule', 'Index.scss'),
435
+ {encoding: 'utf-8'},
436
+ );
437
+ fs.writeFileSync(
438
+ path.join(basePath, 'src', 'views', 'Index.scss'),
439
+ indexSCSS,
440
+ );
441
+ }
442
+
443
+ resolve();
444
+ }).catch((e) => {
445
+ console.warn('Could not complete setup: ' + e);
446
+ });
447
+ };*/
448
+ var getNextVersion = function (version) {
449
+ var parts = version.split('.');
450
+ return parts[0] + '.' + parts[1] + '.' + (parseInt(parts[2]) + 1).toString();
451
+ };
452
+ var getNextMajorVersion = function (version) {
453
+ var parts = version.split('.');
454
+ return (parseInt(parts[0]) + 1).toString() + '.0.0';
455
+ };
456
+ var getNextMinorVersion = function (version) {
457
+ var parts = version.split('.');
458
+ return parts[0] + '.' + (parseInt(parts[1]) + 1).toString() + '.0';
459
+ };
460
+ var buildFailed = function (output) {
461
+ return (output.indexOf('Aborted due to warnings') !== -1 &&
462
+ output.indexOf('Command failed') !== -1);
463
+ };
464
+ program.command('shapes').action(function () { return __awaiter(void 0, void 0, void 0, function () {
465
+ var pack, moduleName, moduleExports, shapes, key, moduleExport, shapeContents;
466
+ return __generator(this, function (_a) {
467
+ switch (_a.label) {
468
+ case 0:
469
+ if (!fs.existsSync(process.cwd() + '/package.json')) return [3 /*break*/, 2];
470
+ pack = JSON.parse(fs.readFileSync(process.cwd() + '/package.json', 'utf8'));
471
+ moduleName = pack.name;
472
+ //just making sure the library is loaded in correct order because circular references are currently happening when importing BlankNode before NamedNode for example
473
+ require('lincd');
474
+ moduleExports = require(process.cwd() + '/lib/index.js');
475
+ shapes = new Set();
476
+ for (key in moduleExports) {
477
+ moduleExport = moduleExports[key];
478
+ // console.log(key, Object.keys(moduleExports[key]));
479
+ if (moduleExport.shape) {
480
+ // console.log(Object.keys(moduleExport.shape));
481
+ if (moduleExport.shape && moduleExport.shape instanceof lib_1.SHACL_Shape) {
482
+ shapes.add(moduleExport.shape);
483
+ }
484
+ }
485
+ }
486
+ console.log(Object.keys(JSONLDWriter_1.JSONLDWriter).join(","));
487
+ return [4 /*yield*/, JSONLDWriter_1.JSONLDWriter.stringify(shapes)];
488
+ case 1:
489
+ shapeContents = _a.sent();
490
+ // console.log(key);
491
+ // let shapeContents = JSON.stringify(json);
492
+ // console.log(JSON.stringify(json));
493
+ return [2 /*return*/, fs.writeFile(path.join('dist', 'shapes.json'), shapeContents)];
494
+ case 2:
495
+ console.warn('Not a project');
496
+ _a.label = 3;
497
+ case 3: return [2 /*return*/];
498
+ }
499
+ });
500
+ }); });
501
+ program.command('publish [version]').action(function (newVersion) {
502
+ if (fs.existsSync(process.cwd() + '/package.json')) {
503
+ var pack = JSON.parse(fs.readFileSync(process.cwd() + '/package.json', 'utf8'));
504
+ var version_1 = pack.version;
505
+ var moduleName_1 = pack.name;
506
+ if (newVersion == 'same') {
507
+ newVersion = version_1;
508
+ }
509
+ else if (newVersion == 'minor') {
510
+ newVersion = getNextMinorVersion(version_1);
511
+ console.log(chalk.cyan('Increasing version number for minor release: ' + newVersion));
512
+ }
513
+ else if (newVersion == 'major') {
514
+ newVersion = getNextMajorVersion(version_1);
515
+ console.log(chalk.cyan('Increasing version number for major release: ' + newVersion));
516
+ }
517
+ else if (!newVersion || newVersion == 'patch') {
518
+ newVersion = getNextVersion(version_1);
519
+ console.log(chalk.cyan('Increasing version number for patch release: ' + newVersion));
520
+ }
521
+ else {
522
+ newVersion = version_1;
523
+ console.log(chalk.cyan('using given version as is: ' + newVersion));
524
+ }
525
+ // message = "%s " + message;
526
+ console.log(chalk.cyan('preparing to publish ' + moduleName_1 + ' ' + newVersion));
527
+ //temporary test code
528
+ return fetch('http://localhost:3000/publish', {
529
+ method: 'POST',
530
+ headers: {
531
+ Accept: 'application/json, text/plain, */*',
532
+ 'Content-Type': 'application/json'
533
+ },
534
+ body: JSON.stringify({ package: moduleName_1 })
535
+ })
536
+ .then(function (res) { return res.text(); })
537
+ .then(function (text) {
538
+ console.log(text);
539
+ });
540
+ console.log(chalk.cyan('building production bundles'));
541
+ return execPromise('yarn lincd build production', false, true)
542
+ .then(function (output) {
543
+ if (buildFailed(output)) {
544
+ // console.warn("Build failed:");
545
+ console.log(output);
546
+ throw new Error('build failed');
547
+ }
548
+ pack.version = newVersion;
549
+ //save package.json
550
+ return fs.writeFileSync(path.join(process.cwd(), 'package.json'), JSON.stringify(pack, null, 2));
551
+ })
552
+ .then(function (version) {
553
+ console.log(chalk.cyan('Committing to git'));
554
+ //we have just changed package.json, so there will be things "uncommitted"
555
+ //to make sure this module does not automatically come up as "needing to be published" we need to commit this change here straight away
556
+ //so: add all files not added yet in the folder of this module
557
+ //then commit all changes (including new version number in package.json)
558
+ //then add a version commit git flag
559
+ return execPromise("git add -- ./ & git commit -m \"publishing ".concat(moduleName_1, " ").concat(newVersion, "\" -- ./ & git tag ").concat(moduleName_1, "@").concat(newVersion, "\""));
560
+ })
561
+ .then(function (version) {
562
+ console.log(chalk.cyan('Publishing ' + moduleName_1 + ' ' + newVersion));
563
+ // let tag = moduleName+'@'+version;
564
+ return execPromise('yarn publish --new-version ' + newVersion, true);
565
+ })
566
+ .then(function (res) {
567
+ if (res.indexOf('Aborted due to warnings') !== -1 ||
568
+ res.indexOf('Could not publish') !== -1 ||
569
+ res.indexOf("Couldn't publish") !== -1) {
570
+ console.log(chalk.red('Failed to publish'));
571
+ return false;
572
+ }
573
+ else {
574
+ var pack = JSON.parse(fs.readFileSync(process.cwd() + '/package.json', 'utf8'));
575
+ version_1 = pack.version;
576
+ console.log(chalk.green('Published ' + version_1));
577
+ return true;
578
+ }
579
+ })["catch"](function (err) {
580
+ console.warn(chalk.red('Could not publish: ' + err));
581
+ });
582
+ }
583
+ else {
584
+ console.warn('not found: ' + process.cwd() + '/package.json');
585
+ }
586
+ });
587
+ var getPackageJSON = function (root) {
588
+ if (root === void 0) { root = process.cwd(); }
589
+ var packagePath = path.join(root, 'package.json');
590
+ if (fs.existsSync(packagePath)) {
591
+ return JSON.parse(fs.readFileSync(packagePath, 'utf8'));
592
+ }
593
+ else if (root === process.cwd()) {
594
+ console.warn('Could not find package.json. Make sure you run this command from the root of a lincd module or a lincd yarn workspace');
595
+ process.exit();
596
+ }
597
+ };
598
+ // program.command('create [action] [value]').action((action, prefixedUri) => {
599
+ //
600
+ // let [ontology,label] = typeof prefixedUri !== 'undefined' ? prefixedUri.split(":") : [];
601
+ // if(!ontology || !label)
602
+ // {
603
+ // return console.warn("Please provide a prefixed URI of the "+action+" to create");
604
+ // }
605
+ // if(action == 'viewtype')
606
+ // {
607
+ // //add to ontology file
608
+ // let contents = fs.readFileSync(path.join('src','ontologies',ontology),'utf8');
609
+ //
610
+ //
611
+ // //create view file
612
+ // //add view file to index
613
+ // }
614
+ // });
615
+ program.command('info').action(function () {
616
+ var ownPackage = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
617
+ console.log(ownPackage.version);
618
+ console.log('Running from: ' + __dirname);
619
+ });
620
+ var ensurePath = function () {
621
+ var folders = [];
622
+ for (var _i = 0; _i < arguments.length; _i++) {
623
+ folders[_i] = arguments[_i];
624
+ }
625
+ // let target = path.join(folders.shift());
626
+ var target;
627
+ folders.forEach(function (folder) {
628
+ target = target ? path.join(target, folder) : path.join(folder);
629
+ if (!fs.existsSync(target)) {
630
+ fs.mkdirSync(target);
631
+ }
632
+ });
633
+ return target;
634
+ };
635
+ program.command('test-build').action(function (target, target2) {
636
+ execPromise('yarn lincd build', true)
637
+ .then(function (result) {
638
+ console.log('success');
639
+ })["catch"](function (err) {
640
+ console.log('failed');
641
+ });
642
+ });
643
+ program.command('build [target] [target2]').action(function (target, target2) {
644
+ buildModule(target, target2);
645
+ });
646
+ var buildModule = function (target, target2, modulePath, logResults) {
647
+ if (modulePath === void 0) { modulePath = process.cwd(); }
648
+ if (logResults === void 0) { logResults = true; }
649
+ if (target == 'production' ||
650
+ target == 'es5' ||
651
+ target == 'es6' ||
652
+ !target) {
653
+ if (!fs.existsSync(path.join(modulePath, 'Gruntfile.js'))) {
654
+ console.warn("No Gruntfile found at ".concat(modulePath, "\\Gruntfile.js. Cannot build."));
655
+ return;
656
+ }
657
+ var nodeEnv = '';
658
+ if (target == 'production') {
659
+ if (!(target2 == 'es5' || target2 == 'es6' || typeof target2 == 'undefined')) {
660
+ console.warn('unknown second build target. Use es5 or es6', target2);
661
+ return;
662
+ }
663
+ var isWindows = /^win/.test(process.platform);
664
+ if (isWindows) {
665
+ nodeEnv = 'SET NODE_ENV=production&& ';
666
+ }
667
+ else {
668
+ nodeEnv = "NODE_ENV='production' ";
669
+ }
670
+ }
671
+ if (!target) {
672
+ target = 'es6';
673
+ }
674
+ log('building once: ' +
675
+ nodeEnv +
676
+ 'grunt build' +
677
+ (target ? '-' + target : '') +
678
+ (target2 ? '-' + target2 : '') +
679
+ ' --color');
680
+ var method = logResults ? execp : execPromise;
681
+ //execute the command to build the method, and provide the current work directory as option
682
+ return method(nodeEnv +
683
+ 'grunt build' +
684
+ (target ? '-' + target : '') +
685
+ (target2 ? '-' + target2 : '') +
686
+ ' --color', false, false, { cwd: modulePath })["catch"](function (err) {
687
+ process.exit(1);
688
+ });
689
+ }
690
+ else {
691
+ console.warn('unknown build target. Use es5, es6 or production.');
692
+ }
693
+ };
694
+ // program.command('css').action((message) => {
695
+ // return execp('grunt babel:css-module-transforms');
696
+ // });
697
+ var getLastBuildTime = function (modulePath) {
698
+ return getLastModifiedFile(modulePath + '/@(builds|lib)/**/*.js');
699
+ };
700
+ var getLastModifiedSourceTime = function (modulePath) {
701
+ return getLastModifiedFile(modulePath + '/@(src|data|scss)/**/*', {
702
+ ignore: [modulePath + '/**/*.scss.json', modulePath + '/**/*.d.ts']
703
+ });
704
+ };
705
+ var getLastCommitTime = function (modulePath) {
706
+ // console.log(`git log -1 --format=%ci -- ${modulePath}`);
707
+ // process.exit();
708
+ return execPromise("git log -1 --format=%ci -- ".concat(modulePath)).then(function (result) {
709
+ var lastCommit = new Date(result);
710
+ // console.log(modulePath,result,lastCommit);
711
+ return lastCommit;
712
+ });
713
+ };
714
+ var getLastModifiedFile = function (filePath, config) {
715
+ if (config === void 0) { config = {}; }
716
+ var files = glob.sync(filePath, config);
717
+ // console.log(files.join(" - "));
718
+ var lastModifiedName;
719
+ var lastModified;
720
+ var lastModifiedTime = 0;
721
+ files.forEach(function (fileName) {
722
+ if (fs.lstatSync(fileName).isDirectory()) {
723
+ // console.log("skipping directory "+fileName);
724
+ return;
725
+ }
726
+ //not counting things that are generated during build process when determining last modified source-code time
727
+ // if(fileName.indexOf(".d.ts") !== -1 || fileName.indexOf(".css.json") !== -1)
728
+ // {
729
+ // // console.log("not counting "+fileName);
730
+ // return;
731
+ // }
732
+ var mtime = fs.statSync(path.join(fileName)).mtime;
733
+ var modifiedTime = mtime.getTime();
734
+ if (modifiedTime > lastModifiedTime) {
735
+ // console.log(fileName,mtime);
736
+ lastModifiedName = fileName;
737
+ lastModified = mtime;
738
+ lastModifiedTime = modifiedTime;
739
+ }
740
+ });
741
+ return { lastModified: lastModified, lastModifiedName: lastModifiedName, lastModifiedTime: lastModifiedTime };
742
+ };
743
+ program.command('publish-updated').action(function () {
744
+ return publishUpdated();
745
+ });
746
+ program.command('status').action(function () {
747
+ return publishUpdated(true).then(function () {
748
+ return buildUpdated(undefined, '', '', true);
749
+ });
750
+ });
751
+ var publishUpdated = function (test) {
752
+ var _this = this;
753
+ if (test === void 0) { test = false; }
754
+ var modules = getLocalLincdModules();
755
+ var browserCoreBuilt = false;
756
+ var p = Promise.resolve('');
757
+ modules.forEach(function (module) {
758
+ p = p.then(function (previousResult) {
759
+ log('# Checking module ' + module.moduleName);
760
+ // log('# Requesting ' + 'yarn info '+module.packageName+' --json');
761
+ // return execPromise('yarn info '+module.packageName+' --json').then((output:string) => {
762
+ // console.log("Will be requesting npm view from this current working directory:\n"+process.cwd());
763
+ // return execPromise('npm view '+module.packageName+' --json').then((output:string) => {
764
+ return execPromise('yarn info ' + module.packageName + ' --json')
765
+ .then(function (output) { return __awaiter(_this, void 0, void 0, function () {
766
+ var info, lastPublish, lastPublishDate, _a, lastModifiedTime, lastModifiedName, lastModified, lastCommit, res, browserModule;
767
+ return __generator(this, function (_b) {
768
+ switch (_b.label) {
769
+ case 0:
770
+ try {
771
+ if (output == '') {
772
+ // console.warn("No response (empty) from `yarn info`");
773
+ throw new Error('Empty response from `npm view`');
774
+ return [2 /*return*/];
775
+ }
776
+ info = JSON.parse(output);
777
+ // var stats = fs.statSync(path.join(moduleDirectory));
778
+ // var files = fs.readdirSync(path.join(moduleDirectory,'src'));
779
+ }
780
+ catch (err) {
781
+ chalk.red(module.moduleName + ' failed: ' + err.message + '\n');
782
+ console.warn('Returned JSON from npm: ' + output);
783
+ return [2 /*return*/, (previousResult +
784
+ ' ' +
785
+ chalk.red(module.moduleName + ' failed: ' + err.message + '\n'))];
786
+ }
787
+ lastPublish = info.data.time[info.data.version];
788
+ lastPublishDate = new Date(lastPublish);
789
+ _a = getLastModifiedSourceTime(module.path), lastModifiedTime = _a.lastModifiedTime, lastModifiedName = _a.lastModifiedName, lastModified = _a.lastModified;
790
+ return [4 /*yield*/, getLastCommitTime(module.path)];
791
+ case 1:
792
+ lastCommit = _b.sent();
793
+ console.log(lastPublishDate.toDateString() +
794
+ ' ' +
795
+ lastPublishDate.toTimeString() +
796
+ ' published ' +
797
+ info.data.version);
798
+ console.log(lastCommit.toDateString() +
799
+ ' ' +
800
+ new Date(lastCommit).toTimeString() +
801
+ ' source last committed');
802
+ // console.log(lastModified.toDateString() + ' ' + new Date(lastModified).toTimeString() + ' source ' + lastModifiedName + ' last edited');
803
+ //NOTE: removed lastModified, because switching branches will say that the file was modified and cause everything to publish
804
+ //SO: now you NEED TO commit before it picks up that you should publish
805
+ //|| lastPublishDate.getTime() < lastModified.getTime()
806
+ if (lastPublishDate.getTime() < lastCommit.getTime()) {
807
+ res = executeSingleBuild(module, previousResult, test, info);
808
+ if (module.moduleName == 'browser-core') {
809
+ browserCoreBuilt = true;
810
+ }
811
+ //when publishing core, also make sure to publish browser-core
812
+ if (module.moduleName == 'core' && !browserCoreBuilt) {
813
+ browserModule = modules.find(function (m) { return m.moduleName == 'browser-core'; });
814
+ return [2 /*return*/, Promise.resolve(res).then(function (previousResult) {
815
+ log('# Automatically also publishing module browser-core');
816
+ return executeSingleBuild(browserModule, previousResult, test);
817
+ })];
818
+ }
819
+ return [2 /*return*/, res];
820
+ }
821
+ return [2 /*return*/, previousResult];
822
+ }
823
+ });
824
+ }); })["catch"](function (err) {
825
+ console.log(err);
826
+ return (previousResult + ' ' + chalk.red(module.moduleName + ' failed\n'));
827
+ });
828
+ });
829
+ });
830
+ return p.then(function (messages) {
831
+ if (messages == '') {
832
+ console.log('All published modules are already up-to-date.');
833
+ }
834
+ else {
835
+ console.log('Summary: \n' + messages);
836
+ }
837
+ });
838
+ };
839
+ var executeSingleBuild = function (module, previousResult, test, info) {
840
+ var nextVersion = info ? getNextVersion(info.data.version) : '';
841
+ console.log(chalk.blue('--> ' +
842
+ (test ? 'should publish' : 'publishing') +
843
+ ' ' +
844
+ module.moduleName +
845
+ ' ' +
846
+ nextVersion));
847
+ if (!test) {
848
+ return execPromise('cd ' + module.path + ' && yarn lincd publish', true)
849
+ .then(function (res) {
850
+ if (res.indexOf('Aborted due to warnings') !== -1 ||
851
+ res.indexOf('Could not publish') !== -1 ||
852
+ res.indexOf("Couldn't publish") !== -1) {
853
+ console.log(res);
854
+ return (previousResult + ' ' + chalk.red(module.moduleName + ' failed\n'));
855
+ }
856
+ console.log(chalk.green('Successfully published ' + nextVersion));
857
+ return (previousResult +
858
+ ' ' +
859
+ chalk.green(module.moduleName + ' published ' + nextVersion + '\n'));
860
+ })["catch"](function (err) {
861
+ console.log(chalk.red('Failed to publish: ' + err));
862
+ return chalk.red('Failed to publish: ' + err);
863
+ });
864
+ }
865
+ else {
866
+ //when testing what needs to be published
867
+ return (previousResult + ' ' + chalk.blue(module.moduleName + ' should publish\n'));
868
+ }
869
+ };
870
+ program
871
+ .command('build-updated [target] [target2]')
872
+ .action(function (target, target2) {
873
+ return buildUpdated(1, target, target2);
874
+ });
875
+ program
876
+ .command('build-updated-since [num-commits-back] [target] [target2]')
877
+ .action(function (back, target, target2) {
878
+ return buildUpdated(back, target, target2);
879
+ });
880
+ var buildUpdated = function (back, target, target2, test) {
881
+ if (test === void 0) { test = false; }
882
+ back = back || 1;
883
+ return execPromise("git log -".concat(back, " --format=%ci")).then(function (result) {
884
+ var lastCommit = new Date(result);
885
+ var previousResult = '';
886
+ log((test ? 'Checking which modules' : 'Building all modules that') +
887
+ ' have been changed since last commit on ' +
888
+ lastCommit.toString());
889
+ var modules = getLocalLincdModules();
890
+ var p = Promise.resolve('');
891
+ modules.forEach(function (module) {
892
+ var moduleName = module.moduleName;
893
+ p = p
894
+ .then(function (previousResult) {
895
+ var lastModifiedSource = getLastModifiedSourceTime(module.path);
896
+ var lastModifiedBundle = getLastBuildTime(module.path);
897
+ // console.log(module.path,lastModifiedSource.lastModifiedTime,lastModifiedBundle.lastModifiedTime);
898
+ // console.log(module.path,new Date(lastModifiedSource.lastModified).toString(),new Date(lastModifiedBundle.lastModified).toString());
899
+ console.log('# Checking module ' + moduleName);
900
+ if (lastModifiedSource.lastModifiedTime >
901
+ lastModifiedBundle.lastModifiedTime) {
902
+ // log(moduleName+' modified since last commit on '+lastCommit.toString());
903
+ console.log(chalk.cyan('Last modified source: ' +
904
+ lastModifiedSource.lastModifiedName +
905
+ ' on ' +
906
+ lastModifiedSource.lastModified.toString()));
907
+ console.log(chalk.cyan('Last build: ' + lastModifiedBundle.lastModified.toString()));
908
+ log('--> ' + (test ? 'need to build ' : 'building ') + moduleName);
909
+ if (!test) {
910
+ return execPromise('cd ' +
911
+ module.path +
912
+ ' && yarn lincd build' +
913
+ (target ? ' ' + target : '') +
914
+ (target2 ? ' ' + target2 : '')).then(function (res) {
915
+ if (res.indexOf('Aborted due to warnings') !== -1 ||
916
+ res.indexOf('Fatal error') !== -1) {
917
+ console.log(res);
918
+ return (previousResult + ' ' + chalk.red(moduleName + ' failed\n'));
919
+ }
920
+ console.log(chalk.green(moduleName + ' bundles successfully built'));
921
+ return (previousResult + ' ' + chalk.green(moduleName + ' built\n'));
922
+ });
923
+ }
924
+ return (previousResult +
925
+ ' ' +
926
+ chalk.blue(moduleName + ' should be build\n'));
927
+ }
928
+ return previousResult;
929
+ })["catch"](function (err) {
930
+ console.log(err);
931
+ return previousResult + ' ' + chalk.red(moduleName + ' failed\n');
932
+ });
933
+ });
934
+ return p.then(function (messages) {
935
+ if (messages == '') {
936
+ console.log(chalk.green('Nothing to rebuild.'));
937
+ }
938
+ else {
939
+ console.log('Summary: \n' + messages);
940
+ }
941
+ });
942
+ });
943
+ };
944
+ program.command('build-all [target] [target2]').action(function (target, target2) {
945
+ var dependencies = new Map();
946
+ console.log('Building all modules of this repository in order of dependencies');
947
+ var modules = getLocalLincdModuleMap();
948
+ //get dependencies of each module
949
+ var leastDependentModule;
950
+ modules.forEach(function (module) {
951
+ var pack = getPackageJSON(module.path);
952
+ if (pack) {
953
+ //get lincd related dependencies and get the actual module details from the module map by removing '@dacore/' from the package name
954
+ var moduleDependencies = Object.keys(pack.dependencies)
955
+ .filter(function (dependency) { return modules.has(dependency); })
956
+ .map(function (dependency) {
957
+ return modules.has(dependency) ? modules.get(dependency) : dependency;
958
+ });
959
+ // console.log(module.moduleName,moduleDependencies.map())
960
+ dependencies.set(module, moduleDependencies);
961
+ }
962
+ });
963
+ dependencies.forEach(function (moduleDependencies, module) {
964
+ if (!moduleDependencies.some(function (dependency) {
965
+ return (typeof dependency !== 'string' && modules.has(dependency.moduleName));
966
+ })) {
967
+ leastDependentModule = module;
968
+ }
969
+ });
970
+ var startFrom;
971
+ //by default start building
972
+ var building = true;
973
+ //option to start from a specific module in the stack
974
+ if (target == 'from') {
975
+ startFrom = target2;
976
+ //if we have a startFrom, then we havnt started the build process yet
977
+ building = startFrom ? false : true;
978
+ //clear targets
979
+ target = '';
980
+ target2 = '';
981
+ console.log(chalk.blue('Will skip builds until ' + startFrom));
982
+ }
983
+ var stack = [leastDependentModule];
984
+ var done = new Set();
985
+ var p = Promise.resolve();
986
+ var runStack = function () { return __awaiter(void 0, void 0, void 0, function () {
987
+ var modulesLeft, first_1;
988
+ return __generator(this, function (_a) {
989
+ switch (_a.label) {
990
+ case 0:
991
+ modulesLeft = modules.size - done.size;
992
+ if (done.size > 0) {
993
+ console.log(chalk.magenta('\n-------\nThese modules are next, since all their dependencies have now been build:'));
994
+ console.log(chalk.magenta(stack.map(function (i) { return i.moduleName; })));
995
+ // log(stack);
996
+ }
997
+ stack.forEach(function (module) {
998
+ p = p.then(function () {
999
+ var command;
1000
+ //if we're skipping builds until a certain module
1001
+ if (!building) {
1002
+ //if the module name matches the module we're supposed to start from then start building modules
1003
+ if (module.moduleName == startFrom ||
1004
+ module.packageName == startFrom) {
1005
+ building = true;
1006
+ }
1007
+ //else still waiting for the module
1008
+ else {
1009
+ log(chalk.blue('skipping ' + module.moduleName));
1010
+ command = Promise.resolve(true);
1011
+ }
1012
+ }
1013
+ //unless told otherwise, build the module
1014
+ if (!command) {
1015
+ command = execp('cd ' +
1016
+ module.path +
1017
+ ' && yarn lincd build' +
1018
+ (target ? ' ' + target : '') +
1019
+ (target2 ? ' ' + target2 : ''));
1020
+ log(chalk.magenta(modulesLeft + ' modules left'));
1021
+ log(chalk.cyan('Building ' + module.moduleName));
1022
+ }
1023
+ modulesLeft--;
1024
+ return command["catch"](function (err) {
1025
+ var dependentModules = [];
1026
+ dependencies.forEach(function (dModuleDependencies, dModule) {
1027
+ if (dModuleDependencies.indexOf(module) !== -1) {
1028
+ dependentModules.push(dModule);
1029
+ }
1030
+ });
1031
+ if (dependentModules.length > 0) {
1032
+ console.log(chalk.magenta('Stopping build process because an error occurred whilst building ' +
1033
+ module.moduleName +
1034
+ ', which ' +
1035
+ dependentModules.length +
1036
+ ' other modules depend on.')); //"+dependentModules.map(d => d.moduleName).join(", ")));
1037
+ process.exit(1);
1038
+ }
1039
+ });
1040
+ });
1041
+ done.add(module);
1042
+ });
1043
+ //wait till stack is completed
1044
+ return [4 /*yield*/, p];
1045
+ case 1:
1046
+ //wait till stack is completed
1047
+ _a.sent();
1048
+ //clear stack for next round
1049
+ stack = [];
1050
+ //find those modules who have all their dependencies already built and add them to the stack
1051
+ modules.forEach(function (module) {
1052
+ var deps = dependencies.get(module);
1053
+ //if the module is not done yet
1054
+ //but every dependency is now done OR was not something we can build (some @dacore dependencies may not be local)
1055
+ if (!done.has(module) &&
1056
+ deps.every(function (dependency) {
1057
+ return (typeof dependency !== 'string' &&
1058
+ (done.has(dependency) || !modules.has(dependency.moduleName)));
1059
+ })) {
1060
+ stack.push(module);
1061
+ }
1062
+ // else if(!done.has(module))
1063
+ // {
1064
+ // console.log(chalk.red(module+' not yet'))
1065
+ // console.log('UNMET DEPS: '+deps.filter(dependency => !done.has(dependency)).join(" "))
1066
+ // }
1067
+ });
1068
+ //if more to be built, iterate
1069
+ if (stack.length > 0) {
1070
+ return [2 /*return*/, runStack()];
1071
+ }
1072
+ else {
1073
+ //if no more modules to build but we never started building...
1074
+ if (!building) {
1075
+ console.log(chalk.red('Could not find the module to start from. Please provide a correct package name or module name to build from'));
1076
+ }
1077
+ else {
1078
+ first_1 = true;
1079
+ modules.forEach(function (module) {
1080
+ if (!done.has(module)) {
1081
+ var deps = dependencies.get(module);
1082
+ if (first_1) {
1083
+ console.log(chalk.red('CYCLICAL DEPENDENCIES? - could not build some modules because they depend on each other.'));
1084
+ first_1 = false;
1085
+ }
1086
+ //print the cyclical dependencies
1087
+ console.log(chalk.red(module.moduleName) +
1088
+ ' depends on ' +
1089
+ deps
1090
+ .filter(function (dependency) {
1091
+ return typeof dependency !== 'string';
1092
+ })
1093
+ .map(function (d) {
1094
+ return done.has(d) ? d.moduleName : chalk.red(d.moduleName);
1095
+ })
1096
+ .join(', '));
1097
+ //also print some information why these modules have not been moved into the stack
1098
+ var stringDependencies = deps.filter(function (d) { return typeof d === 'string'; });
1099
+ if (stringDependencies.length > 0) {
1100
+ console.log(chalk.red('And it depends on these module(s) - which seem not to be proper modules :' +
1101
+ stringDependencies.join(', ')));
1102
+ console.log(chalk.red('Could you remove this from dependencies? Should it be a devDependency?'));
1103
+ }
1104
+ }
1105
+ });
1106
+ }
1107
+ }
1108
+ return [2 /*return*/];
1109
+ }
1110
+ });
1111
+ }); };
1112
+ //starts the process
1113
+ runStack();
1114
+ });
1115
+ program
1116
+ .command('modules [action] [includedSpaces]')
1117
+ .action(function (command, includedSpaces) {
1118
+ executeCommandForEachModule(getLincdModules(), command, includedSpaces);
1119
+ });
1120
+ program
1121
+ .command('modules-except [excludedSpaces] [action]')
1122
+ .action(function (excludedSpaces, command) {
1123
+ executeCommandForEachModule(getLincdModules(), command, null, excludedSpaces);
1124
+ });
1125
+ var executeCommandForEachModule = function (modules, command, includedSpaces, excludedSpaces) {
1126
+ //if a specific set of modules is given
1127
+ if (includedSpaces) {
1128
+ //filter modules, so that we only execute on the modules as provided in the command
1129
+ includedSpaces = includedSpaces.split(',');
1130
+ modules = modules.filter(function (module) { return includedSpaces.indexOf(module.moduleName) !== -1; });
1131
+ log('Applying to included spaces');
1132
+ }
1133
+ //if a specific set of modules is given
1134
+ if (excludedSpaces) {
1135
+ //filter modules, so that we only execute on the modules as provided in the command
1136
+ excludedSpaces = excludedSpaces.split(',');
1137
+ modules = modules.filter(function (module) { return excludedSpaces.indexOf(module.moduleName) === -1; });
1138
+ log('Filtering excluded spaces');
1139
+ }
1140
+ log("Executing '" +
1141
+ command +
1142
+ "' on modules " +
1143
+ modules.map(function (m) { return m.moduleName; }).join(', '));
1144
+ var p = Promise.resolve(true);
1145
+ modules.forEach(function (module) {
1146
+ p = p.then(function () {
1147
+ log('# Module ' + module.moduleName + ' - ' + module.path);
1148
+ return execp('cd ' + module.path + ' && ' + command);
1149
+ });
1150
+ });
1151
+ return p;
1152
+ };
1153
+ program.command('dev [target] [mode]').action(function (target, mode) {
1154
+ if (!target)
1155
+ target = 'es6';
1156
+ if (mode !== 'production')
1157
+ mode = '';
1158
+ else if (target !== 'es6')
1159
+ log('target must be es6 when developing for production');
1160
+ if (target == 'es5' || target == 'es6') {
1161
+ // log('> Starting continuous development build for '+target+' target')
1162
+ log('starting continuous development build');
1163
+ log('grunt dev' +
1164
+ (target ? '-' + target : '') +
1165
+ (mode ? '-' + mode : '') +
1166
+ ' --color');
1167
+ var command = exec('grunt dev' +
1168
+ (target ? '-' + target : '') +
1169
+ (mode ? '-' + mode : '') +
1170
+ ' --color');
1171
+ command.stdout.pipe(process.stdout);
1172
+ command.stderr.pipe(process.stderr);
1173
+ }
1174
+ else {
1175
+ console.warn('unknown build target. Use es5 or es6');
1176
+ }
1177
+ });
1178
+ program.command('help').action(function (command) {
1179
+ logHelp();
1180
+ });
1181
+ program.command('*').action(function (command) {
1182
+ console.warn(chalk.red('unknown command: ' + command.args.join(' ')));
1183
+ logHelp();
1184
+ });
1185
+ function logHelp() {
1186
+ var ownPackage = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
1187
+ console.log('lincd-cli ' + ownPackage.version);
1188
+ console.log(chalk.green('\nAvailable commands from a module:'));
1189
+ console.log(chalk.blue('- build [es5|es6|production] [es5|es6] ') +
1190
+ chalk.cyan('- creates bundles & compiles source files each target environment'));
1191
+ console.log(chalk.blue('- dev [es5|es6] [production] ') +
1192
+ chalk.cyan('- continuously build bundles & compile source on file changes'));
1193
+ // console.log(
1194
+ // chalk.blue('- init [name] [uribase] ') +
1195
+ // chalk.cyan(
1196
+ // '- sets up a new module, sets up initial files and installs dependencies',
1197
+ // ),
1198
+ // );
1199
+ console.log(chalk.blue('- publish [version|minor|major|patch] ') +
1200
+ chalk.cyan('- publish new version to the npm registry AND to the LINCD.org registry'));
1201
+ //TODO: these all need to be tested to see if they work with the new LINCD setup
1202
+ /*
1203
+ console.log(
1204
+ chalk.green('\nAvailable commands from a yarn workspace:')
1205
+ );
1206
+ console.log(
1207
+ chalk.blue('- build-all [from] [module-name]') +
1208
+ chalk.cyan(
1209
+ '- build all modules in order of dependencies. To continue later from a specific module, add `from {modulename}`',
1210
+ ),
1211
+ );
1212
+ console.log(
1213
+ chalk.blue('- build-updated [n] ') +
1214
+ chalk.cyan(
1215
+ '- build only those modules that have updated their source since the last local commit (or optionally n commits back',
1216
+ ),
1217
+ );
1218
+ console.log(
1219
+ chalk.blue('- modules [action]') +
1220
+ chalk.cyan('- execute a command for all modules'),
1221
+ );
1222
+ console.log(
1223
+ chalk.blue('- publish-updated [message] ') +
1224
+ chalk.cyan(
1225
+ "- publish all modules who's source changes have been committed to git since the last published version.",
1226
+ ),
1227
+ );
1228
+ console.log(
1229
+ chalk.blue('- status') +
1230
+ chalk.cyan('- see which modules need to be published or build'),
1231
+ );*/
1232
+ console.log(chalk.green('\nOther commands:'));
1233
+ console.log(chalk.blue('- info ') +
1234
+ chalk.cyan('- print the version of this tool and where it runs from'));
1235
+ console.log(chalk.blue('- help ') +
1236
+ chalk.cyan('- print this message'));
1237
+ }
1238
+ program.parse(process.argv);