lincd-cli 0.1.22 → 0.1.24

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/lib/cli.js CHANGED
@@ -72,6 +72,7 @@ var path = require('path');
72
72
  var glob = require('glob');
73
73
  var variables = {};
74
74
  var open = require('open');
75
+ var gruntConfig;
75
76
  program
76
77
  .command('create-app')
77
78
  .action(function (name) {
@@ -84,24 +85,31 @@ program
84
85
  .action(function (name, uriBase) {
85
86
  return createModule(name, uriBase);
86
87
  })
87
- .description('Create a new folder with all the required files for a new LINCD module')
88
- .argument('<name>', 'The name of the module. Will be used as package name in package.json')
89
- .argument('[uri_base]', 'The base URL used for data of this module. Leave blank to use the URL of your module on lincd.org after you register it');
88
+ .description('Create a new folder with all the required files for a new LINCD package')
89
+ .argument('<name>', 'The name of the package. Will be used as package name in package.json')
90
+ .argument('[uri_base]', 'The base URL used for data of this package. Leave blank to use the URL of your package on lincd.org after you register it');
90
91
  program
91
92
  .command('create-shape')
92
93
  .action(function (name, uriBase) {
93
94
  return createShape(name);
94
95
  })
95
- .description('Creates a new ShapeClass file for your module. Execute this from your module folder.')
96
+ .description('Creates a new ShapeClass file for your package. Execute this from your package folder.')
96
97
  .argument('<name>', 'The name of the shape. Will be used for the file name and the class name');
98
+ program
99
+ .command('create-component')
100
+ .action(function (name, uriBase) {
101
+ return createComponent(name);
102
+ })
103
+ .description('Creates a new Component file for your package. Execute this from your package folder.')
104
+ .argument('<name>', 'The name of the component. Will be used for the file name and the export name');
97
105
  program
98
106
  .command('create-ontology')
99
107
  .action(function (prefix, uriBase) {
100
108
  return createOntology(prefix, uriBase);
101
109
  })
102
- .description('Creates a new ontology file for your module. Execute this from your module folder.')
110
+ .description('Creates a new ontology file for your package. Execute this from your package folder.')
103
111
  .argument('<suggested-prefix>', 'The suggested prefix for your ontology. Also the shorthand code used for the file name and the exported ontology object')
104
- .argument('[uribase]', "Optional argument to set the URI base for the URI's of all entities in your ontology. Leave blank to use the URI's provided by lincd.org once you register this module");
112
+ .argument('[uribase]', "Optional argument to set the URI base for the URI's of all entities in your ontology. Leave blank to use the URI's provided by lincd.org once you register this package");
105
113
  program.command('register-local', { hidden: true }).action(function () {
106
114
  register('http://localhost:4101');
107
115
  });
@@ -113,7 +121,7 @@ program
113
121
  .action(function () {
114
122
  register('https://registry.lincd.org');
115
123
  })
116
- .description('Register (a new version of) this module to the LINCD registry. If successful your module will appear on www.lincd.org');
124
+ .description('Register (a new version of) this package to the LINCD registry. If successful your package will appear on www.lincd.org');
117
125
  program
118
126
  .command('info')
119
127
  .action(function () {
@@ -129,7 +137,9 @@ program.command('publish-updated').action(function () {
129
137
  return publishUpdated();
130
138
  });
131
139
  program.command('status').action(function () {
140
+ //log which packages need to be published
132
141
  return publishUpdated(true).then(function () {
142
+ //log which packages need to be build
133
143
  return buildUpdated(undefined, '', '', true);
134
144
  });
135
145
  });
@@ -142,17 +152,17 @@ program.command('build-updated-since [num-commits-back] [target] [target2]').act
142
152
  program.command('build-all [target] [target2]').action(function (target, target2) {
143
153
  buildAll(target, target2);
144
154
  });
145
- program.command('modules [action] [includedSpaces]').action(function (command, includedSpaces) {
146
- executeCommandForEachModule(getLincdModules(), command, includedSpaces);
147
- });
148
- program.command('modules-except [excludedSpaces] [action]').action(function (excludedSpaces, command) {
149
- executeCommandForEachModule(getLincdModules(), command, null, excludedSpaces);
155
+ program.command('all [action] [filter] [filter-value]').action(function (command, filter, filterValue) {
156
+ executeCommandForEachModule(getLincdModules(), command, filter, filterValue);
150
157
  });
158
+ // program.command('all-except [excludedSpaces] [action]').action((excludedSpaces, command) => {
159
+ // executeCommandForEachModule(getLincdModules(), command, null, excludedSpaces);
160
+ // });
151
161
  program.command('dev [target] [mode]').action(function (target, mode) {
152
162
  developModule(target, mode);
153
163
  });
154
164
  program
155
- .command('module|m')
165
+ .command('module|m|package|p')
156
166
  .action(function (name, command, args) {
157
167
  var fullCommand = command
158
168
  ? command +
@@ -166,8 +176,8 @@ program
166
176
  executeCommandForModule(name, fullCommand);
167
177
  })
168
178
  .alias('m')
169
- .description("Searches for a module in this workspace with a partially matching name and executes a command for that module (without needing to execute it from that modules' folder)")
170
- .argument('<name>', 'the name of the module. Can be a part of the name.')
179
+ .description('Searches for a package in this workspace with a partially matching name and executes a command for that package (without needing to execute it from the folder of the package)')
180
+ .argument('<name>', 'the name of the package. Can be a part of the name.')
171
181
  .argument('[command]', 'the lincd command you want to execute. Like dev or build')
172
182
  .argument('[args...]', 'the additional arguments of that command');
173
183
  function logHelp() {
@@ -182,6 +192,33 @@ function log() {
182
192
  console.log(chalk.cyan('Info: ') + message);
183
193
  });
184
194
  }
195
+ function progressUpdate(message) {
196
+ process.stdout.write(' \r');
197
+ process.stdout.write(message + '\r');
198
+ }
199
+ function debugInfo() {
200
+ var messages = [];
201
+ for (var _i = 0; _i < arguments.length; _i++) {
202
+ messages[_i] = arguments[_i];
203
+ }
204
+ // messages.forEach((message) => {
205
+ // console.log(chalk.cyan('Info: ') + message);
206
+ // });
207
+ //@TODO: let packages also use lincd.config.json? instead of gruntfile...
208
+ // that way we can read "analyse" here and see if we need to log debug info
209
+ // if(!gruntConfig)
210
+ // {
211
+ // gruntConfig = getGruntConfig();
212
+ // console.log(gruntConfig);
213
+ // process.exit();
214
+ // }
215
+ // if(gruntConfig.analyse === true)
216
+ // {
217
+ // messages.forEach((message) => {
218
+ // console.log(chalk.cyan('Info: ') + message);
219
+ // });
220
+ // }
221
+ }
185
222
  function warn() {
186
223
  var messages = [];
187
224
  for (var _i = 0; _i < arguments.length; _i++) {
@@ -239,7 +276,7 @@ function checkModulePath(rootPath, modulePath, res) {
239
276
  // console.log('checking '+packagePath);
240
277
  if (fs.existsSync(packagePath)) {
241
278
  var pack = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
242
- //some packages are not true lincd modules, but we still want them to be re-built automatically. This is what lincd_util is for
279
+ //some packages are not true lincd packages, but we still want them to be re-built automatically. This is what lincd_util is for
243
280
  if (pack && pack.workspaces) {
244
281
  checkWorkspaces(modulePath, pack.workspaces, res);
245
282
  }
@@ -252,221 +289,240 @@ function checkModulePath(rootPath, modulePath, res) {
252
289
  }
253
290
  }
254
291
  }
255
- function buildAll(target, target2) {
292
+ function runOnPackagesGroupedByDependencies(lincdPackages, onBuildStack, onStackEnd) {
256
293
  var _this = this;
257
294
  var dependencies = new Map();
258
- console.log('Building all modules of this repository in order of dependencies');
259
- var modules = getLocalLincdModuleMap();
260
- //get dependencies of each module
295
+ //get dependencies of each package
261
296
  var leastDependentModule;
262
- modules.forEach(function (module) {
263
- var pack = (0, utils_1.getPackageJSON)(module.path);
297
+ lincdPackages.forEach(function (pkg) {
298
+ var pack = (0, utils_1.getPackageJSON)(pkg.path);
264
299
  if (pack) {
265
- //get lincd related dependencies and get the actual module details from the module map by removing '@dacore/' from the package name
300
+ //get lincd related dependencies and get the actual package details from the package map by removing '@dacore/' from the package name
266
301
  var moduleDependencies = Object.keys(pack.dependencies)
267
- .filter(function (dependency) { return modules.has(dependency); })
302
+ .filter(function (dependency) { return lincdPackages.has(dependency); })
268
303
  .map(function (dependency) {
269
- return modules.has(dependency) ? modules.get(dependency) : dependency;
304
+ return lincdPackages.has(dependency) ? lincdPackages.get(dependency) : dependency;
270
305
  });
271
- // console.log(module.moduleName,moduleDependencies.map())
272
- dependencies.set(module, moduleDependencies);
306
+ // console.log(package.moduleName,moduleDependencies.map())
307
+ dependencies.set(pkg, moduleDependencies);
273
308
  }
274
309
  });
275
- dependencies.forEach(function (moduleDependencies, module) {
310
+ dependencies.forEach(function (moduleDependencies, pkg) {
276
311
  if (!moduleDependencies.some(function (dependency) {
277
- return typeof dependency !== 'string' && modules.has(dependency.moduleName);
312
+ return typeof dependency !== 'string' && lincdPackages.has(dependency.moduleName);
278
313
  })) {
279
- leastDependentModule = module;
314
+ leastDependentModule = pkg;
280
315
  }
281
316
  });
282
- var startFrom;
283
- //by default start building
284
- var building = true;
285
- //option to start from a specific module in the stack
286
- if (target == 'from') {
287
- startFrom = target2;
288
- //if we have a startFrom, then we havnt started the build process yet
289
- building = startFrom ? false : true;
290
- //clear targets
291
- target = '';
292
- target2 = '';
293
- console.log(chalk.blue('Will skip builds until ' + startFrom));
294
- }
295
- var stack = [leastDependentModule];
317
+ var startStack = [leastDependentModule];
296
318
  var done = new Set();
297
- var p = Promise.resolve();
298
- var runStack = function () { return __awaiter(_this, void 0, void 0, function () {
299
- var modulesLeft, failedModules, stackPromise, first_1;
319
+ var results = [];
320
+ var runStack = function (stack) { return __awaiter(_this, void 0, void 0, function () {
321
+ var runFunction, stackPromise, stackResults;
300
322
  return __generator(this, function (_a) {
301
323
  switch (_a.label) {
302
324
  case 0:
303
- modulesLeft = modules.size - done.size;
304
- if (done.size > 0) {
305
- console.log(chalk.magenta('\n-------\nThese modules are next, since all their dependencies have now been build:'));
306
- console.log(chalk.magenta(stack.map(function (i) { return i.moduleName; })));
307
- // log(stack);
308
- }
309
- failedModules = [];
310
- stackPromise = Promise.all(stack.map(function (module) {
325
+ runFunction = onBuildStack(stack, dependencies);
326
+ stackPromise = Promise.all(stack.map(function (pck) {
311
327
  // p = p.then(() => {
312
- var command;
313
- //if we're skipping builds until a certain module
314
- if (!building) {
315
- //if the module name matches the module we're supposed to start from then start building modules
316
- if (module.moduleName == startFrom || module.packageName == startFrom) {
317
- building = true;
318
- }
319
- //else still waiting for the module
320
- else {
321
- log(chalk.blue('skipping ' + module.moduleName));
322
- command = Promise.resolve(true);
323
- }
324
- }
325
- //unless told otherwise, build the module
326
- if (!command) {
327
- command = execp('cd ' +
328
- module.path +
329
- ' && yarn lincd build' +
330
- (target ? ' ' + target : '') +
331
- (target2 ? ' ' + target2 : ''));
332
- log(chalk.cyan('Building ' + module.moduleName));
333
- }
334
- return command["catch"](function (err) {
335
- var dependentModules = [];
336
- dependencies.forEach(function (dModuleDependencies, dModule) {
337
- if (dModuleDependencies.indexOf(module) !== -1) {
338
- dependentModules.push(dModule);
339
- }
340
- });
341
- if (dependentModules.length > 0) {
342
- failedModules.push(module.moduleName);
343
- printBuildResults(failedModules, done);
344
- console.log(chalk.magenta('Stopping build process because an error occurred whilst building ' +
345
- module.moduleName +
346
- ', which ' +
347
- dependentModules.length +
348
- ' other modules depend on.')); //"+dependentModules.map(d => d.moduleName).join(", ")));
349
- console.log(chalk.cyanBright('tip ') +
350
- 'Run ' +
351
- chalk.green("lincd build-all from ".concat(module.moduleName)) +
352
- ' to build only the remaining modules'); //"+dependentModules.map(d => d.moduleName).join(", ")));
353
- process.exit(1);
354
- }
355
- else {
356
- failedModules.push(module.moduleName);
357
- }
328
+ return runFunction(pck)["catch"](function (_a) {
329
+ var error = _a.error, stdout = _a.stdout, stderr = _a.stderr;
330
+ warn('Uncaught exception whilst running parallel function on ' + pck.moduleName, error.message);
331
+ // warn(chalk.red(pck.moduleName+' failed:'));
332
+ // console.log(stdout);
358
333
  })
359
334
  .then(function (res) {
360
- // console.log("RESULT: ",res);
361
- // if(res && res.includes("Aborted due to warnings"))
362
- // {
363
- // failedModules.push(module.moduleName);
364
- // }
365
- // else
366
- // {
367
- done.add(module);
368
- // }
369
- modulesLeft--;
370
- log(chalk.magenta(modulesLeft + ' modules left'));
371
- if (modulesLeft == 0) {
372
- printBuildResults(failedModules, done);
373
- }
335
+ done.add(pck);
374
336
  return res;
375
337
  });
376
- // });
377
- // done.add(module);
378
338
  }));
379
- //wait till stack is completed
380
339
  return [4 /*yield*/, stackPromise];
381
340
  case 1:
382
- //wait till stack is completed
383
- _a.sent();
384
- // await p;
341
+ stackResults = _a.sent();
342
+ results = results.concat(stackResults);
385
343
  //clear stack for next round
386
344
  stack = [];
387
- //find those modules who have all their dependencies already built and add them to the stack
388
- modules.forEach(function (module) {
389
- var deps = dependencies.get(module);
390
- //if the module is not done yet
345
+ //find those packages who have all their dependencies already built and add them to the stack
346
+ lincdPackages.forEach(function (pkg) {
347
+ var deps = dependencies.get(pkg);
348
+ //if the package is not done yet
391
349
  //but every dependency is now done OR was not something we can build (some @dacore dependencies may not be local)
392
- if (!done.has(module) &&
350
+ if (!done.has(pkg) &&
393
351
  deps.every(function (dependency) {
394
- return typeof dependency !== 'string' && (done.has(dependency) || !modules.has(dependency.moduleName));
352
+ return typeof dependency !== 'string' && (done.has(dependency) || !lincdPackages.has(dependency.moduleName));
395
353
  })) {
396
- stack.push(module);
354
+ stack.push(pkg);
397
355
  }
398
- // else if(!done.has(module))
356
+ // else if(!done.has(package))
399
357
  // {
400
- // console.log(chalk.red(module+' not yet'))
358
+ // console.log(chalk.red(package+' not yet'))
401
359
  // console.log('UNMET DEPS: '+deps.filter(dependency => !done.has(dependency)).join(" "))
402
360
  // }
403
361
  });
404
362
  //if more to be built, iterate
405
363
  if (stack.length > 0) {
406
- return [2 /*return*/, runStack()];
364
+ return [2 /*return*/, runStack(stack)];
407
365
  }
408
366
  else {
409
- //if no more modules to build but we never started building...
410
- if (!building) {
411
- console.log(chalk.red('Could not find the module to start from. Please provide a correct package name or module name to build from'));
412
- }
413
- else {
414
- first_1 = true;
415
- modules.forEach(function (module) {
416
- if (!done.has(module)) {
417
- var deps = dependencies.get(module);
418
- if (first_1) {
419
- console.log(chalk.red('CYCLICAL DEPENDENCIES? - could not build some modules because they depend on each other.'));
420
- first_1 = false;
421
- }
422
- //print the cyclical dependencies
423
- console.log(chalk.red(module.moduleName) +
424
- ' depends on ' +
425
- deps
426
- .filter(function (dependency) {
427
- return typeof dependency !== 'string';
428
- })
429
- .map(function (d) {
430
- return done.has(d) ? d.moduleName : chalk.red(d.moduleName);
431
- })
432
- .join(', '));
433
- //also print some information why these modules have not been moved into the stack
434
- var stringDependencies = deps.filter(function (d) { return typeof d === 'string'; });
435
- if (stringDependencies.length > 0) {
436
- console.log(chalk.red('And it depends on these module(s) - which seem not to be proper modules :' +
437
- stringDependencies.join(', ')));
438
- console.log(chalk.red('Could you remove this from dependencies? Should it be a devDependency?'));
439
- }
440
- }
441
- });
442
- }
367
+ onStackEnd(results.filter(Boolean));
443
368
  }
444
369
  return [2 /*return*/];
445
370
  }
446
371
  });
447
372
  }); };
448
373
  //starts the process
449
- runStack();
374
+ runStack(startStack);
375
+ }
376
+ function buildAll(target, target2) {
377
+ var _this = this;
378
+ console.log('Building all LINCD packages of this repository in order of dependencies');
379
+ var lincdPackages = getLocalLincdModuleMap();
380
+ var startFrom;
381
+ //by default start building
382
+ var building = true;
383
+ //option to start from a specific package in the stack
384
+ if (target == 'from') {
385
+ startFrom = target2;
386
+ //if we have a startFrom, then we havnt started the build process yet
387
+ building = startFrom ? false : true;
388
+ //clear targets
389
+ target = '';
390
+ target2 = '';
391
+ console.log(chalk.blue('Will skip builds until ' + startFrom));
392
+ return function (pkg) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
393
+ return [2 /*return*/];
394
+ }); }); };
395
+ }
396
+ var done = new Set();
397
+ var failedModules = [];
398
+ progressUpdate(lincdPackages.size + ' packages left');
399
+ var modulesLeft = lincdPackages.size;
400
+ // let modulesLeft = lincdPackages.size - done.size;
401
+ runOnPackagesGroupedByDependencies(lincdPackages, function (packageGroup, dependencies) {
402
+ if (done.size > 0) {
403
+ debugInfo(chalk.magenta('\n-------\nThese packages are next, since all their dependencies have now been build:'));
404
+ // log(stack);
405
+ }
406
+ debugInfo('Now building: ' + chalk.blue(packageGroup.map(function (i) { return i.moduleName; })));
407
+ return function (pkg) { return __awaiter(_this, void 0, void 0, function () {
408
+ var command;
409
+ return __generator(this, function (_a) {
410
+ //if we're skipping builds until a certain package
411
+ if (!building) {
412
+ //if the package name matches the package we're supposed to start from then start building packages
413
+ if (pkg.moduleName == startFrom || pkg.packageName == startFrom) {
414
+ building = true;
415
+ }
416
+ //else still waiting for the package
417
+ else {
418
+ log(chalk.blue('skipping ' + pkg.moduleName));
419
+ command = Promise.resolve(true);
420
+ }
421
+ }
422
+ //unless told otherwise, build the package
423
+ if (!command) {
424
+ command = execPromise('cd ' + pkg.path + ' && yarn lincd build' + (target ? ' ' + target : '') + (target2 ? ' ' + target2 : ''), false, false, {}, false);
425
+ debugInfo(chalk.cyan('Building ' + pkg.moduleName));
426
+ }
427
+ return [2 /*return*/, command["catch"](function (_a) {
428
+ var error = _a.error, stdout = _a.stdout, stderr = _a.stderr;
429
+ //this prints out the webpack output, including the build errors
430
+ warn('Failed to build ' + pkg.moduleName);
431
+ console.log(stdout);
432
+ failedModules.push(pkg.moduleName);
433
+ var dependentModules = getDependentPackages(dependencies, pkg);
434
+ if (dependentModules.length > 0) {
435
+ printBuildResults(failedModules, done);
436
+ console.log(chalk.magenta('Stopping build process because an error occurred whilst building ' +
437
+ pkg.moduleName +
438
+ ', which ' +
439
+ dependentModules.length +
440
+ ' other packages depend on.')); //"+dependentModules.map(d => d.moduleName).join(", ")));
441
+ console.log(chalk.cyanBright('tip ') +
442
+ 'Run ' +
443
+ chalk.green("lincd build-all from ".concat(pkg.moduleName)) +
444
+ ' to build only the remaining packages'); //"+dependentModules.map(d => d.moduleName).join(", ")));
445
+ process.exit(1);
446
+ }
447
+ })
448
+ .then(function (res) {
449
+ done.add(pkg);
450
+ modulesLeft--;
451
+ // log(chalk.magenta(modulesLeft + ' packages left'));
452
+ process.stdout.write(modulesLeft + ' packages left\r');
453
+ if (modulesLeft == 0) {
454
+ printBuildResults(failedModules, done);
455
+ }
456
+ return res;
457
+ })];
458
+ });
459
+ }); };
460
+ }, function (dependencies) {
461
+ //if no more packages to build but we never started building...
462
+ if (!building) {
463
+ console.log(chalk.red('Could not find the package to start from. Please provide a correct package name or package name to build from'));
464
+ }
465
+ else {
466
+ //Detecting cyclical dependencies that caused some packages not to be build
467
+ var first_1 = true;
468
+ lincdPackages.forEach(function (pkg) {
469
+ if (!done.has(pkg)) {
470
+ var deps = dependencies.get(pkg);
471
+ if (first_1) {
472
+ console.log(chalk.red('CYCLICAL DEPENDENCIES? - could not build some packages because they depend on each other.'));
473
+ first_1 = false;
474
+ }
475
+ //print the cyclical dependencies
476
+ console.log(chalk.red(pkg.moduleName) +
477
+ ' depends on ' +
478
+ deps
479
+ .filter(function (dependency) {
480
+ return typeof dependency !== 'string';
481
+ })
482
+ .map(function (d) {
483
+ return done.has(d) ? d.moduleName : chalk.red(d.moduleName);
484
+ })
485
+ .join(', '));
486
+ //also print some information why these packages have not been moved into the stack
487
+ var stringDependencies = deps.filter(function (d) { return typeof d === 'string'; });
488
+ if (stringDependencies.length > 0) {
489
+ console.log(chalk.red('And it depends on these package(s) - which seem not to be proper packages :' +
490
+ stringDependencies.join(', ')));
491
+ console.log(chalk.red('Could you remove this from dependencies? Should it be a devDependency?'));
492
+ }
493
+ }
494
+ });
495
+ }
496
+ });
497
+ }
498
+ function getDependentPackages(dependencies, pkg) {
499
+ var dependentModules = [];
500
+ dependencies.forEach(function (dModuleDependencies, dModule) {
501
+ if (dModuleDependencies.indexOf(pkg) !== -1) {
502
+ dependentModules.push(dModule);
503
+ }
504
+ });
505
+ return dependentModules;
450
506
  }
451
507
  /**
452
- * Returns a map of the modules that this repository manages (so no modules found through the workspaces who's path contains ../ )
508
+ * Returns a map of the packages that this repository manages (so no packages found through the workspaces who's path contains ../ )
453
509
  * @param rootPath
454
510
  */
455
511
  function getLocalLincdModuleMap(rootPath) {
456
512
  if (rootPath === void 0) { rootPath = './'; }
457
513
  var map = new Map();
458
- getLincdModules(rootPath).forEach(function (module) {
459
- if (module.path.indexOf('../') === -1 && module.path.indexOf('..\\') === -1) {
460
- // console.log(module.path);
461
- map.set(module.moduleName, module);
514
+ getLincdModules(rootPath).forEach(function (pkg) {
515
+ if (pkg.path.indexOf('../') === -1 && pkg.path.indexOf('..\\') === -1) {
516
+ // console.log(package.path);
517
+ map.set(pkg.moduleName, pkg);
462
518
  }
463
519
  });
464
520
  return map;
465
521
  }
466
522
  function getLocalLincdModules(rootPath) {
467
523
  if (rootPath === void 0) { rootPath = './'; }
468
- return getLincdModules(rootPath).filter(function (module) {
469
- return module.path.indexOf('..\\') === -1;
524
+ return getLincdModules(rootPath).filter(function (pkg) {
525
+ return pkg.path.indexOf('..\\') === -1;
470
526
  });
471
527
  }
472
528
  function getLincdModules(rootPath) {
@@ -551,16 +607,17 @@ function execp(cmd, log, allowError, options) {
551
607
  });
552
608
  });
553
609
  }
554
- function execPromise(command, log, allowError, options) {
610
+ function execPromise(command, log, allowError, options, pipeOutput) {
555
611
  if (log === void 0) { log = false; }
556
612
  if (allowError === void 0) { allowError = false; }
613
+ if (pipeOutput === void 0) { pipeOutput = false; }
557
614
  return new Promise(function (resolve, reject) {
558
615
  if (log)
559
616
  console.log(chalk.cyan(command));
560
- exec(command, options, function (error, stdout, stderr) {
617
+ var child = exec(command, options, function (error, stdout, stderr) {
561
618
  if (error) {
562
619
  if (!allowError) {
563
- reject(error.message);
620
+ reject({ error: error, stdout: stdout, stderr: stderr });
564
621
  return;
565
622
  }
566
623
  else if (log) {
@@ -576,6 +633,10 @@ function execPromise(command, log, allowError, options) {
576
633
  }
577
634
  resolve(result);
578
635
  });
636
+ if (pipeOutput) {
637
+ child.stdout.pipe(process.stdout);
638
+ child.stderr.pipe(process.stderr);
639
+ }
579
640
  });
580
641
  }
581
642
  var replaceVariablesInFile = function (filePath) { return __awaiter(void 0, void 0, void 0, function () {
@@ -599,13 +660,11 @@ var replaceCurlyVariables = function (string) {
599
660
  };
600
661
  var capitalize = function (str) { return str.charAt(0).toUpperCase() + str.toLowerCase().slice(1); };
601
662
  var camelCase = function (str) {
602
- //this version does not replace any capitals already used by the user
603
- var string = str
604
- .replace(/[^A-Za-z0-9]/g, ' ')
605
- .split(' ')
606
- .reduce(function (result, word) { return result + capitalize(word); });
607
- //it also leave the first capital intact
608
- return string;
663
+ var string = str.replace(/[^A-Za-z0-9]/g, ' ').split(' ');
664
+ if (string.length > 1) {
665
+ return string.reduce(function (result, word) { return result + capitalize(word); });
666
+ }
667
+ return str;
609
668
  };
610
669
  var createOntology = function (prefix, uriBase, basePath) {
611
670
  if (basePath === void 0) { basePath = process.cwd(); }
@@ -764,6 +823,33 @@ var createShape = function (name, basePath) {
764
823
  });
765
824
  });
766
825
  };
826
+ var createComponent = function (name, basePath) {
827
+ if (basePath === void 0) { basePath = process.cwd(); }
828
+ return __awaiter(void 0, void 0, void 0, function () {
829
+ var targetFolder, _a, hyphenName, camelCaseName, underscoreName, targetFile, targetFile2, indexPath;
830
+ return __generator(this, function (_b) {
831
+ switch (_b.label) {
832
+ case 0:
833
+ targetFolder = ensureFolderExists(basePath, 'src', 'components');
834
+ _a = setNameVariables(name), hyphenName = _a.hyphenName, camelCaseName = _a.camelCaseName, underscoreName = _a.underscoreName;
835
+ //copy default shape file
836
+ log("Creating files for component '" + name + "'");
837
+ targetFile = path.join(targetFolder, hyphenName + '.tsx');
838
+ fs.copySync(path.join(__dirname, '..', 'defaults', 'component.tsx'), targetFile);
839
+ targetFile2 = path.join(targetFolder, hyphenName + '.scss');
840
+ fs.copySync(path.join(__dirname, '..', 'defaults', 'component.scss'), targetFile2);
841
+ //replace variables in some of the copied files
842
+ return [4 /*yield*/, replaceVariablesInFiles(targetFile, targetFile2)];
843
+ case 1:
844
+ //replace variables in some of the copied files
845
+ _b.sent();
846
+ indexPath = addLineToIndex("import './components/".concat(hyphenName, "';"), 'components');
847
+ log("Created a new component template in ".concat(chalk.magenta(targetFile.replace(basePath, ''))), "Created component stylesheet template in ".concat(chalk.magenta(targetFile2.replace(basePath, ''))), "Added an import of this file from ".concat(chalk.magenta(indexPath)));
848
+ return [2 /*return*/];
849
+ }
850
+ });
851
+ });
852
+ };
767
853
  var createModule = function (name, uriBase, basePath) {
768
854
  if (basePath === void 0) { basePath = process.cwd(); }
769
855
  return __awaiter(void 0, void 0, void 0, function () {
@@ -772,7 +858,7 @@ var createModule = function (name, uriBase, basePath) {
772
858
  switch (_c.label) {
773
859
  case 0:
774
860
  //if ran with npx, basePath will be the root directory of the repository, even if we're executing from a sub folder (the root directory is where node_modules lives and package.json with workspaces)
775
- //so we manually find a modules folder, if it exists we go into that.
861
+ //so we manually find a packages folder, if it exists we go into that.
776
862
  if (fs.existsSync(path.join(basePath, 'modules'))) {
777
863
  basePath = path.join(basePath, 'modules');
778
864
  }
@@ -791,12 +877,12 @@ var createModule = function (name, uriBase, basePath) {
791
877
  // --> match[0] = @dacore/some-mod
792
878
  // --> match[1] = @dacore
793
879
  // --> match[2] = some-mod
794
- //but save full scoped module name under ${module_name}
880
+ //but save full scoped package name under ${module_name}
795
881
  setVariable('module_name', name);
796
882
  //extra variable for clarity (will be same as 'name')
797
883
  setVariable('output_file_name', name);
798
884
  _b = setNameVariables(cleanPackageName), hyphenName = _b.hyphenName, camelCaseName = _b.camelCaseName, underscoreName = _b.underscoreName;
799
- log("Creating new LINCD module '" + name + "'");
885
+ log("Creating new LINCD package '" + name + "'");
800
886
  fs.copySync(path.join(__dirname, '..', 'defaults', 'module'), targetFolder);
801
887
  //replace variables in some of the copied files
802
888
  return [4 /*yield*/, Promise.all([
@@ -815,7 +901,7 @@ var createModule = function (name, uriBase, basePath) {
815
901
  case 1:
816
902
  //replace variables in some of the copied files
817
903
  _c.sent();
818
- //rename these to a file name similar to the module name
904
+ //rename these to a file name similar to the pkg name
819
905
  [
820
906
  'src/ontologies/example-ontology.ts',
821
907
  'src/data/example-ontology.json',
@@ -840,7 +926,7 @@ var createModule = function (name, uriBase, basePath) {
840
926
  })];
841
927
  case 3:
842
928
  _c.sent();
843
- log("Prepared a new LINCD module in ".concat(chalk.magenta(targetFolder)), "Run ".concat(chalk.blueBright('yarn build'), " from this directory to build once"), "Or ".concat(chalk.blueBright('yarn dev'), " to continuously rebuild on file changes"));
929
+ log("Prepared a new LINCD package in ".concat(chalk.magenta(targetFolder)), "Run ".concat(chalk.blueBright('yarn build'), " from this directory to build once"), "Or ".concat(chalk.blueBright('yarn dev'), " to continuously rebuild on file changes"));
844
930
  return [2 /*return*/];
845
931
  }
846
932
  });
@@ -927,7 +1013,7 @@ var buildFailed = function (output) {
927
1013
  }
928
1014
  else
929
1015
  {
930
- console.warn("Invalid LINCD module. Index file should export a packageExports object. See examples.")
1016
+ console.warn("Invalid LINCD package. Index file should export a packageExports object. See examples.")
931
1017
  }
932
1018
 
933
1019
  } else {
@@ -939,20 +1025,21 @@ var register = function (registryURL) {
939
1025
  var pack = JSON.parse(fs.readFileSync(process.cwd() + '/package.json', 'utf8'));
940
1026
  var version = pack.version;
941
1027
  var moduleName = pack.name;
942
- var author = pack.author;
943
- var description = pack.description;
944
- var authorName = pack.author;
945
- if (pack.author.name) {
946
- authorName = pack.author.name;
947
- }
948
- console.log(chalk.cyan('registering ' + authorName + "'s module, " + moduleName + ' ' + version + ' in the LINCD registry'));
1028
+ // let author = pack.author;
1029
+ // let description = pack.description;
1030
+ //
1031
+ // let authorName = pack.author;
1032
+ // if (pack.author.name) {
1033
+ // authorName = pack.author.name;
1034
+ // }
1035
+ console.log(chalk.cyan('registering package ' + moduleName + ' ' + version + ' in the LINCD registry'));
949
1036
  return fetch(registryURL + '/register', {
950
1037
  method: 'POST',
951
1038
  headers: {
952
1039
  Accept: 'application/json, text/plain, */*',
953
1040
  'Content-Type': 'application/json'
954
1041
  },
955
- body: JSON.stringify({ package: moduleName, version: version, description: description })
1042
+ body: JSON.stringify({ package: moduleName, version: version })
956
1043
  })
957
1044
  .then(function (res) { return res.json(); })
958
1045
  .then(function (json) {
@@ -960,7 +1047,7 @@ var register = function (registryURL) {
960
1047
  console.log(chalk.red('Response: ' + json.error));
961
1048
  }
962
1049
  else if (json.result) {
963
- console.log(chalk.cyan('Response: ') + json.result);
1050
+ console.log(chalk.blueBright('Response: ') + json.result);
964
1051
  if (json.warning) {
965
1052
  console.log(chalk.red('Warning: ') + json.warning);
966
1053
  }
@@ -1015,7 +1102,7 @@ var buildModule = function (target, target2, modulePath, logResults) {
1015
1102
  }
1016
1103
  };
1017
1104
  var getLastBuildTime = function (modulePath) {
1018
- return getLastModifiedFile(modulePath + '/@(builds|lib)/**/*.js');
1105
+ return getLastModifiedFile(modulePath + '/@(builds|lib|dist)/**/*.js');
1019
1106
  };
1020
1107
  var getLastModifiedSourceTime = function (modulePath) {
1021
1108
  return getLastModifiedFile(modulePath + '/@(src|data|scss)/**/*', {
@@ -1025,10 +1112,15 @@ var getLastModifiedSourceTime = function (modulePath) {
1025
1112
  var getLastCommitTime = function (modulePath) {
1026
1113
  // console.log(`git log -1 --format=%ci -- ${modulePath}`);
1027
1114
  // process.exit();
1028
- return execPromise("git log -1 --format=%ci -- ".concat(modulePath)).then(function (result) {
1115
+ return execPromise("git log -1 --format=%ci -- ".concat(modulePath))
1116
+ .then(function (result) {
1029
1117
  var lastCommit = new Date(result);
1030
1118
  // console.log(modulePath,result,lastCommit);
1031
1119
  return lastCommit;
1120
+ })["catch"](function (_a) {
1121
+ var error = _a.error, stdout = _a.stdout, stderr = _a.stderr;
1122
+ debugInfo(chalk.red('Git error: ') + error.message.toString());
1123
+ return null;
1032
1124
  });
1033
1125
  };
1034
1126
  var getLastModifiedFile = function (filePath, config) {
@@ -1057,60 +1149,90 @@ var getLastModifiedFile = function (filePath, config) {
1057
1149
  var publishUpdated = function (test) {
1058
1150
  var _this = this;
1059
1151
  if (test === void 0) { test = false; }
1060
- var modules = getLocalLincdModules();
1152
+ var packages = getLocalLincdModules();
1061
1153
  var browserCoreBuilt = false;
1062
1154
  var p = Promise.resolve('');
1063
- modules.forEach(function (module) {
1155
+ var packagesLeft = packages.length;
1156
+ console.log('Checking which packages need to be published by comparing last published date with last git commit');
1157
+ packages.forEach(function (pckg) {
1064
1158
  p = p.then(function (previousResult) {
1065
- log('# Checking module ' + module.moduleName);
1066
- // log('# Requesting ' + 'yarn info '+module.packageName+' --json');
1067
- // return execPromise('yarn info '+module.packageName+' --json').then((output:string) => {
1159
+ progressUpdate(packagesLeft-- + ' packages left. Now checking ' + pckg.moduleName);
1160
+ debugInfo('# Checking package ' + pckg.moduleName);
1161
+ // log('# Requesting ' + 'yarn info '+pkg.packageName+' --json');
1162
+ // return execPromise('yarn info '+pkg.packageName+' --json').then((output:string) => {
1068
1163
  // console.log("Will be requesting npm view from this current working directory:\n"+process.cwd());
1069
- // return execPromise('npm view '+module.packageName+' --json').then((output:string) => {
1070
- return execPromise('yarn info ' + module.packageName + ' --json')
1164
+ // return execPromise('npm view '+pkg.packageName+' --json').then((output:string) => {
1165
+ var shouldPublish;
1166
+ var pack = (0, utils_1.getPackageJSON)(pckg.path);
1167
+ var version = getNextVersion(pack.version);
1168
+ if (pack.private) {
1169
+ shouldPublish = false;
1170
+ debugInfo(chalk.blue('--> is private, skipping'));
1171
+ return previousResult + ' ' + chalk.gray(pckg.moduleName + ' is private\n');
1172
+ }
1173
+ return execPromise('yarn info ' + pckg.packageName + ' --json')
1071
1174
  .then(function (output) { return __awaiter(_this, void 0, void 0, function () {
1072
- var info, lastPublish, lastPublishDate, _a, lastModifiedTime, lastModifiedName, lastModified, lastCommit, res, browserModule;
1073
- return __generator(this, function (_b) {
1074
- switch (_b.label) {
1175
+ var info, lastPublish, lastPublishDate, lastCommit, res, browserModule;
1176
+ return __generator(this, function (_a) {
1177
+ switch (_a.label) {
1075
1178
  case 0:
1076
1179
  try {
1077
1180
  if (output == '') {
1078
- // console.warn("No response (empty) from `yarn info`");
1079
- throw new Error('Empty response from `npm view`');
1080
- return [2 /*return*/];
1181
+ debugInfo('No response (empty) from `yarn info`. This package was probably not published before');
1182
+ // throw new Error('Empty response from `yarn info`. This pkg was probably not published before');
1183
+ // return;
1184
+ shouldPublish = true;
1185
+ //don't patch the version number (default, see above), use the current version
1186
+ version = pack.version;
1187
+ }
1188
+ else {
1189
+ info = JSON.parse(output);
1081
1190
  }
1082
- info = JSON.parse(output);
1083
1191
  // var stats = fs.statSync(path.join(moduleDirectory));
1084
1192
  // var files = fs.readdirSync(path.join(moduleDirectory,'src'));
1085
1193
  }
1086
1194
  catch (err) {
1087
- chalk.red(module.moduleName + ' failed: ' + err.message + '\n');
1195
+ chalk.red(pckg.moduleName + ' failed: ' + err.message + '\n');
1088
1196
  console.warn('Returned JSON from npm: ' + output);
1089
- return [2 /*return*/, previousResult + ' ' + chalk.red(module.moduleName + ' failed: ' + err.message + '\n')];
1197
+ return [2 /*return*/, previousResult + ' ' + chalk.red(pckg.moduleName + ' failed: ' + err.message + '\n')];
1090
1198
  }
1199
+ if (!info) return [3 /*break*/, 2];
1091
1200
  lastPublish = info.data.time[info.data.version];
1092
1201
  lastPublishDate = new Date(lastPublish);
1093
- _a = getLastModifiedSourceTime(module.path), lastModifiedTime = _a.lastModifiedTime, lastModifiedName = _a.lastModifiedName, lastModified = _a.lastModified;
1094
- return [4 /*yield*/, getLastCommitTime(module.path)];
1202
+ return [4 /*yield*/, getLastCommitTime(pckg.path)];
1095
1203
  case 1:
1096
- lastCommit = _b.sent();
1097
- console.log(lastPublishDate.toDateString() + ' ' + lastPublishDate.toTimeString() + ' published ' + info.data.version);
1098
- console.log(lastCommit.toDateString() + ' ' + new Date(lastCommit).toTimeString() + ' source last committed');
1099
- // console.log(lastModified.toDateString() + ' ' + new Date(lastModified).toTimeString() + ' source ' + lastModifiedName + ' last edited');
1100
- //NOTE: removed lastModified, because switching branches will say that the file was modified and cause everything to publish
1101
- //SO: now you NEED TO commit before it picks up that you should publish
1102
- //|| lastPublishDate.getTime() < lastModified.getTime()
1103
- if (lastPublishDate.getTime() < lastCommit.getTime()) {
1104
- res = executeSingleBuild(module, previousResult, test, info);
1105
- if (module.moduleName == 'browser-core') {
1204
+ lastCommit = _a.sent();
1205
+ if (!lastCommit) {
1206
+ shouldPublish = false;
1207
+ debugInfo('Could not determine last git commit');
1208
+ return [2 /*return*/, previousResult + ' ' + chalk.red(pckg.moduleName + ' - could not determine last commit\n')];
1209
+ }
1210
+ else {
1211
+ //NOTE: removed lastModified, because switching branches will say that the file was modified and cause everything to publish
1212
+ //SO: now you NEED TO commit before it picks up that you should publish
1213
+ shouldPublish = lastPublishDate.getTime() < lastCommit.getTime();
1214
+ if (shouldPublish) {
1215
+ debugInfo(lastPublishDate.toDateString() +
1216
+ ' ' +
1217
+ lastPublishDate.toTimeString() +
1218
+ ' published ' +
1219
+ info.data.version);
1220
+ debugInfo(lastCommit.toDateString() + ' ' + new Date(lastCommit).toTimeString() + ' source last committed');
1221
+ }
1222
+ }
1223
+ _a.label = 2;
1224
+ case 2:
1225
+ if (shouldPublish) {
1226
+ res = publishPackage(pckg, previousResult, test, info, version);
1227
+ if (pckg.moduleName == 'browser-core') {
1106
1228
  browserCoreBuilt = true;
1107
1229
  }
1108
1230
  //when publishing core, also make sure to publish browser-core
1109
- if (module.moduleName == 'core' && !browserCoreBuilt) {
1110
- browserModule = modules.find(function (m) { return m.moduleName == 'browser-core'; });
1231
+ if (pckg.moduleName == 'core' && !browserCoreBuilt) {
1232
+ browserModule = packages.find(function (m) { return m.moduleName == 'browser-core'; });
1111
1233
  return [2 /*return*/, Promise.resolve(res).then(function (previousResult) {
1112
- log('# Automatically also publishing module browser-core');
1113
- return executeSingleBuild(browserModule, previousResult, test);
1234
+ log('# Automatically also publishing package browser-core');
1235
+ return publishPackage(browserModule, previousResult, test);
1114
1236
  })];
1115
1237
  }
1116
1238
  return [2 /*return*/, res];
@@ -1118,132 +1240,194 @@ var publishUpdated = function (test) {
1118
1240
  return [2 /*return*/, previousResult];
1119
1241
  }
1120
1242
  });
1121
- }); })["catch"](function (err) {
1122
- console.log(err);
1123
- return previousResult + ' ' + chalk.red(module.moduleName + ' failed\n');
1243
+ }); })["catch"](function (_a) {
1244
+ var error = _a.error, stdout = _a.stdout, stderr = _a.stderr;
1245
+ console.log(error.message);
1246
+ return previousResult + ' ' + chalk.red(pckg.moduleName + ' failed\n');
1124
1247
  });
1125
1248
  });
1126
1249
  });
1127
1250
  return p.then(function (messages) {
1128
1251
  if (messages == '') {
1129
- console.log('All published modules are already up-to-date.');
1252
+ console.log('All published packages are already up-to-date.');
1130
1253
  }
1131
1254
  else {
1132
1255
  console.log('Summary: \n' + messages);
1133
1256
  }
1134
1257
  });
1135
1258
  };
1136
- var executeSingleBuild = function (module, previousResult, test, info) {
1137
- var nextVersion = info ? getNextVersion(info.data.version) : '';
1138
- console.log(chalk.blue('--> ' + (test ? 'should publish' : 'publishing') + ' ' + module.moduleName + ' ' + nextVersion));
1259
+ var publishPackage = function (pkg, previousResult, test, info, publishVersion) {
1260
+ if (!publishVersion) {
1261
+ publishVersion = info ? getNextVersion(info.data.version) : '';
1262
+ }
1263
+ if (test) {
1264
+ debugInfo('should publish ' + pkg.moduleName + ' ' + publishVersion);
1265
+ }
1266
+ else {
1267
+ console.log(chalk.blue('publishing ' + pkg.moduleName + ' ' + publishVersion));
1268
+ }
1139
1269
  if (!test) {
1140
- return execPromise('cd ' + module.path + ' && yarn lincd register', true)
1270
+ return execPromise("cd ".concat(pkg.path, " && yarn publish").concat(publishVersion ? ' --new-version ' + publishVersion : ''), true, false, {}, true)
1141
1271
  .then(function (res) {
1142
1272
  if (res.indexOf('Aborted due to warnings') !== -1 ||
1143
1273
  res.indexOf('Could not publish') !== -1 ||
1144
1274
  res.indexOf("Couldn't publish") !== -1) {
1145
1275
  console.log(res);
1146
- return previousResult + ' ' + chalk.red(module.moduleName + ' failed\n');
1276
+ return previousResult + ' ' + chalk.red(pkg.moduleName + ' failed\n');
1147
1277
  }
1148
- console.log(chalk.green('Successfully published ' + nextVersion));
1149
- return previousResult + ' ' + chalk.green(module.moduleName + ' published ' + nextVersion + '\n');
1150
- })["catch"](function (err) {
1151
- console.log(chalk.red('Failed to publish: ' + err));
1152
- return chalk.red('Failed to publish: ' + err);
1278
+ console.log(chalk.green('Successfully published ' + pkg.path + ' ' + publishVersion));
1279
+ return previousResult + ' ' + chalk.green(pkg.moduleName + ' published ' + publishVersion + '\n');
1280
+ })["catch"](function (_a) {
1281
+ var error = _a.error, stdout = _a.stdout, stderr = _a.stderr;
1282
+ console.log(chalk.red('Failed to publish: ' + error.message));
1283
+ return previousResult + ' ' + chalk.red(pkg.moduleName + ' failed to publish\n');
1153
1284
  });
1154
1285
  }
1155
1286
  else {
1156
1287
  //when testing what needs to be published
1157
- return previousResult + ' ' + chalk.blue(module.moduleName + ' should publish\n');
1288
+ return previousResult + ' ' + chalk.blue(pkg.moduleName + ' should publish\n');
1158
1289
  }
1159
1290
  };
1160
1291
  var buildUpdated = function (back, target, target2, test) {
1161
1292
  if (test === void 0) { test = false; }
1162
- // back = back || 1;
1163
- // return execPromise(`git log -${back} --format=%ci`).then((result) => {
1164
- // let now = new Date();
1165
- var previousResult = '';
1166
- log((test ? 'Checking which modules' : 'Building all modules that') + ' have been changed since their last built ');
1167
- var modules = getLocalLincdModules();
1168
- //TODO: sort all these modules in the order of their dependencies.
1169
- // To do so, see build-all command and put some of the functionality (like getting modules that depend on a module) in reusable functions
1170
- var p = Promise.resolve('');
1171
- modules.forEach(function (module) {
1172
- var moduleName = module.moduleName;
1173
- p = p
1174
- .then(function (previousResult) {
1175
- var lastModifiedSource = getLastModifiedSourceTime(module.path);
1176
- var lastModifiedBundle = getLastBuildTime(module.path);
1177
- // console.log(module.path,lastModifiedSource.lastModifiedTime,lastModifiedBundle.lastModifiedTime);
1178
- // console.log(module.path,new Date(lastModifiedSource.lastModified).toString(),new Date(lastModifiedBundle.lastModified).toString());
1179
- console.log('# Checking module ' + moduleName);
1180
- if (lastModifiedSource.lastModifiedTime > lastModifiedBundle.lastModifiedTime) {
1181
- //TODO: when building a module, also rebuild all modules that depend on this module.. and iteratively build modules that depend on those modules..
1182
- // log(moduleName+' modified since last commit on '+now.toString());
1183
- console.log(chalk.cyan('Last modified source: ' +
1184
- lastModifiedSource.lastModifiedName +
1185
- ' on ' +
1186
- lastModifiedSource.lastModified.toString()));
1187
- console.log(chalk.cyan('Last build: ' +
1188
- (lastModifiedBundle && typeof lastModifiedBundle.lastModified !== 'undefined'
1189
- ? lastModifiedBundle.lastModified.toString()
1190
- : 'never')));
1191
- log('--> ' + (test ? 'need to build ' : 'building ') + moduleName);
1192
- if (!test) {
1193
- return execPromise('cd ' + module.path + ' && yarn build' + (target ? ' ' + target : '') + (target2 ? ' ' + target2 : '')).then(function (res) {
1194
- if (res.indexOf('Aborted due to warnings') !== -1 || res.indexOf('Fatal error') !== -1) {
1195
- console.log(res);
1196
- return previousResult + ' ' + chalk.red(moduleName + ' failed\n');
1293
+ return __awaiter(this, void 0, void 0, function () {
1294
+ var previousResult, packages, jsonldPkgUpdated, cliPkgUpdated, rebuildAllModules, packagesLeft, p;
1295
+ var _this = this;
1296
+ return __generator(this, function (_a) {
1297
+ switch (_a.label) {
1298
+ case 0:
1299
+ previousResult = '';
1300
+ log(test ? 'Checking which packages need to be rebuild' : 'Building updated packages');
1301
+ packages = getLocalLincdModuleMap();
1302
+ jsonldPkgUpdated = needsRebuilding(packages.get('lincd-jsonld'));
1303
+ cliPkgUpdated = needsRebuilding(packages.get('lincd-cli'));
1304
+ if (!(jsonldPkgUpdated || cliPkgUpdated)) return [3 /*break*/, 2];
1305
+ return [4 /*yield*/, execPromise('yarn build-core', false, false, {}, true)];
1306
+ case 1:
1307
+ _a.sent();
1308
+ _a.label = 2;
1309
+ case 2:
1310
+ rebuildAllModules = false;
1311
+ if (cliPkgUpdated) {
1312
+ rebuildAllModules = true;
1313
+ log(chalk.magenta('Rebuilding all modules because the build tools (lincd-cli) got updated'));
1314
+ }
1315
+ packagesLeft = packages.size;
1316
+ runOnPackagesGroupedByDependencies(packages, function (packageGroup, dependencies) {
1317
+ // console.log('Now checking: ' + chalk.blue(packageGroup.map((i) => i.moduleName)));
1318
+ // console.log((packagesLeft) + " packages left.");
1319
+ packagesLeft = packagesLeft - packageGroup.length;
1320
+ return function (pkg) { return __awaiter(_this, void 0, void 0, function () {
1321
+ var needRebuild;
1322
+ return __generator(this, function (_a) {
1323
+ debugInfo('# Checking package ' + pkg.moduleName);
1324
+ needRebuild = needsRebuilding(pkg, true);
1325
+ if (pkg.moduleName === 'lincd-jsonld' && jsonldPkgUpdated) {
1326
+ needRebuild = true;
1327
+ }
1328
+ // console.log(pkg.path,lastModifiedSource.lastModifiedTime,lastModifiedBundle.lastModifiedTime);
1329
+ // console.log(pkg.path,new Date(lastModifiedSource.lastModified).toString(),new Date(lastModifiedBundle.lastModified).toString());
1330
+ if (needRebuild || rebuildAllModules) {
1331
+ //TODO: when building a pkg, also rebuild all packages that depend on this package.. and iteratively build packages that depend on those packages..
1332
+ // log(moduleName+' modified since last commit on '+now.toString());
1333
+ if (test) {
1334
+ debugInfo('Need to build ' + pkg.moduleName);
1335
+ return [2 /*return*/, chalk.blue(pkg.moduleName + ' should be build')];
1336
+ }
1337
+ log('Building ' + pkg.moduleName);
1338
+ return [2 /*return*/, execPromise('cd ' + pkg.path + ' && yarn build' + (target ? ' ' + target : '') + (target2 ? ' ' + target2 : ''))
1339
+ .then(function (res) {
1340
+ debugInfo(chalk.green(pkg.moduleName + ' successfully built'));
1341
+ return chalk.green(pkg.moduleName + ' built');
1342
+ })["catch"](function (_a) {
1343
+ var error = _a.error, stdout = _a.stdout, stderr = _a.stderr;
1344
+ warn('Failed to build ' + pkg.moduleName);
1345
+ console.log(stdout);
1346
+ var dependentModules = getDependentPackages(dependencies, pkg);
1347
+ if (dependentModules.length > 0) {
1348
+ // printBuildResults(failedModules, done);
1349
+ warn(chalk.red(pkg.moduleName + ' build failed'));
1350
+ warn('Stopping build-updated process because ' +
1351
+ dependentModules.length +
1352
+ ' other packages depend on this module.\n'); //"+dependentModules.map(d => d.moduleName).join(", ")));
1353
+ process.exit(1);
1354
+ }
1355
+ })];
1356
+ }
1357
+ return [2 /*return*/];
1358
+ });
1359
+ }); };
1360
+ }, function (results) {
1361
+ if (results.length) {
1362
+ log('Summary:');
1363
+ log(results.join('\n'));
1364
+ }
1365
+ else {
1366
+ log(chalk.green('Nothing to rebuild'));
1197
1367
  }
1198
- console.log(chalk.green(moduleName + ' bundles successfully built'));
1199
- return previousResult + ' ' + chalk.green(moduleName + ' built\n');
1200
1368
  });
1201
- }
1202
- return previousResult + ' ' + chalk.blue(moduleName + ' should be build\n');
1369
+ return [2 /*return*/];
1203
1370
  }
1204
- return previousResult;
1205
- })["catch"](function (err) {
1206
- console.log(err);
1207
- return previousResult + ' ' + chalk.red(moduleName + ' failed\n');
1208
1371
  });
1209
1372
  });
1210
- return p.then(function (messages) {
1211
- if (messages == '') {
1212
- console.log(chalk.green('Nothing to rebuild.'));
1213
- }
1214
- else {
1215
- console.log('Summary: \n' + messages);
1216
- }
1217
- });
1218
- // });
1373
+ };
1374
+ var needsRebuilding = function (pkg, logDetailsIfTrue) {
1375
+ if (logDetailsIfTrue === void 0) { logDetailsIfTrue = false; }
1376
+ var lastModifiedSource = getLastModifiedSourceTime(pkg.path);
1377
+ var lastModifiedBundle = getLastBuildTime(pkg.path);
1378
+ var result = lastModifiedSource.lastModifiedTime > lastModifiedBundle.lastModifiedTime;
1379
+ if (logDetailsIfTrue) {
1380
+ debugInfo(chalk.cyan('Last modified source: ' +
1381
+ lastModifiedSource.lastModifiedName +
1382
+ ' on ' +
1383
+ lastModifiedSource.lastModified.toString()));
1384
+ debugInfo(chalk.cyan('Last build: ' +
1385
+ (lastModifiedBundle && typeof lastModifiedBundle.lastModified !== 'undefined'
1386
+ ? lastModifiedBundle.lastModified.toString()
1387
+ : 'never')));
1388
+ }
1389
+ return result;
1219
1390
  };
1220
1391
  var printBuildResults = function (failed, done) {
1221
- log('Build results: '
1222
- + chalk.green(__spreadArray([], __read(done), false).map(function (m) { return m.moduleName; }).join(', '))
1223
- + (failed.length > 0 ? (', ' + chalk.red(failed.join(', '))) : '')
1224
- + '\n');
1392
+ log('Successfully built: ' + chalk.green(__spreadArray([], __read(done), false).map(function (m) { return m.moduleName; }).join(', ')) + '\n');
1393
+ if (failed.length > 0) {
1394
+ warn('Failed to build: ' + chalk.red(failed.join(', ')) + '\n');
1395
+ }
1225
1396
  };
1226
- var executeCommandForEachModule = function (modules, command, includedSpaces, excludedSpaces) {
1227
- //if a specific set of modules is given
1228
- if (includedSpaces) {
1229
- //filter modules, so that we only execute on the modules as provided in the command
1230
- includedSpaces = includedSpaces.split(',');
1231
- modules = modules.filter(function (module) { return includedSpaces.indexOf(module.moduleName) !== -1; });
1232
- log('Applying to included spaces');
1397
+ var executeCommandForEachModule = function (packages, command, filterMethod, filterValue) {
1398
+ //if a specific set of packages is given
1399
+ if (filterMethod == 'exclude') {
1400
+ //filter packages, so that we only execute on the packages as provided in the command
1401
+ log('Excluding ' + filterValue);
1402
+ filterValue = filterValue.split(',');
1403
+ packages = packages.filter(function (pkg) { return filterValue.indexOf(pkg.moduleName) === -1; });
1233
1404
  }
1234
- //if a specific set of modules is given
1235
- if (excludedSpaces) {
1236
- //filter modules, so that we only execute on the modules as provided in the command
1237
- excludedSpaces = excludedSpaces.split(',');
1238
- modules = modules.filter(function (module) { return excludedSpaces.indexOf(module.moduleName) === -1; });
1239
- log('Filtering excluded spaces');
1405
+ var startFrom;
1406
+ //by default start executing, unless 'from' is given
1407
+ var executing = true;
1408
+ //option to start from a specific pkg in the stack
1409
+ if (filterMethod == 'from') {
1410
+ startFrom = filterValue;
1411
+ if (startFrom) {
1412
+ console.log(chalk.blue('Will skip ahead to ' + startFrom));
1413
+ }
1414
+ var seen_1 = false;
1415
+ packages = packages.filter(function (pkg) {
1416
+ if (!seen_1 && (pkg.moduleName == startFrom || pkg.packageName == startFrom)) {
1417
+ seen_1 = true;
1418
+ }
1419
+ return seen_1;
1420
+ });
1240
1421
  }
1241
- log("Executing '" + command + "' on modules " + modules.map(function (m) { return m.moduleName; }).join(', '));
1422
+ log("Executing '" +
1423
+ chalk.blueBright(command) +
1424
+ "' on packages " +
1425
+ chalk.magenta(packages.map(function (m) { return m.moduleName; }).join(', ')));
1242
1426
  var p = Promise.resolve(true);
1243
- modules.forEach(function (module) {
1427
+ packages.forEach(function (pkg) {
1244
1428
  p = p.then(function () {
1245
- log('# Module ' + module.moduleName + ' - ' + module.path);
1246
- return execp('cd ' + module.path + ' && ' + command);
1429
+ log('# Package ' + chalk.magenta(pkg.moduleName));
1430
+ return execp('cd ' + pkg.path + ' && ' + command);
1247
1431
  });
1248
1432
  });
1249
1433
  return p;
@@ -1257,7 +1441,7 @@ var executeCommandForModule = function (moduleName, command) {
1257
1441
  return execp('cd ' + moduleDetails.path + ' && yarn lincd' + (command ? ' ' + command : ''));
1258
1442
  }
1259
1443
  else {
1260
- warn("Could not find a module who's name (partially) matched " + chalk.cyan(moduleName));
1444
+ warn("Could not find a pkg who's name (partially) matched " + chalk.cyan(moduleName));
1261
1445
  }
1262
1446
  };
1263
1447
  program.parse(process.argv);