@9of9solutions/replikator 1.0.14 → 1.0.16

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 +186 -52
  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
@@ -209,88 +210,221 @@ async function loadConfigOrPrompt(prompt) {
209
210
  return { src: absSrc, targets: absTargets, ignore: [] };
210
211
  }
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, ignore } = 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 = ignore?.[relDest] || [];
225
+
226
+ const filterFn = srcFile => {
227
+ const rel = path.relative(src, srcFile) + "/";
228
+ return patterns.filter(p => rel.startsWith(p)).length === 0;
229
+ };
230
+
231
+ console.log(dest)
232
+ await fs.copy(src, dest, { overwrite: true, filter: filterFn });
233
+
234
+ if ((await fs.lstat(src)).isFile()) {
235
+ const data = await fs.readFile(src);
236
+ const fd = await fs.open(dest, 'w+');
237
+ const header = Buffer.from(await getReplicatedFileHeader(src));
238
+ await fs.write(fd, header, 0, header.length, 0);
239
+ await fs.write(fd, data, 0, data.length, header.length);
240
+ await fs.chmod(dest, 0o444);
241
+ }
242
+ })
243
+ );
244
+
245
+ console.log('Initial copy completed.');
246
+
247
+ const watcher = chokidar.watch(src, { persistent: true });
248
+ watcher
249
+ .on('add', p => syncFile('add', p, src, targets, ignore))
250
+ .on('change', p => syncFile('change', p, src, targets, ignore))
251
+ .on('unlink', p => syncFile('unlink', p, src, targets, ignore))
252
+ .on('error', e => console.error('Watcher error:', e));
253
+ }
254
+
255
+ /**
256
+ * Show infos of replikator
257
+ */
258
+ async function showInfo() {
259
+ console.log(`RPK / Replikator CLI tool / version ${await getVersion()}`)
260
+ console.log("");
261
+ console.log("Usage: rpk [command]");
262
+ console.log("");
263
+ console.log("Commands:");
264
+ console.log(" init Command used to init replikator configuration.");
265
+ console.log(" run Command used to run replikator.");
266
+ console.log(" update Command used to update replikator.");
267
+ console.log(" exclude Command used to exclude files for selected apps.");
268
+ process.exit(0);
269
+ }
270
+
212
271
  /**
213
272
  * Starts the initial copy and then sets up the watcher.
214
273
  */
215
274
  async function main() {
216
- let prompt = false;
217
275
  if (process.argv.length > 2) {
218
276
  switch (process.argv[2]) {
219
277
  case "init":
220
- prompt = true
278
+ await run(true);
221
279
  break;
222
280
  case "run":
223
- prompt = false
281
+ await run(false);
282
+ break;
283
+ case "update":
284
+ await updateRpk();
224
285
  break;
225
- case "clean":
226
- console.log('Cleaning...');
227
- console.log('\x1b[32mCleaning is complete.\x1b[0m');
228
- process.exit(0);
286
+ case "exclude":
287
+ await excludeRpk();
288
+ break;
289
+ default:
290
+ await showInfo();
291
+ break
229
292
  }
230
293
  } 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);
294
+ await showInfo();
239
295
  }
240
- const { src, targets, ignore } = await loadConfigOrPrompt(prompt);
241
296
 
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
297
 
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
298
  }
267
299
 
300
+ /**
301
+ * Update the CLI to the last available version.
302
+ */
303
+ async function updateRpk() {
304
+ const ua = process.env.npm_config_user_agent || '';
305
+ let cmd, args;
306
+
307
+ if (ua.startsWith('pnpm')) {
308
+ cmd = 'pnpm';
309
+ args = ['add', '-g', '@9of9solutions/replikator@latest'];
310
+ } else if (ua.startsWith('yarn')) {
311
+ cmd = 'yarn';
312
+ args = ['global', 'add', '@9of9solutions/replikator@latest'];
313
+ } else {
314
+ cmd = 'npm';
315
+ args = ['install', '-g', '@9of9solutions/replikator@latest'];
316
+ }
317
+
318
+ try {
319
+ await execa(cmd, args, { stdio: 'inherit' });
320
+ const newVersion = await getVersion();
321
+ console.log(green(`RPK CLI updated to version ${newVersion}`));
322
+ } catch (err) {
323
+ console.log(red(`Failed to update RPK CLI: ${err.message}`));
324
+ process.exit(1);
325
+ }
326
+ }
327
+
328
+ const green = txt => `\x1b[32m${txt}\x1b[0m`;
329
+ const red = txt => `\x1b[31m${txt}\x1b[0m`;
330
+
268
331
  /**
269
332
  * Syncs a file that was added/modified/deleted to all targets.
270
333
  */
