1xops 0.2.5 → 0.2.6

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/package.json +1 -1
  2. package/src/commands.mjs +90 -21
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "1xops",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "1xops by OceanSoft.io: set up the 1xops plugin, settings and read-only cloud connectors for an organisation, team or person. Native Node.js, no dependencies.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Nhat-Thanh Nguyen <nnthanh101@gmail.com> (https://www.oceansoft.io)",
package/src/commands.mjs CHANGED
@@ -43,10 +43,41 @@ export function accessFromRole(arn = '') {
43
43
  const ACCESS = { read: 'read-only', write: 'can change things: use a read-only role', unknown: 'access unknown: use a read-only role' };
44
44
 
45
45
  // The same look as the Python CLI's rich table: a heavy header, light rows, colour on a terminal. No dependency.
46
+ // On a terminal the table fits the window: the widest columns shrink and their cells wrap, as rich does.
47
+ // Piped (the assistant, evidence) it sizes to its content, so both CLIs print the same bytes.
46
48
  const visible = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, '').length;
49
+ function wrap(text, w) {
50
+ if (visible(text) <= w) return [String(text)];
51
+ // A coloured cell wraps on its plain text; each line then gets the colour again, so no code is cut or bleeds.
52
+ const styled = String(text).match(/^(\x1b\[[0-9;]*m)(.*?)(\x1b\[[0-9;]*m)$/s);
53
+ if (styled) return wrap(styled[2], w).map((l) => styled[1] + l + styled[3]);
54
+ const lines = [];
55
+ let line = '';
56
+ for (const word of String(text).split(' ')) {
57
+ for (let piece = word; piece.length; ) {
58
+ const room = line ? w - line.length - 1 : w;
59
+ if (piece.length <= room) { line = line ? `${line} ${piece}` : piece; piece = ''; }
60
+ else if (line) { lines.push(line); line = ''; }
61
+ else { lines.push(piece.slice(0, w)); piece = piece.slice(w); }
62
+ }
63
+ }
64
+ if (line) lines.push(line);
65
+ return lines;
66
+ }
47
67
  function table(title, columns, rows) {
48
68
  const width = columns.map((c, i) => Math.max(c.length, ...rows.map((r) => visible(r[i]))));
49
- const cells = (r, bar) => `${bar} ${r.map((c, i) => String(c) + ' '.repeat(width[i] - visible(c))).join(` ${bar} `)} ${bar}`;
69
+ const limit = process.stdout.isTTY ? (process.stdout.columns || 80) - (3 * width.length + 1) : Infinity;
70
+ while (width.reduce((a, w) => a + w, 0) > limit) {
71
+ const i = width.indexOf(Math.max(...width));
72
+ if (width[i] <= 8) break;
73
+ width[i] -= 1;
74
+ }
75
+ const pad = (c, i) => String(c) + ' '.repeat(Math.max(0, width[i] - visible(c)));
76
+ const cells = (r, bar) => {
77
+ const parts = r.map((c, i) => wrap(c, width[i]));
78
+ const height = Math.max(...parts.map((p) => p.length));
79
+ return Array.from({ length: height }, (_, k) => `${bar} ${parts.map((p, i) => pad(p[k] ?? '', i)).join(` ${bar} `)} ${bar}`).join('\n');
80
+ };
50
81
  const rule = (l, m, r, h) => l + width.map((w) => h.repeat(w + 2)).join(m) + r;
51
82
  const total = width.reduce((a, w) => a + w + 3, 1);
52
83
  const left = Math.max(0, Math.floor((total - title.length) / 2));
@@ -172,8 +203,16 @@ export function doctor(opts, version) {
172
203
  if (tty) process.stdout.write('\r\x1b[K');
173
204
  const shown = rows.map(([name, required, ok, detail]) => [name, required ? 'required' : 'optional', ok ? 'ok' : required ? 'missing' : 'check', scrub(detail)]);
174
205
  shown.push(...connectors.map(([name, status, fix]) => [name, 'connector', status, scrub(fix)]));
206
+ // Required tools and configured connectors that are not ok or ready. Optional tools stay in the table only.
207
+ const todo = shown.filter((r) => r[2] !== 'ok' && r[2] !== 'ready' && r[1] !== 'optional');
175
208
  for (const r of shown) r[2] = color(RESULT_STYLE[r[2]], r[2]);
176
209
  table(`1xops ${version} doctor`, ['check', 'needed', 'result', 'detail'], shown);
210
+ // What to do next, in table order (see todo above).
211
+ if (!todo.length) console.log(color('green', 'All set: nothing to fix.'));
212
+ else {
213
+ console.log(color('bold', 'Next:'));
214
+ todo.forEach((r, i) => console.log(` ${i + 1}. ${r[0]}: ${r[3]}`));
215
+ }
177
216
  const failed = rows.filter((r) => r[1] && !r[2]).map((r) => r[0]);
178
217
  if (failed.length) {
179
218
  console.log(color('red', `Required: ${failed.join(', ')}`));
@@ -220,21 +259,21 @@ function diffLines(a, b) {
220
259
  let i = 0, j = 0;
221
260
  while (i < n || j < m) {
222
261
  if (i < n && j < m && a[i] === b[j]) { out.push(` ${a[i]}`); i++; j++; }
223
- else if (j < m && (i === n || lcs[i][j + 1] >= lcs[i + 1][j])) out.push(`+${b[j++]}`);
224
- else out.push(`-${a[i++]}`);
262
+ else if (i < n && (j === m || lcs[i + 1][j] >= lcs[i][j + 1])) out.push(`-${a[i++]}`); // removed first, as difflib
263
+ else out.push(`+${b[j++]}`);
225
264
  }
226
265
  return out;
227
266
  }
228
267
 
229
- function showChange(file, before, after) {
268
+ function showChange(file, before, after, linesToo = true) {
230
269
  if (s.dumps(before) === s.dumps(after)) {
231
270
  console.log(color('dim', `${file}: already up to date`));
232
271
  return false;
233
272
  }
234
- console.log(`--- ${file}\n+++ ${file}`);
235
- for (const l of diffLines(s.dumps(before).trimEnd().split('\n'), s.dumps(after).trimEnd().split('\n'))) {
236
- if (l[0] !== ' ') console.log(l);
237
- }
273
+ const lines = diffLines(s.dumps(before).trimEnd().split('\n'), s.dumps(after).trimEnd().split('\n')).filter((l) => l[0] !== ' ');
274
+ const added = lines.filter((l) => l[0] === '+').length;
275
+ console.log(color('bold', `${file}: ${added} lines added, ${lines.length - added} removed`));
276
+ if (linesToo) for (const l of lines) console.log(color(l[0] === '+' ? 'green' : 'red', l));
238
277
  return true;
239
278
  }
240
279
 
@@ -280,7 +319,7 @@ export function config(opts) {
280
319
  const target = s.settingsPath(scope, project, out);
281
320
  const before = s.readJson(target);
282
321
  const after = s.merge(before, wanted);
283
- if (showChange(target, before, after)) planned.push([target, after]);
322
+ if (showChange(target, before, after, opts.preview !== 'summary')) planned.push([target, after]);
284
323
 
285
324
  const hostCmds = [];
286
325
  if (Object.keys(servers).length) {
@@ -288,7 +327,7 @@ export function config(opts) {
288
327
  if (mcpFile) {
289
328
  const b = s.readJson(mcpFile);
290
329
  const a = s.merge(b, { mcpServers: servers });
291
- if (showChange(mcpFile, b, a)) planned.push([mcpFile, a]);
330
+ if (showChange(mcpFile, b, a, opts.preview !== 'summary')) planned.push([mcpFile, a]);
292
331
  } else {
293
332
  const hostScope = scope === 'personal' ? 'user' : 'local';
294
333
  for (const [name, spec] of Object.entries(servers)) {
@@ -299,7 +338,7 @@ export function config(opts) {
299
338
  }
300
339
 
301
340
  if (!opts.yes) {
302
- console.log('Dry run. Re-run with --yes to write these changes.');
341
+ if (!opts.preview) console.log('Dry run. Re-run with --yes to write these changes.');
303
342
  return 0;
304
343
  }
305
344
  if (hostCmds.length && !which(s.HOST)) {
@@ -396,6 +435,13 @@ export function readOnlyProfiles() {
396
435
  return found.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
397
436
  }
398
437
 
438
+ const SCOPE_HELP = {
439
+ org: 'managed files for IT, every person in the organisation',
440
+ team: 'a shared project or tenant folder',
441
+ local: 'you, in this project only',
442
+ personal: 'you, in every project',
443
+ };
444
+
399
445
  export async function setup(opts) {
400
446
  const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
401
447
  const lines = rl[Symbol.asyncIterator]();
@@ -412,30 +458,52 @@ export async function setup(opts) {
412
458
  try {
413
459
  const file = opts.file;
414
460
  console.log(`${color('bold', '1xops setup')} — non-secret values only; secrets stay in your sign-in.\n`);
461
+ table('Who the settings are for', ['scope', 'for'], s.SCOPES.map((n) => [n, SCOPE_HELP[n]]));
415
462
  let scope;
416
- do scope = await ask(`Scope (${s.SCOPES.join(' | ')})`, 'team'); while (!s.SCOPES.includes(scope));
463
+ do scope = await ask(`Scope (${s.SCOPES.join('/')})`, 'team'); while (!s.SCOPES.includes(scope));
417
464
  const conf = { scope };
418
465
  if (scope === 'team' || scope === 'local') conf.dir = await ask('Project or tenant folder', '.');
419
466
  if (scope === 'org') conf.out = await ask('Folder to write the managed files to', '.');
420
467
  const found = detect();
421
468
  const connectors = {};
469
+ let listed = false;
422
470
  for (const name of s.builtinProfiles()) {
423
471
  const profile = s.loadProfile(name);
424
472
  if (!(await yes(`Add ${name}: ${profile.description ?? ''}?`, false))) continue;
425
473
  const values = {};
426
474
  for (const v of cf.variables(profile)) {
427
475
  if (v.endsWith('_PROFILE')) {
428
- // Pick a read-only AWS profile by number. No typing: a mistyped or admin profile cannot get in.
476
+ // Pick a read-only AWS profile: by number, or type part of a name to filter. A name outside the read-only
477
+ // list cannot get in. The list is shown once; later questions refer to it.
429
478
  const options = readOnlyProfiles();
430
479
  if (!options.length) {
431
- console.log(` ${v}: no read-only AWS profile found in ~/.aws/config. Create one (an SSO role such as ReadOnlyAccess) with: aws configure sso. This connector will show as missing in /1xops:check until then.`);
480
+ if (!listed) { // say it once, not once per variable
481
+ console.log(' No read-only AWS profile in ~/.aws/config yet.');
482
+ console.log(' Create one with: aws configure sso (a role such as ReadOnlyAccess).');
483
+ console.log(' Until then /1xops:check shows this connector as missing.');
484
+ listed = true;
485
+ }
432
486
  continue;
433
487
  }
434
- console.log(` ${v}: read-only profiles only`);
435
- options.forEach(([n, acct, role], i) => console.log(` ${i + 1}) ${n} ${acct} ${role}`));
436
- let pick;
437
- do pick = await ask(' Number (Enter to skip)'); while (pick && !(Number(pick) >= 1 && Number(pick) <= options.length));
438
- if (pick) values[v] = options[Number(pick) - 1][0];
488
+ const numbered = options.map((o, i) => [i + 1, o]);
489
+ const show = (rows, title) => table(title, ['#', 'profile', 'account', 'role'], rows.map(([n, [name, acct, role]]) => [String(n).padStart(String(options.length).length), name, acct, role]));
490
+ if (!listed) { show(numbered, `Read-only AWS profiles (${options.length})`); listed = true; }
491
+ const current = numbered.find(([, [name]]) => name === process.env[v]);
492
+ const hint = current ? `Enter keeps ${current[0]}, - skips` : 'Enter skips';
493
+ for (;;) {
494
+ const pick = (await ask(` ${v}: number or part of a name (${hint})`, current ? String(current[0]) : '')).trim();
495
+ if (!pick || pick === '-') break;
496
+ if (/^\d+$/.test(pick)) {
497
+ if (Number(pick) >= 1 && Number(pick) <= options.length) { values[v] = options[Number(pick) - 1][0]; break; }
498
+ console.log(` No profile number ${pick}: pick 1 to ${options.length}.`);
499
+ continue;
500
+ }
501
+ const q = pick.toLowerCase();
502
+ const matches = numbered.filter(([, [name, , role]]) => name.toLowerCase().includes(q) || role.toLowerCase().includes(q));
503
+ if (matches.length === 1) { values[v] = matches[0][1][0]; break; }
504
+ if (matches.length) show(matches, `Matching '${pick}' (${matches.length})`);
505
+ else console.log(` No read-only profile matches '${pick}'.`);
506
+ }
439
507
  continue;
440
508
  }
441
509
  const value = await ask(` ${v} (blank to skip)`, process.env[v] || found[v] || '');
@@ -448,14 +516,15 @@ export async function setup(opts) {
448
516
  conf.connectors = connectors;
449
517
 
450
518
  const text = cf.dump(conf);
451
- console.log(`\n${file}\n${text}`);
519
+ console.log(`\n${color('bold', file)}\n${text}`);
452
520
  if (existsSync(file) && !(await yes(`${file} exists. Replace it?`, false))) return 1;
453
521
  if (!(await yes(`Write ${file}?`, true))) return 1;
454
522
  write(file, text);
455
523
  cf.load(file); // same checks as `1xops config --file`
456
524
 
457
525
  console.log('\nChanges this would make:');
458
- if (config({ file }) !== 0) return 2;
526
+ if (config({ file, preview: 'summary' }) !== 0) return 2;
527
+ if (await yes('Show every line first?', false)) config({ file, preview: 'full' });
459
528
  if (await yes('Apply them now?', false)) return config({ file, yes: true });
460
529
  console.log(`Apply later with: 1xops config --file ${file} --yes`);
461
530
  return 0;