forked from finos/architecture-as-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
956 lines (871 loc) · 44.5 KB
/
Copy pathcli.ts
File metadata and controls
956 lines (871 loc) · 44.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
import { CALM_META_SCHEMA_DIRECTORY, DocifyMode, DiagramExportFormat, initLogger, runGenerate, SchemaDirectory, TemplateProcessingMode, CalmChoice, buildDocumentLoader, DocumentLoader, DocumentLoaderOptions } from '@finos/calm-shared';
import { Option, Command } from 'commander';
import { version } from '../package.json';
import { promptUserForOptions, loadChoicesFromInput } from './command-helpers/generate-options';
import * as cliConfig from './cli-config';
import path from 'path';
import { select } from '@inquirer/prompts';
import {
CreateNamespaceOptions,
ListNamespacesOptions,
PushOptions,
PullOptions,
runCreateNamespace,
runListArchitectures,
runListNamespaces,
runListPatterns,
runListStandards,
runPullArchitecture,
runPullPattern,
runPullStandard,
runPushArchitecture,
runPushPattern,
runPushStandard,
CreateDomainOptions,
ListDomainsOptions,
PushControlOptions,
PullControlOptions,
ListControlsOptions,
ListControlConfigurationsOptions,
runCreateDomain,
runListDomains,
runPushControlRequirement,
runPullControlRequirement,
runPushControlConfiguration,
runPullControlConfiguration,
runListControls,
runListControlConfigurations,
ListOptions,
BumpOptions,
runBumpArchitecture,
runBumpPattern,
runBumpStandard,
runBumpControlRequirement,
runBumpControlConfiguration,
} from './command-helpers/hub-commands';
import type { ResourceChangeType } from '@finos/calm-shared';
// Shared options used across multiple commands
const ARCHITECTURE_OPTION = '-a, --architecture <file>';
const OUTPUT_OPTION = '-o, --output <file>';
const SCHEMAS_OPTION = '-s, --schema-directory <path>';
const TIMELINE_OPTION = '--timeline <file>';
const VERBOSE_OPTION = '-v, --verbose';
// Generate command options
const PATTERN_OPTION = '-p, --pattern <file>';
const CALMHUB_URL_OPTION = '-c, --calm-hub-url <url>';
const OPTION_CHOICES_OPTION = '--option-choices <choices>';
// Validate command options
const FORMAT_OPTION = '-f, --format <format>';
const STRICT_OPTION = '--strict';
// Template and Docify command options
const BUNDLE_OPTION = '-b, --bundle <path>';
const TEMPLATE_OPTION = '-t, --template <path>';
const TEMPLATE_DIR_OPTION = '-d, --template-dir <path>';
const URL_MAPPING_OPTION = '-u, --url-to-local-file-mapping <path>';
const CLEAR_OUTPUT_DIRECTORY_OPTION = '--clear-output-directory';
// init-ai command options
const AI_DIRECTORY_OPTION = '-d, --directory <path>';
const AI_PROVIDER_OPTION = '-p, --provider <provider>';
const AI_PROVIDER_CHOICES = ['copilot', 'kiro', 'claude', 'codex'];
// Hub command options
const NAMESPACE_OPTION = '--namespace <namespace>';
const NAME_OPTION = '--name <name>';
const DESCRIPTION_OPTION = '--description <description>';
const HUB_VERSION_OPTION = '--ver <version>'; // --version conflicts with Commander's built-in version flag
const DOMAIN_OPTION = '--domain <domain>';
const CONTROL_NAME_OPTION = '--control-name <controlName>';
const CONFIG_NAME_OPTION = '--config-name <configName>';
const MAPPING_OPTION = '-m, --mapping <mapping>';
export function setupCLI(program: Command) {
program
.name('calm')
.version(version)
.description('A set of tools for interacting with the Common Architecture Language Model (CALM)');
program
.command('generate')
.description('Generate an architecture from a CALM pattern file.')
.requiredOption(PATTERN_OPTION, 'Path to the pattern file to use. May be a file path or a CalmHub URL.')
.requiredOption(OUTPUT_OPTION, 'Path location at which to output the generated file.', 'architecture.json')
.option(SCHEMAS_OPTION, 'Path to the directory containing the meta schemas to use.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option(URL_MAPPING_OPTION, 'Path to mapping file which maps URLs to local paths')
.option(OPTION_CHOICES_OPTION, 'Pre-defined option choices as a JSON object mapping option unique-ids to choice descriptions, or a path to a JSON file. Skips interactive prompts.')
.option(VERBOSE_OPTION, 'Enable verbose logging.', false)
.action(async (options) => {
const debug = !!options.verbose;
const { getUrlToLocalFileMap } = await import('./command-helpers/template');
const urlToLocalMap = getUrlToLocalFileMap(options.urlToLocalFileMapping);
const patternBasePath = options.pattern ? path.dirname(path.resolve(options.pattern)) : undefined;
const docLoaderOpts = await parseDocumentLoaderConfig(options, urlToLocalMap, patternBasePath);
const docLoader = buildDocumentLoader(docLoaderOpts);
const schemaDirectory = await buildSchemaDirectory(docLoader, debug);
const pattern: object = await docLoader.loadMissingDocument(options.pattern, 'pattern');
const choices: CalmChoice[] = options.optionChoices
? loadChoicesFromInput(options.optionChoices, pattern, debug)
: await promptUserForOptions(pattern, options.verbose);
await runGenerate(pattern, options.output, debug, schemaDirectory, choices);
});
program
.command('validate')
.description('Validate a CALM document.')
.addHelpText('after', `
Validation requires:
- an architecture: to validate against CALM schema
- an architecture and pattern: to validate the architecture against the CALM pattern
- a pattern: to validate the pattern against CALM schema
- a timeline: to validate the timeline against CALM timeline schema`)
.option(PATTERN_OPTION, 'Path to the pattern file to use. May be a file path or a URL.')
.option(ARCHITECTURE_OPTION, 'Path to the architecture file to use. May be a file path or a URL.')
.option(TIMELINE_OPTION, 'Path to the timeline file to validate. May be a file path or a URL.')
.option(SCHEMAS_OPTION, 'Path to the directory containing the meta schemas to use.', CALM_META_SCHEMA_DIRECTORY)
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option(URL_MAPPING_OPTION, 'Path to mapping file which maps URLs to local paths')
.option(STRICT_OPTION, 'When run in strict mode, the CLI will fail if any warnings are reported.', false)
.addOption(
new Option(FORMAT_OPTION, 'The format of the output')
.choices(['json', 'junit', 'pretty'])
.default('json')
)
.option(OUTPUT_OPTION, 'Path location at which to output the generated file.')
.option(VERBOSE_OPTION, 'Enable verbose logging.', false)
.action(async (options) => {
const { checkValidateOptions, runValidate } = await import('./command-helpers/validate');
checkValidateOptions(program, options, PATTERN_OPTION, ARCHITECTURE_OPTION, TIMELINE_OPTION);
await runValidate({
architecturePath: options.architecture,
patternPath: options.pattern,
timelinePath: options.timeline,
metaSchemaPath: options.schemaDirectory,
calmHubUrl: options.calmHubUrl,
urlToLocalFileMapping: options.urlToLocalFileMapping,
verbose: !!options.verbose,
strict: options.strict,
outputFormat: options.format,
outputPath: options.output
});
});
program
.command('template')
.description('Generate files from a CALM model using a template bundle, a single file, or a directory of templates')
.requiredOption(ARCHITECTURE_OPTION, 'Path to the CALM architecture JSON file')
.requiredOption(OUTPUT_OPTION, 'Path to output directory or file')
.option(CLEAR_OUTPUT_DIRECTORY_OPTION, 'Clear the output directory before processing', false)
.option(BUNDLE_OPTION, 'Path to the template bundle directory')
.option(TEMPLATE_OPTION, 'Path to a single .hbs or .md template file')
.option(TEMPLATE_DIR_OPTION, 'Path to a directory of .hbs/.md templates')
.option(URL_MAPPING_OPTION, 'Path to mapping file which maps URLs to local paths')
.option(VERBOSE_OPTION, 'Enable verbose logging.', false)
.action(async (options) => {
const { getUrlToLocalFileMap } = await import('./command-helpers/template');
const { TemplateProcessor } = await import('@finos/calm-shared');
if (options.verbose) {
process.env.DEBUG = 'true';
}
const localDirectory = getUrlToLocalFileMap(options.urlToLocalFileMapping);
let mode: TemplateProcessingMode;
let templatePath: string;
const flagsUsed = [options.template, options.templateDir, options.bundle].filter(Boolean);
if (flagsUsed.length !== 1) {
console.error('❌ Please specify exactly one of --template, --template-dir, or --bundle');
process.exit(1);
}
if (options.template) {
templatePath = options.template;
mode = 'template';
} else if (options.templateDir) {
templatePath = options.templateDir;
mode = 'template-directory';
} else {
templatePath = options.bundle;
mode = 'bundle';
}
const processor = new TemplateProcessor(
options.architecture,
templatePath,
options.output,
localDirectory,
mode,
false,
options.clearOutputDirectory
);
await processor.processTemplate();
});
program
.command('docify')
.description('Generate a documentation website from your CALM model using a template or template directory')
.requiredOption(ARCHITECTURE_OPTION, 'Path to the CALM architecture JSON file')
.requiredOption(OUTPUT_OPTION, 'Path to output directory')
.option(CLEAR_OUTPUT_DIRECTORY_OPTION, 'Clear the output directory before processing', false)
.option(TEMPLATE_OPTION, 'Path to a single .hbs or .md template file')
.option(TEMPLATE_DIR_OPTION, 'Path to a directory of .hbs/.md templates')
.option(URL_MAPPING_OPTION, 'Path to mapping file which maps URLs to local paths')
.option('--scaffold', 'Copy template files without processing (for customization/live docify)', false)
.addOption(new Option('--ants').default(false).hideHelp())
.addOption(new Option('--export-diagrams <format>',
'Render mermaid diagrams to image files using a local Chromium-based browser ' +
'(adds roughly 10-40s depending on diagram count)').choices(['svg', 'png']))
.option('--browser-path <path>',
'Path to a Chromium-based browser executable, only needed if automatic detection fails (run with --export-diagrams to see guidance)')
.option('--diagram-render-timeout <ms>',
'Per-diagram render timeout in milliseconds, only used with --export-diagrams (default: 30000). ' +
'Increase this for large/complex diagrams that time out during rendering.')
.option(VERBOSE_OPTION, 'Enable verbose logging.', false)
.action(async (options) => {
const { Docifier } = await import('@finos/calm-shared');
if (options.verbose) {
process.env.DEBUG = 'true';
}
const flagsUsed = [options.template, options.templateDir].filter(Boolean);
if (flagsUsed.length > 1) {
console.error('❌ Please specify only one of --template or --template-dir');
process.exit(1);
}
if (options.ants && flagsUsed.length > 0) {
console.error('❌ --ants cannot be combined with --template or --template-dir');
process.exit(1);
}
if (options.exportDiagrams && options.scaffold) {
console.error('❌ --export-diagrams cannot be combined with --scaffold (scaffold output is unrendered)');
process.exit(1);
}
if (options.browserPath && !options.exportDiagrams) {
console.error('❌ --browser-path requires --export-diagrams <svg|png>');
process.exit(1);
}
if (options.diagramRenderTimeout && !options.exportDiagrams) {
console.error('❌ --diagram-render-timeout requires --export-diagrams <svg|png>');
process.exit(1);
}
let diagramRenderTimeoutMs: number | undefined;
if (options.diagramRenderTimeout) {
diagramRenderTimeoutMs = Number(options.diagramRenderTimeout);
if (!Number.isFinite(diagramRenderTimeoutMs) || diagramRenderTimeoutMs <= 0) {
console.error('❌ --diagram-render-timeout must be a positive number of milliseconds');
process.exit(1);
}
}
let docifyMode: DocifyMode = 'WEBSITE';
let templateProcessingMode: TemplateProcessingMode = 'bundle';
let templatePath: string | undefined = undefined;
if (options.ants) {
docifyMode = 'ANTS';
} else if (options.template) {
docifyMode = 'USER_PROVIDED';
templateProcessingMode = 'template';
templatePath = options.template;
} else if (options.templateDir) {
docifyMode = 'USER_PROVIDED';
templateProcessingMode = 'template-directory';
templatePath = options.templateDir;
}
const docifier = new Docifier(
docifyMode,
options.architecture,
options.output,
options.urlToLocalFileMapping,
templateProcessingMode,
templatePath,
options.clearOutputDirectory,
options.scaffold,
options.exportDiagrams as DiagramExportFormat | undefined,
options.browserPath,
diagramRenderTimeoutMs
);
await docifier.docify();
});
const providerOption = new Option(AI_PROVIDER_OPTION, 'AI provider to initialize')
.choices(AI_PROVIDER_CHOICES);
program
.command('init-ai')
.description('Augment a git repository with AI assistance for CALM')
.addOption(providerOption)
.option(AI_DIRECTORY_OPTION, 'Target directory (defaults to current directory)', '.')
.option(VERBOSE_OPTION, 'Enable verbose logging.', false)
.action(async (options) => {
const { setupAiTools } = await import('./command-helpers/ai-tools');
const providers = AI_PROVIDER_CHOICES;
let selectedProvider: string = options.provider;
if (!selectedProvider) {
selectedProvider = await select({
message: 'Select an AI provider:',
choices: providers.map((p: string) => ({ name: p, value: p })),
});
}
console.log(`Selected AI provider: ${selectedProvider}`);
await setupAiTools(selectedProvider, options.directory, !!options.verbose);
});
program
.command('diff')
.description('Compare two CALM documents (architectures or patterns), or the moments of a CALM timeline, and report what changed.')
.addHelpText('after', `
Diff modes:
- two documents: diff -a <doc-a> -b <doc-b>
- a timeline: diff --timeline <file> (diffs every adjacent moment pair)
- timeline pair: diff --timeline <file> --from <id> --to <id> (diffs any two moments)
Timeline moment 'detailed-architecture' references are resolved relative to the timeline file's directory.`)
.option('-a, --document-a <file>', 'Path to the first (baseline) CALM document.')
.option('-b, --document-b <file>', 'Path to the second CALM document to compare against the baseline.')
.option(TIMELINE_OPTION, 'Path to a CALM timeline file. Diffs adjacent moments, or a specific pair with --from/--to.')
.option('--from <momentId>', 'With --timeline, the unique-id of the baseline moment (requires --to).')
.option('--to <momentId>', 'With --timeline, the unique-id of the moment to compare against (requires --from).')
// Deprecated aliases retained for backwards compatibility with cli-v1.41.0,
// which shipped the diff command with architecture-only long flags.
.addOption(new Option('--architecture-a <file>', 'Deprecated alias for --document-a.').hideHelp())
.addOption(new Option('--architecture-b <file>', 'Deprecated alias for --document-b.').hideHelp())
.addOption(
new Option('-f, --format <format>', 'Output format')
.choices(['json', 'summary'])
.default('json')
)
.addOption(
new Option('-t, --type <type>', 'Force the document type instead of auto-detecting it.')
.choices(['architecture', 'pattern'])
)
.option(OUTPUT_OPTION, 'Path location at which to write the diff output. If omitted, prints to stdout.')
.option('--exit-code', 'Exit with a non-zero status code when changes are detected. Useful in CI to gate version bumps.', false)
.option(VERBOSE_OPTION, 'Enable verbose logging.', false)
.action(async (options, command) => {
if (options.timeline) {
const documentAPath = options.documentA ?? options.architectureA;
const documentBPath = options.documentB ?? options.architectureB;
if (documentAPath || documentBPath) {
command.error('error: --timeline cannot be combined with -a/--document-a or -b/--document-b');
}
if ((options.from && !options.to) || (!options.from && options.to)) {
command.error('error: --from and --to must be supplied together');
}
const { runTimelineDiffCommand } = await import('./command-helpers/diff');
const hasChanges = await runTimelineDiffCommand({
timelinePath: options.timeline,
fromMomentId: options.from,
toMomentId: options.to,
outputFormat: options.format,
outputPath: options.output,
verbose: !!options.verbose,
});
if (options.exitCode && hasChanges) {
process.exit(1);
}
return;
}
if (options.from || options.to) {
command.error('error: --from/--to are only valid together with --timeline');
}
const documentAPath = options.documentA ?? options.architectureA;
const documentBPath = options.documentB ?? options.architectureB;
if (!documentAPath || !documentBPath) {
command.error('error: both -a/--document-a <file> and -b/--document-b <file> are required');
}
if (options.architectureA || options.architectureB) {
process.stderr.write('warning: --architecture-a/--architecture-b are deprecated; use --document-a/--document-b.\n');
}
const { runDiffCommand } = await import('./command-helpers/diff');
const hasChanges = await runDiffCommand({
documentAPath,
documentBPath,
outputFormat: options.format,
outputPath: options.output,
documentType: options.type,
verbose: !!options.verbose,
});
if (options.exitCode && hasChanges) {
process.exit(1);
}
});
program
.command('timeline')
.description('Synthesise an implied CALM timeline from a set of local versioned architecture files.')
.addHelpText('after', `
One moment is generated per input architecture, in the order the files are given
(plain files have no semver versions to sort by). Each moment's name/description
is taken from the architecture's own name/description when present, else derived
from the filename. The 'detailed-architecture' reference is written relative to
the --output file's directory so the timeline is portable and reloadable by
'calm validate --timeline' / 'calm diff --timeline'.
Example:
calm timeline -a v1.json -a v2.json -a v3.json -o calm-timeline.json`)
.requiredOption('-a, --architecture <files...>', 'Paths to architecture files, in moment order. Repeat the flag or pass several paths after one flag.')
.option(OUTPUT_OPTION, 'Path location at which to write the generated timeline. If omitted, prints to stdout.')
.option(VERBOSE_OPTION, 'Enable verbose logging.', false)
.action(async (options) => {
const { runTimelineGenerate } = await import('./command-helpers/timeline');
runTimelineGenerate({
architecturePaths: options.architecture,
outputPath: options.output,
verbose: !!options.verbose,
});
});
program
.command('init-config')
.description('Create or update the CALM CLI configuration file (~/.calm.json).')
.option('--allowed-remote-hosts <hosts>', 'Comma-separated list of trusted remote hosts to allow for direct URL loading')
.option('--calm-hub-url <url>', 'URL to a trusted file location (e.g. CALMHub) to allow for direct URL loading of CALM documents')
.action(async (options) => {
const existingConfig = await cliConfig.loadCliConfig() ?? {};
if (options.allowedRemoteHosts) {
const newHosts = (options.allowedRemoteHosts as string).split(',').map((h: string) => h.trim()).filter(Boolean);
const existingHosts = existingConfig.allowedRemoteHosts ?? [];
const merged = [...new Set([...existingHosts, ...newHosts])];
existingConfig.allowedRemoteHosts = merged;
}
if (options.calmHubUrl) {
existingConfig.calmHubUrl = options.calmHubUrl;
}
const configPath = cliConfig.getUserConfigLocation();
await cliConfig.saveCliConfig(existingConfig);
console.log(`✅ Configuration saved to ${configPath}`);
console.log(JSON.stringify(existingConfig, null, 2));
});
// ── hub ───────────────────────────────────────────────────────────────────
const hubOutputOption = new Option(FORMAT_OPTION, 'Output format').choices(['json', 'pretty']).default('json');
const hubVersionBumpOption = new Option('-t, --change-type <type>', 'Type of change for version bump when pushing a new version of an existing resource. Defaults to \'patch\'')
.choices(['patch', 'minor', 'major'])
.default('patch');
const hubCmd = new Command('hub').description('Interact with CALM Hub');
// hub push
const hubPushCmd = hubCmd.command('push').description('Push a CALM document to CALM Hub');
hubPushCmd
.command('architecture <architecture-file>')
.description('Push a CALM architecture file to CALM Hub. $id of document must contain a full document ID including namespace, type, mapping slug and version.')
.option(NAME_OPTION, 'Name for the architecture in CALM Hub; overrides `title` field if set.')
.option(DESCRIPTION_OPTION, 'Description for the architecture; overrides `description` field if set.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option('--fail-if-exists', 'Push the exact version from $id without auto-bumping; fail if that version already exists on the hub.')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (architectureFile, options) => {
const pushOptions: PushOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
name: options.name,
description: options.description,
file: architectureFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
failIfExists: options.failIfExists ?? false,
};
await runPushArchitecture(pushOptions);
});
hubPushCmd
.command('pattern <pattern-file>')
.description('Push a CALM pattern file to CALM Hub. $id of document must contain a full document ID including namespace, type, mapping slug and version.')
.option(NAME_OPTION, 'Name for the pattern in CALM Hub; overrides `title` field if set.')
.option(DESCRIPTION_OPTION, 'Description for the pattern')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option('--fail-if-exists', 'Push the exact version from $id without auto-bumping; fail if that version already exists on the hub.')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (patternFile, options) => {
const pushPatternOptions: PushOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
name: options.name,
description: options.description,
file: patternFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
failIfExists: options.failIfExists ?? false,
};
await runPushPattern(pushPatternOptions);
});
hubPushCmd
.command('standard <standard-file>')
.description('Push a CALM standard file to CALM Hub. $id of document must contain a full document ID including namespace, type, mapping slug and version.')
.option(NAME_OPTION, 'Name for the standard in CALM Hub')
.option(DESCRIPTION_OPTION, 'Description for the standard')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option('--fail-if-exists', 'Push the exact version from $id without auto-bumping; fail if that version already exists on the hub.')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (standardFile, options) => {
const pushStandardOptions: PushOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
name: options.name,
description: options.description,
file: standardFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
failIfExists: options.failIfExists ?? false,
};
await runPushStandard(pushStandardOptions);
});
hubPushCmd
.command('control-requirement <requirement-file>')
.description('Push a control requirement version to CALM Hub. $id of document must contain a full control requirement document ID including domain, control name and version.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option('--fail-if-exists', 'Push the exact version from $id without auto-bumping; fail if that version already exists on the hub.')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (requirementFile, options) => {
const pushOptions: PushControlOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
file: requirementFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
failIfExists: options.failIfExists ?? false,
};
await runPushControlRequirement(pushOptions);
});
hubPushCmd
.command('control-configuration <config-file>')
.description('Push a control configuration version to CALM Hub. $id of document must contain a full control configuration document ID including domain, control name, configuration name and version.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option('--fail-if-exists', 'Push the exact version from $id without auto-bumping; fail if that version already exists on the hub.')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (configFile, options) => {
const pushOptions: PushControlOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
file: configFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
failIfExists: options.failIfExists ?? false,
};
await runPushControlConfiguration(pushOptions);
});
// hub bump
const hubBumpCmd = hubCmd.command('bump').description('Bump the version of a CALM document on disk if the current version already exists on the hub. Intended for dev-time use before committing, so CI can push with --fail-if-exists.');
hubBumpCmd
.command('architecture <architecture-file>')
.description('Bump the version of a CALM architecture on disk if that version already exists on the hub.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (architectureFile, options) => {
const bumpOptions: BumpOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
file: architectureFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
};
await runBumpArchitecture(bumpOptions);
});
hubBumpCmd
.command('pattern <pattern-file>')
.description('Bump the version of a CALM pattern on disk if that version already exists on the hub.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (patternFile, options) => {
const bumpOptions: BumpOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
file: patternFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
};
await runBumpPattern(bumpOptions);
});
hubBumpCmd
.command('standard <standard-file>')
.description('Bump the version of a CALM standard on disk if that version already exists on the hub.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (standardFile, options) => {
const bumpOptions: BumpOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
file: standardFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
};
await runBumpStandard(bumpOptions);
});
hubBumpCmd
.command('control-requirement <requirement-file>')
.description('Bump the version of a control requirement on disk if that version already exists on the hub.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (requirementFile, options) => {
const bumpOptions: BumpOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
file: requirementFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
};
await runBumpControlRequirement(bumpOptions);
});
hubBumpCmd
.command('control-configuration <config-file>')
.description('Bump the version of a control configuration on disk if that version already exists on the hub.')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.addOption(hubVersionBumpOption)
.action(async (configFile, options) => {
const bumpOptions: BumpOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
file: configFile,
format: options.format,
changeType: options.changeType.toUpperCase() as ResourceChangeType,
};
await runBumpControlConfiguration(bumpOptions);
});
// hub pull
const hubPullCmd = hubCmd.command('pull').description('Pull a CALM document from CALM Hub');
hubPullCmd
.command('architecture')
.description('Pull a specific version of a CALM architecture from CALM Hub')
.requiredOption(NAMESPACE_OPTION, 'Source namespace')
.requiredOption(MAPPING_OPTION, 'Mapping slug of the architecture to pull')
.option(HUB_VERSION_OPTION, 'Version to retrieve')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option(OUTPUT_OPTION, 'Write output to this file instead of stdout')
.action(async (options) => {
const pullOptions: PullOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
namespace: options.namespace,
mapping: options.mapping,
version: options.ver,
output: options.output
};
await runPullArchitecture(pullOptions);
});
hubPullCmd
.command('pattern')
.description('Pull a specific version of a CALM pattern from CALM Hub')
.requiredOption(NAMESPACE_OPTION, 'Source namespace')
.requiredOption(MAPPING_OPTION, 'Mapping slug of the pattern to pull')
.option(HUB_VERSION_OPTION, 'Version to retrieve')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option(OUTPUT_OPTION, 'Write output to this file instead of stdout')
.action(async (options) => {
const pullPatternOptions: PullOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
namespace: options.namespace,
mapping: options.mapping,
version: options.ver,
output: options.output
};
await runPullPattern(pullPatternOptions);
});
hubPullCmd
.command('standard')
.description('Pull a specific version of a CALM standard from CALM Hub')
.requiredOption(NAMESPACE_OPTION, 'Source namespace')
.requiredOption(MAPPING_OPTION, 'Mapping slug of the standard to pull')
.option(HUB_VERSION_OPTION, 'Version to retrieve')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option(OUTPUT_OPTION, 'Write output to this file instead of stdout')
.action(async (options) => {
const pullStandardOptions: PullOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
namespace: options.namespace,
mapping: options.mapping,
version: options.ver,
output: options.output
};
await runPullStandard(pullStandardOptions);
});
hubPullCmd
.command('control-requirement')
.description('Pull a control requirement version from CALM Hub')
.requiredOption(DOMAIN_OPTION, 'Source domain')
.requiredOption(CONTROL_NAME_OPTION, 'Control name')
.option(HUB_VERSION_OPTION, 'Version to retrieve (defaults to the latest)')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option(OUTPUT_OPTION, 'Write output to this file instead of stdout')
.action(async (options) => {
const pullOptions: PullControlOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
domain: options.domain,
controlName: options.controlName,
version: options.ver,
output: options.output
};
await runPullControlRequirement(pullOptions);
});
hubPullCmd
.command('control-configuration')
.description('Pull a control configuration version from CALM Hub')
.requiredOption(DOMAIN_OPTION, 'Source domain')
.requiredOption(CONTROL_NAME_OPTION, 'Control name')
.requiredOption(CONFIG_NAME_OPTION, 'Configuration name')
.option(HUB_VERSION_OPTION, 'Version to retrieve (defaults to the latest)')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.option(OUTPUT_OPTION, 'Write output to this file instead of stdout')
.action(async (options) => {
const pullOptions: PullControlOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
domain: options.domain,
controlName: options.controlName,
configName: options.configName,
version: options.ver,
output: options.output
};
await runPullControlConfiguration(pullOptions);
});
// hub list
const hubListCmd = hubCmd.command('list').description('List CALM Hub resources');
hubListCmd
.command('architectures')
.description('List architectures in a namespace')
.option(NAMESPACE_OPTION, 'Target namespace', 'default')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const listOptions: ListOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
namespace: options.namespace,
format: options.format
};
await runListArchitectures(listOptions);
});
hubListCmd
.command('namespaces')
.description('List all namespaces')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const listOptions: ListNamespacesOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
format: options.format
};
await runListNamespaces(listOptions);
});
hubListCmd
.command('patterns')
.description('List patterns in a namespace')
.option(NAMESPACE_OPTION, 'Target namespace', 'default')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const listPatternsOptions: ListOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
namespace: options.namespace,
format: options.format
};
await runListPatterns(listPatternsOptions);
});
hubListCmd
.command('standards')
.description('List standards in a namespace')
.option(NAMESPACE_OPTION, 'Target namespace', 'default')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const listStandardsOptions: ListOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
namespace: options.namespace,
format: options.format
};
await runListStandards(listStandardsOptions);
});
hubListCmd
.command('domains')
.description('List all domains')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const listOptions: ListDomainsOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
format: options.format
};
await runListDomains(listOptions);
});
hubListCmd
.command('controls')
.description('List control names in a domain')
.requiredOption(DOMAIN_OPTION, 'Target domain')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const listOptions: ListControlsOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
domain: options.domain,
format: options.format
};
await runListControls(listOptions);
});
hubListCmd
.command('control-configurations')
.description('List configuration names for a control')
.requiredOption(DOMAIN_OPTION, 'Target domain')
.requiredOption(CONTROL_NAME_OPTION, 'Control name')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const listOptions: ListControlConfigurationsOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
domain: options.domain,
controlName: options.controlName,
format: options.format
};
await runListControlConfigurations(listOptions);
});
// hub create
const hubCreateCmd = hubCmd.command('create').description('Create CALM Hub resources');
hubCreateCmd
.command('namespace')
.description('Create a new namespace in CALM Hub')
.requiredOption(NAME_OPTION, 'Namespace name')
.requiredOption(DESCRIPTION_OPTION, 'Namespace description')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const createOptions: CreateNamespaceOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
name: options.name,
description: options.description,
format: options.format
};
await runCreateNamespace(createOptions);
});
hubCreateCmd
.command('domain')
.description('Create a new domain in CALM Hub')
.requiredOption(NAME_OPTION, 'Domain name')
.option(CALMHUB_URL_OPTION, 'URL to CALMHub instance')
.addOption(hubOutputOption)
.action(async (options) => {
const createOptions: CreateDomainOptions = {
calmHubOptions: { calmHubUrl: options.calmHubUrl },
name: options.name,
format: options.format
};
await runCreateDomain(createOptions);
});
program.addCommand(hubCmd);
}
interface ParseDocumentLoaderOptions {
verbose?: boolean;
calmHubUrl?: string;
schemaDirectory?: string;
allowedRemoteHosts?: string[];
}
export async function parseDocumentLoaderConfig(
options: ParseDocumentLoaderOptions,
urlToLocalMap?: Map<string, string>,
basePath?: string
): Promise<DocumentLoaderOptions> {
const logger = initLogger(options.verbose ?? false, 'calm-cli');
const docLoaderOpts: DocumentLoaderOptions = {
calmHubUrl: options.calmHubUrl,
schemaDirectoryPath: options.schemaDirectory,
urlToLocalMap: urlToLocalMap,
basePath: basePath,
allowedRemoteHosts: options.allowedRemoteHosts,
debug: !!options.verbose
};
const userConfig = await cliConfig.loadCliConfig();
if (userConfig && userConfig.calmHubUrl && !options.calmHubUrl) {
logger.info('Using CALMHub URL from config file: ' + userConfig.calmHubUrl);
docLoaderOpts.calmHubUrl = userConfig.calmHubUrl;
}
// if we have an auth plugin and we have calmHub configured
if (userConfig && userConfig.authPluginPath) {
logger.info('Loading auth plugin from config file: ' + userConfig.authPluginPath);
try {
const authPlugin = await cliConfig.loadAuthPlugin(userConfig.authPluginPath, !!options.verbose);
docLoaderOpts.authPlugin = authPlugin;
logger.debug('Auth plugin loaded successfully');
} catch (err) {
logger.error('Failed to load auth plugin: ' + (err instanceof Error ? err.message : String(err)));
}
}
if (userConfig && userConfig.allowedRemoteHosts && !options.allowedRemoteHosts) {
logger.info('Using allowed remote hosts from config file');
docLoaderOpts.allowedRemoteHosts = userConfig.allowedRemoteHosts;
}
return docLoaderOpts;
}
export async function buildSchemaDirectory(docLoader: DocumentLoader, debug: boolean): Promise<SchemaDirectory> {
return new SchemaDirectory(docLoader, debug);
}