271
- async function syncFile(event, filePath, srcDir, targets) {
334
+ async function syncFile(event, filePath, srcDir, targets, ignore) {
272
335
  const rel = path.relative(srcDir, filePath);
273
336
  await Promise.all(targets.map(async destRoot => {
274
337
  const destPath = path.join(destRoot, rel);
275
338
  if (event === 'unlink') {
276
339
  await fs.remove(destPath);
277
- console.log(`Deleted: ${rel}`);
278
340
  } 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)
341
+ const relDest = path.relative(projectRoot, destRoot);
342
+ const patterns = ignore?.[relDest] || [];
343
+ if (patterns.filter(p => (rel+"/").startsWith(p)).length === 0) {
344
+ await fs.ensureDir(path.dirname(destPath));
345
+ await fs.copy(filePath, destPath, { overwrite: true });
346
+ if ((await fs.lstat(filePath)).isFile()) {
347
+ const data = await fs.readFile(filePath);
348
+ const fd = await fs.open(destPath, 'w+');
349
+ const buffer = Buffer.from(await getReplicatedFileHeader(filePath));
350
+ await fs.write(fd, buffer, 0, buffer.length, 0);
351
+ await fs.write(fd, data, 0, data.length, buffer.length);
352
+ await fs.chmod(destPath, 0o444)
353
+ }
288
354
  }
289
- console.log(`${event === 'add' ? 'Added' : 'Updated'}: ${rel}`);
355
+
290
356
  }
291
357
  }));
292
358
  }
293
359
 
360
+ /**
361
+ * Setup excluded files or directories for apps
362
+ */
363
+ async function excludeRpk() {
364
+ const rawPkg = await fs.readJson(PACKAGE_JSON_ROOT_PATH, 'utf8');
365
+ const cfg = rawPkg.replikator;
366
+ if (!cfg || !cfg.src || !Array.isArray(cfg.targets)) {
367
+ console.log(red('No Replikator configuration found. Please run `rpk init` first.'));
368
+ process.exit(1);
369
+ }
370
+
371
+ const absSrc = path.resolve(projectRoot, cfg.src);
372
+ const absTargets = cfg.targets.map(rel => path.resolve(projectRoot, rel));
373
+
374
+ const apps = await findApplications(projectRoot);
375
+ const choicesApps = absTargets.map(absT => {
376
+ const match = apps.find(a => path.join(a.src, SHARED_PATH) === absT);
377
+ return {
378
+ name: match ? match.name : path.relative(projectRoot, absT),
379
+ value: absT
380
+ };
381
+ });
382
+
383
+ const { selectedApps } = await inquirer.prompt([{
384
+ type: 'checkbox',
385
+ name: 'selectedApps',
386
+ message: 'Select applications on which to apply exclusions:',
387
+ choices: choicesApps,
388
+ validate(ans) {
389
+ return ans.length > 0 ? true : 'You must choose at least one application.';
390
+ }
391
+ }]);
392
+
393
+ async function walk(dir, base = '') {
394
+ const entries = [];
395
+ for (const ent of await fs.readdir(dir, { withFileTypes: true })) {
396
+ const rel = path.join(base, ent.name);
397
+ const full = path.join(dir, ent.name);
398
+ entries.push(rel + (ent.isDirectory() ? '/' : ''));
399
+ if (ent.isDirectory()) {
400
+ entries.push(...await walk(full, rel));
401
+ }
402
+ }
403
+ return entries;
404
+ }
405
+ const allEntries = await walk(absSrc);
406
+
407
+ const { toExclude } = await inquirer.prompt([{
408
+ type: 'checkbox',
409
+ name: 'toExclude',
410
+ message: 'Select files/directories (relative to src) to exclude:',
411
+ choices: allEntries.map(rel => ({ name: rel, value: rel })),
412
+ validate(ans) {
413
+ return ans.length > 0 ? true : 'You must choose at least one entry to exclude.';
414
+ }
415
+ }]);
416
+
417
+ rawPkg.replikator.ignore = rawPkg.replikator.ignore || {};
418
+ for (const absT of selectedApps) {
419
+ const relT = path.relative(projectRoot, absT);
420
+ rawPkg.replikator.ignore[relT] = toExclude;
421
+ }
422
+ console.log(PACKAGE_JSON_ROOT_PATH)
423
+ console.log(rawPkg)
424
+ await fs.writeJson(PACKAGE_JSON_ROOT_PATH, rawPkg, { spaces: 2 });
425
+ console.log(green(`Exclusion config updated for ${selectedApps.length} app(s).`));
426
+ }
427
+
294
428
  main().catch(err => {
295
429
  console.error('Fatal error:', err);
296
430
  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.16",
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
  }