@9of9solutions/replikator 1.0.14 → 1.0.17

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.
Files changed (2) hide show
  1. package/main.js +198 -57
  2. package/package.json +2 -8
package/main.js CHANGED
@@ -4,6 +4,7 @@ import fs from 'fs-extra';
4
4
  import chokidar from 'chokidar';
5
5
  import inquirer from 'inquirer';
6
6
  import url from 'url';
7
+ import { execa } from 'execa';
7
8
  const projectRoot = process.cwd();
8
9
  const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
9
10
  const pkgPath = path.join(__dirname, 'package.json');
@@ -23,7 +24,7 @@ async function getReplicatedFileHeader(path) {
23
24
  * Edit at '${path}'
24
25
  *
25
26
  ******************************************************/\n`
26
-
27
+
27
28
  }
28
29
 
29
30
  //We save configuration in root package.json
@@ -76,17 +77,17 @@ async function findApplications(root) {
76
77
  /**
77
78
  * Loads the config if it exists, or creates it via prompt.
78
79
  * The stored config contains paths relative to process.cwd().
79
- * Returns an object { src, targets, ignore } where src/targets are absolute paths.
80
+ * Returns an object { src, targets, include } where src/targets are absolute paths.
80
81
  */
81
82
  async function loadConfigOrPrompt(prompt) {
82
83
  if (await fs.pathExists(PACKAGE_JSON_ROOT_PATH)) {
83
84
  if (!prompt) {
84
85
  const raw = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
85
- if (raw.replikator && raw.replikator.src && raw.replikator.targets && raw.replikator.ignore) {
86
+ if (raw.replikator && raw.replikator.src && raw.replikator.targets && raw.replikator.include) {
86
87
  return {
87
88
  src: path.resolve(projectRoot, raw.replikator.src),
88
89
  targets: raw.replikator.targets.map(rel => path.resolve(projectRoot, rel)),
89
- ignore: raw.replikator.ignore
90
+ include: raw.replikator.include
90
91
  };
91
92
  }
92
93
  }
@@ -202,95 +203,235 @@ async function loadConfigOrPrompt(prompt) {
202
203
 
203
204
 
204
205
  const package_json = await fs.readJson(PACKAGE_JSON_ROOT_PATH);
205
- const config = { ...package_json, replikator: { src: relSrc, targets: relTargets, ignore: [] } };
206
+ const config = { ...package_json, replikator: { src: relSrc, targets: relTargets, include: {} } };
206
207
  await fs.writeJson(PACKAGE_JSON_ROOT_PATH, config, { spaces: 2 });
207
208
  console.log(`Configuration saved in ${path.relative(projectRoot, PACKAGE_JSON_ROOT_PATH)}`);
208
209
 
209
- return { src: absSrc, targets: absTargets, ignore: [] };
210
+ return { src: absSrc, targets: absTargets, include: [] };
211
+ }
212
+
213
+ /**
214
+ * Replikator run command
215
+ * @param {*} prompt - Should init config or no
216
+ */
217
+ async function run(prompt) {
218
+ const { src, targets, include } = await loadConfigOrPrompt(prompt);
219
+ await Promise.all(
220
+ targets.map(async dest => {
221
+ await fs.remove(dest)
222
+ await fs.ensureDir(dest);
223
+ const relDest = path.relative(projectRoot, dest);
224
+ const patterns = include?.[relDest] || [];
225
+
226
+ const filterFn = srcFile => {
227
+ const rel = path.relative(src, srcFile);
228
+ console.log(rel)
229
+ return patterns.filter(p => rel.startsWith(p)).length > 0;
230
+ };
231
+
232
+ console.log(dest)
233
+ await fs.copy(src, dest, { overwrite: true, filter: filterFn });
234
+
235
+ if ((await fs.lstat(src)).isFile()) {
236
+ const data = await fs.readFile(src);
237
+ const fd = await fs.open(dest, 'w+');
238
+ const header = Buffer.from(await getReplicatedFileHeader(src));
239
+ await fs.write(fd, header, 0, header.length, 0);
240
+ await fs.write(fd, data, 0, data.length, header.length);
241
+ await fs.chmod(dest, 0o444);
242
+ }
243
+ })
244
+ );
245
+
246
+ console.log('Initial copy completed.');
247
+
248
+ const watcher = chokidar.watch(src, { persistent: true });
249
+ watcher
250
+ .on('add', p => syncFile('add', p, src, targets, include))
251
+ .on('change', p => syncFile('change', p, src, targets, include))
252
+ .on('unlink', p => syncFile('unlink', p, src, targets, include))
253
+ .on('error', e => console.error('Watcher error:', e));
254
+ }
255
+
256
+ /**
257
+ * Show infos of replikator
258
+ */
259
+ async function showInfo() {
260
+ console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
261
+ console.log("");
262
+ console.log("Usage: rpk [command]");
263
+ console.log("");
264
+ console.log("Commands:");
265
+ console.log(" init Command used to init replikator configuration.");
266
+ console.log(" run Command used to run replikator.");
267
+ console.log(" update Command used to update replikator.");
268
+ console.log(" include Command used to include files for selected apps.");
269
+ process.exit(0);
210
270
  }
211
271
 
212
272
  /**
213
273
  * Starts the initial copy and then sets up the watcher.
214
274
  */
215
275
  async function main() {
216
- let prompt = false;
217
276
  if (process.argv.length > 2) {
218
277
  switch (process.argv[2]) {
219
278
  case "init":
220
- prompt = true
279
+ await run(true);
221
280
  break;
222
281
  case "run":
223
- prompt = false
282
+ await run(false);
224
283
  break;
225
- case "clean":
226
- console.log('Cleaning...');
227
- console.log('\x1b[32mCleaning is complete.\x1b[0m');
228
- process.exit(0);
284
+ case "update":
285
+ await updateRpk();
286
+ break;
287
+ case "include":
288
+ await includeRpk();
289
+ break;
290
+ default:
291
+ await showInfo();
292
+ break
229
293
  }
230
294
  } else {
231
- console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
232
- console.log("");
233
- console.log("Usage: rpk [command]");
234
- console.log("");
235
- console.log("Commands:");
236
- console.log(" init Command used to init replikator configuration.");
237
- console.log(" run Command used to run replikator.");
238
- process.exit(0);
295
+ await showInfo();
239
296
  }
240
- const { src, targets, ignore } = await loadConfigOrPrompt(prompt);
241
297
 
242
- await Promise.all(
243
- targets.map(dest =>
244
- fs.ensureDir(dest).then(async () => {
245
- await fs.copy(src, dest, { overwrite: true })
246
- if((await fs.lstat(src)).isFile()) {
247
- const data = await fs.readFile(src);
248
- const fd = await fs.open(dest, 'w+');
249
- const buffer = Buffer.from(await getReplicatedFileHeader(src));
250
- await fs.write(fd, buffer, 0, buffer.length, 0);
251
- await fs.write(fd, data, 0, data.length, buffer.length);
252
- await fs.chmod(dest, 0o444)
253
- }
254
- }
255
- )
256
- )
257
- );
258
- console.log('Initial copy completed.');
259
298
 
260
- const watcher = chokidar.watch(src, { ignored: ignore, persistent: true });
261
- watcher
262
- .on('add', p => syncFile('add', p, src, targets))
263
- .on('change', p => syncFile('change', p, src, targets))
264
- .on('unlink', p => syncFile('unlink', p, src, targets))
265
- .on('error', e => console.error('Watcher error:', e));
266
299
  }
267
300
 
301
+ /**
302
+ * Update the CLI to the last available version.
303
+ */
304
+ async function updateRpk() {
305
+ const ua = process.env.npm_config_user_agent || '';
306
+ let cmd, args;
307
+
308
+ if (ua.startsWith('pnpm')) {
309
+ cmd = 'pnpm';
310
+ args = ['add', '-g', '@9of9solutions/replikator@latest', '-w'];
311
+ } else if (ua.startsWith('yarn')) {
312
+ cmd = 'yarn';
313
+ args = ['global', 'add', '@9of9solutions/replikator@latest'];
314
+ } else {
315
+ cmd = 'npm';
316
+ args = ['install', '-g', '@9of9solutions/replikator@latest'];
317
+ }
318
+
319
+ try {
320
+ await execa(cmd, args, { stdio: 'inherit' });
321
+ const newVersion = await getVersion();
322
+ console.log(green(`RPK CLI updated to version ${newVersion}`));
323
+ } catch (err) {
324
+ console.log(red(`Failed to update RPK CLI: ${err.message}`));
325
+ process.exit(1);
326
+ }
327
+ }
328
+
329
+ const green = txt => `\x1b[32m${txt}\x1b[0m`;
330
+ const red = txt => `\x1b[31m${txt}\x1b[0m`;
331
+
268
332
  /**
269
333
  * Syncs a file that was added/modified/deleted to all targets.
270
334
  */
271
- async function syncFile(event, filePath, srcDir, targets) {
335
+ async function syncFile(event, filePath, srcDir, targets, include) {
272
336
  const rel = path.relative(srcDir, filePath);
273
337
  await Promise.all(targets.map(async destRoot => {
274
338
  const destPath = path.join(destRoot, rel);
275
339
  if (event === 'unlink') {
276
340
  await fs.remove(destPath);
277
- console.log(`Deleted: ${rel}`);
278
341
  } else {
279
- await fs.ensureDir(path.dirname(destPath));
280
- await fs.copy(filePath, destPath, { overwrite: true });
281
- if((await fs.lstat(filePath)).isFile()) {
282
- const data = await fs.readFile(filePath);
283
- const fd = await fs.open(destPath, 'w+');
284
- const buffer = Buffer.from(await getReplicatedFileHeader(filePath));
285
- await fs.write(fd, buffer, 0, buffer.length, 0);
286
- await fs.write(fd, data, 0, data.length, buffer.length);
287
- await fs.chmod(destPath, 0o444)
342
+ const relDest = path.relative(projectRoot, destRoot);
343
+ const patterns = include?.[relDest] || [];
344
+ if (patterns.filter(p => (rel).startsWith(p)).length > 0) {
345
+ await fs.ensureDir(path.dirname(destPath));
346
+ await fs.copy(filePath, destPath, { overwrite: true });
347
+ if ((await fs.lstat(filePath)).isFile()) {
348
+ const data = await fs.readFile(filePath);
349
+ const fd = await fs.open(destPath, 'w+');
350
+ const buffer = Buffer.from(await getReplicatedFileHeader(filePath));
351
+ await fs.write(fd, buffer, 0, buffer.length, 0);
352
+ await fs.write(fd, data, 0, data.length, buffer.length);
353
+ await fs.chmod(destPath, 0o444)
354
+ }
288
355
  }
289
- console.log(`${event === 'add' ? 'Added' : 'Updated'}: ${rel}`);
356
+
290
357
  }
291
358
  }));
292
359
  }
293
360
 
361
+ /**
362
+ * Setup included files or directories for apps
363
+ */
364
+ async function includeRpk() {
365
+ const rawPkg = await fs.readJson(PACKAGE_JSON_ROOT_PATH, 'utf8');
366
+ const cfg = rawPkg.replikator;
367
+ if (!cfg || !cfg.src || !Array.isArray(cfg.targets)) {
368
+ console.log(red('No Replikator configuration found. Please run `rpk init` first.'));
369
+ process.exit(1);
370
+ }
371
+
372
+ const absSrc = path.resolve(projectRoot, cfg.src);
373
+ const absTargets = cfg.targets.map(rel => path.resolve(projectRoot, rel));
374
+
375
+ const apps = await findApplications(projectRoot);
376
+ const choicesApps = absTargets.map(absT => {
377
+ const match = apps.find(a => path.join(a.src, SHARED_PATH) === absT);
378
+ return {
379
+ name: match ? match.name : path.relative(projectRoot, absT),
380
+ value: absT
381
+ };
382
+ });
383
+
384
+ const { selectedApps } = await inquirer.prompt([{
385
+ type: 'checkbox',
386
+ name: 'selectedApps',
387
+ message: 'Select applications on which to apply include:',
388
+ choices: choicesApps,
389
+ validate(ans) {
390
+ return ans.length > 0 ? true : 'You must choose at least one application.';
391
+ }
392
+ }]);
393
+
394
+ async function walk(dir, base = '') {
395
+ const entries = [];
396
+ const children = await fs.readdir(dir, { withFileTypes: true });
397
+
398
+ const hasFile = children.some(c => c.isFile() && /\.(ts|tsx)$/.test(c.name));
399
+ if (hasFile && base !== '') {
400
+ entries.push(base);
401
+ }
402
+
403
+ for (const ent of children) {
404
+ if (ent.isDirectory() && !ent.name.includes('node_modules')) {
405
+ const rel = path.join(base, ent.name);
406
+ const full = path.join(dir, ent.name);
407
+ entries.push(...await walk(full, rel));
408
+ }
409
+ }
410
+
411
+ return entries;
412
+ }
413
+
414
+ const allEntries = await walk(absSrc);
415
+
416
+ const { toinclude } = await inquirer.prompt([{
417
+ type: 'checkbox',
418
+ name: 'toinclude',
419
+ message: 'Select directories (relative to src) to include:',
420
+ choices: allEntries.map(rel => ({ name: rel, value: rel })),
421
+ validate(ans) {
422
+ return ans.length > 0 ? true : 'You must choose at least one entry to include.';
423
+ }
424
+ }]);
425
+
426
+ rawPkg.replikator.include = rawPkg.replikator.include || {};
427
+ for (const absT of selectedApps) {
428
+ const relT = path.relative(projectRoot, absT);
429
+ rawPkg.replikator.include[relT] = toinclude;
430
+ }
431
+ await fs.writeJson(PACKAGE_JSON_ROOT_PATH, rawPkg, { spaces: 2 });
432
+ console.log(green(`Inclusion config updated for ${selectedApps.length} app(s).`));
433
+ }
434
+
294
435
  main().catch(err => {
295
436
  console.error('Fatal error:', err);
296
437
  process.exit(1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@9of9solutions/replikator",
3
- "version": "1.0.14",
3
+ "version": "1.0.17",
4
4
  "type": "module",
5
5
  "main": "main.js",
6
6
  "bin": {
@@ -25,14 +25,8 @@
25
25
  "dependencies": {
26
26
  "commander": "^13.1.0",
27
27
  "degit": "^2.8.4",
28
+ "execa": "^9.5.2",
28
29
  "inquirer": "^8.2.6",
29
30
  "winston": "^3.17.0"
30
- },
31
- "replikator": {
32
- "src": "packages/shared",
33
- "targets": [
34
- "apps/app1/src/shared"
35
- ],
36
- "ignore": []
37
31
  }
38
32
  }