-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
2092 lines (1853 loc) · 74.5 KB
/
extension.js
File metadata and controls
2092 lines (1853 loc) · 74.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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const vscode = require("vscode");
const { CloudsmithProvider } = require("./views/cloudsmithProvider");
const { helpProvider } = require("./views/helpProvider");
const { SearchProvider } = require("./views/searchProvider");
const { CloudsmithAPI } = require("./util/cloudsmithAPI");
const { CredentialManager } = require("./util/credentialManager");
const { RecentSearches } = require("./util/recentSearches");
const { RemediationHelper } = require("./util/remediationHelper");
const { DependencyHealthProvider } = require("./views/dependencyHealthProvider");
const { InstallCommandBuilder } = require("./util/installCommandBuilder");
const { VulnerabilityProvider } = require("./views/vulnerabilityProvider");
const { QuarantineExplainProvider } = require("./views/quarantineExplainProvider");
const { DiagnosticsPublisher } = require("./util/diagnosticsPublisher");
const { SSOAuthManager } = require("./util/ssoAuthManager");
const { UpstreamChecker } = require("./util/upstreamChecker");
const { UpstreamPreviewProvider } = require("./views/upstreamPreviewProvider");
const { UpstreamDetailProvider } = require("./views/upstreamDetailProvider");
const { PromotionProvider } = require("./views/promotionProvider");
const { SearchQueryBuilder } = require("./util/searchQueryBuilder");
const { formatApiError } = require("./util/errorFormatter");
const { LicenseClassifier } = require("./util/licenseClassifier");
const { fetchRepositoryUpstreams, generateTerraformConfig } = require("./util/terraformExporter");
const { SUPPORTED_UPSTREAM_FORMATS } = require("./util/upstreamFormats");
const recentPackages = require("./util/recentPackages");
let exportTerraformAbortController = null;
/**
* Helper: unwrap a property that may be stored as:
* - a raw string: "value"
* - a single-wrapped object: { id: "Name", value: "value" }
* - a double-wrapped object (from the getChildren double-wrap bug):
* { id: "Name", value: { id: "Name", value: "value" } }
* Returns the raw string value in all cases.
*/
function unwrapValue(prop) {
if (prop == null) {
return null;
}
if (typeof prop === "string") {
return prop;
}
if (typeof prop === "object" && prop.value != null) {
// Could be double-wrapped: { value: { value: "str" } }
if (typeof prop.value === "object" && prop.value.value != null) {
return String(prop.value.value);
}
return String(prop.value);
}
return String(prop);
}
/**
* Helper: extract package properties from different node types.
* Handles PackageNode (double-wrapped from tree), SearchResultNode (single-wrapped),
* and DependencyHealthNode (mixed). Uses unwrapValue for safe extraction.
*/
function extractPackageInfo(item) {
return {
name: item.name,
format: item.format,
version: unwrapValue(item.version) || (item.declaredVersion || null),
workspace: item.namespace || null,
repo: item.repository || null,
slugPerm: unwrapValue(item.slug_perm),
slug: unwrapValue(item.slug),
};
}
function getNestedInstallField(item, fieldName) {
if (!item || typeof item !== "object") {
return null;
}
if (item[fieldName] != null) {
return item[fieldName];
}
if (item.cloudsmithMatch && item.cloudsmithMatch[fieldName] != null) {
return item.cloudsmithMatch[fieldName];
}
return null;
}
function isQuarantinedPackage(item) {
const status = unwrapValue(item && item.status_str) ||
(item && item.status_str_raw) ||
getNestedInstallField(item, "status_str");
return status === "Quarantined";
}
function getInstallTags(item) {
if (!item || typeof item !== "object") {
return null;
}
if (item.tags_raw && typeof item.tags_raw === "object" && !Array.isArray(item.tags_raw)) {
return item.tags_raw;
}
if (item.tags && typeof item.tags === "object" && !Array.isArray(item.tags)) {
if (!(item.tags.id && Object.prototype.hasOwnProperty.call(item.tags, "value"))) {
return item.tags;
}
}
if (item.cloudsmithMatch && item.cloudsmithMatch.tags && typeof item.cloudsmithMatch.tags === "object") {
return item.cloudsmithMatch.tags;
}
return null;
}
function getInstallOptions(item) {
const installOpts = {};
const tags = getInstallTags(item);
if (tags) {
installOpts.tags = tags;
}
const showDigest = vscode.workspace.getConfiguration("cloudsmith-vsc").get("showDockerDigestCommand", false);
if (showDigest) {
const checksumSha256 = getNestedInstallField(item, "checksum_sha256");
if (checksumSha256) {
installOpts.checksumSha256 = checksumSha256;
}
const versionDigest = getNestedInstallField(item, "version_digest");
if (versionDigest) {
installOpts.versionDigest = versionDigest;
}
}
const cdnUrl = getNestedInstallField(item, "cdn_url");
if (cdnUrl) {
installOpts.cdnUrl = cdnUrl;
}
const filename = getNestedInstallField(item, "filename");
if (filename) {
installOpts.filename = filename;
}
return installOpts;
}
async function pickInstallCommandVariant(result) {
if (!result.alternatives || result.alternatives.length === 0) {
return result.command;
}
const picks = [
{
label: "$(arrow-right) Primary",
description: InstallCommandBuilder.toClipboardCommand(result.command),
_cmd: result.command,
},
...result.alternatives.map(a => ({
label: `$(arrow-right) ${a.label}`,
description: InstallCommandBuilder.toClipboardCommand(a.command),
_cmd: a.command,
})),
];
const pick = await vscode.window.showQuickPick(picks, {
placeHolder: "Select an install command",
});
return pick ? pick._cmd : null;
}
/**
* Prompt user to select from recently interacted packages.
* Returns a package-like object or null if no selection made.
*/
async function pickRecentPackage() {
const recent = recentPackages.getAll();
if (recent.length === 0) {
vscode.window.showInformationMessage("No recent packages. Run this command from a package context menu.");
return null;
}
const selected = await vscode.window.showQuickPick(
recent.map(p => ({
label: p.name,
description: `${p.version || ""} — ${p.repository || ""}`,
_pkg: p,
})),
{ placeHolder: "Select a package" }
);
if (!selected) {
return null;
}
return selected._pkg;
}
const FILTER_PRESETS = [
{
label: "All packages",
applyBuilder: () => "",
},
{
label: "Available packages",
applyBuilder: (builder) => builder
.raw("NOT status:quarantined")
.raw("deny_policy_violated:false"),
},
{
label: "Quarantined packages",
applyBuilder: (builder) => builder.status("quarantined"),
},
{
label: "Packages with policy violations",
applyBuilder: (builder) => builder.raw("policy_violated:true"),
},
{
label: "$(shield) Vulnerable packages",
description: "Packages with known vulnerabilities",
applyBuilder: (builder) => builder.raw("vulnerabilities:>0"),
},
{
label: "Packages with vulnerability violations",
applyBuilder: (builder) => builder.raw("vulnerability_policy_violated:true"),
},
{
label: "Packages with license violations",
applyBuilder: (builder) => builder.raw("license_policy_violated:true"),
},
{
label: "Packages with restrictive licenses",
applyBuilder: (builder) => builder.raw(LicenseClassifier.buildRestrictiveQuery()),
},
{
label: "Custom query",
applyBuilder: null,
},
];
const FORMAT_OPTIONS = SUPPORTED_UPSTREAM_FORMATS;
/**
* Helper: get workspaces from cache or fetch fresh.
*/
const WORKSPACE_CACHE_TTL_MS = 30 * 60 * 1000; // 30 minutes
/**
* Helper: read the defaultWorkspace setting.
* Returns the slug string if set, or empty string if not.
*/
function getDefaultWorkspace() {
const config = vscode.workspace.getConfiguration("cloudsmith-vsc");
return config.get("defaultWorkspace") || "";
}
async function setConnectedContext(isConnected) {
await vscode.commands.executeCommand("setContext", "cloudsmith.connected", Boolean(isConnected));
}
async function setHasMultipleWorkspacesContext(hasMultipleWorkspaces) {
await vscode.commands.executeCommand(
"setContext",
"cloudsmith.hasMultipleWorkspaces",
Boolean(hasMultipleWorkspaces)
);
}
async function updateDefaultWorkspaceContext() {
await vscode.commands.executeCommand(
"setContext",
"cloudsmith.hasDefaultWorkspace",
Boolean(getDefaultWorkspace())
);
}
async function getWorkspaces(context) {
const cache = context.globalState.get('CloudsmithCache');
if (cache && cache.name === 'Workspaces' && cache.workspaces) {
// Check TTL — treat as stale if older than 30 minutes
if (cache.lastSync && (Date.now() - cache.lastSync) < WORKSPACE_CACHE_TTL_MS) {
await setHasMultipleWorkspacesContext(cache.workspaces.length > 1);
return cache.workspaces;
}
}
const cloudsmithAPI = new CloudsmithAPI(context);
const result = await cloudsmithAPI.get("namespaces/?sort=slug");
if (typeof result === 'string') {
await setHasMultipleWorkspacesContext(false);
vscode.window.showErrorMessage("Failed to load workspaces: " + result);
return null;
}
if (!result || result.length === 0) {
await setHasMultipleWorkspacesContext(false);
return [];
}
await setHasMultipleWorkspacesContext(result.length > 1);
return result;
}
async function getPreferredTextDocumentLanguage() {
const availableLanguages = new Set(await vscode.languages.getLanguages());
if (availableLanguages.has("terraform")) {
return "terraform";
}
if (availableLanguages.has("hcl")) {
return "hcl";
}
return "plaintext";
}
function buildRawSearchQuery(query) {
return new SearchQueryBuilder().raw(query).build();
}
function buildPresetQuery(preset, customQuery) {
if (!preset) {
return "";
}
if (preset.applyBuilder === null) {
return buildRawSearchQuery(customQuery || "");
}
const builder = new SearchQueryBuilder();
const maybeString = preset.applyBuilder(builder);
if (typeof maybeString === "string") {
return maybeString;
}
return builder.build();
}
/**
* @param {vscode.ExtensionContext} context
*/
async function activate(context) {
await context.secrets.store("cloudsmith-vsc.isConnected", "false");
await setConnectedContext(false);
await setHasMultipleWorkspacesContext(false);
await updateDefaultWorkspaceContext();
// Define main view provider which populates with data
const cloudsmithProvider = new CloudsmithProvider(context);
const treeView = vscode.window.createTreeView("cloudsmithView", {
treeDataProvider: cloudsmithProvider,
showCollapseAll: true,
});
cloudsmithProvider.setTreeView(treeView);
cloudsmithProvider.setDefaultWorkspaceFallbackHandler((slug) => {
treeView.title = "Workspaces";
treeView.description = "";
vscode.window.showWarningMessage(
`Could not access workspace "${slug}". Showing all workspaces.`
);
});
// Set tree view title and description from default workspace setting
const defaultWs = getDefaultWorkspace();
if (defaultWs) {
treeView.title = "Repositories";
treeView.description = defaultWs;
}
// Listen for configuration changes to refresh tree when defaultWorkspace changes
context.subscriptions.push(
vscode.workspace.onDidChangeConfiguration(async e => {
if (e.affectsConfiguration("cloudsmith-vsc.defaultWorkspace")) {
await updateDefaultWorkspaceContext();
const newDefault = getDefaultWorkspace();
treeView.title = newDefault ? "Repositories" : "Workspaces";
treeView.description = newDefault || "";
cloudsmithProvider.refresh();
}
})
);
// Set Help & Feedback view.
const provider = new helpProvider();
vscode.window.registerTreeDataProvider("helpView", provider);
// Set Package Search view.
const searchProvider = new SearchProvider(context);
vscode.window.createTreeView("cloudsmithSearchView", {
treeDataProvider: searchProvider,
showCollapseAll: true,
});
// Set Dependency Health view with diagnostics publisher.
const diagnosticsPublisher = new DiagnosticsPublisher();
context.subscriptions.push(diagnosticsPublisher);
const dependencyHealthProvider = new DependencyHealthProvider(context, diagnosticsPublisher);
vscode.window.createTreeView("cloudsmithDependencyHealthView", {
treeDataProvider: dependencyHealthProvider,
showCollapseAll: true,
});
context.subscriptions.push(
context.secrets.onDidChange(async (e) => {
if (e.key !== "cloudsmith-vsc.authToken") {
return;
}
const apiKey = await context.secrets.get("cloudsmith-vsc.authToken");
if (apiKey) {
return;
}
await context.secrets.store("cloudsmith-vsc.isConnected", "false");
await setConnectedContext(false);
await setHasMultipleWorkspacesContext(false);
cloudsmithProvider.refresh({ suppressMissingCredentialsWarning: true });
searchProvider.refresh();
dependencyHealthProvider.refresh();
})
);
// Create vulnerability WebView provider
const vulnerabilityProvider = new VulnerabilityProvider(context);
context.subscriptions.push({ dispose: () => vulnerabilityProvider.dispose() });
// Create quarantine explanation WebView provider
const quarantineExplainProvider = new QuarantineExplainProvider(context);
context.subscriptions.push({ dispose: () => quarantineExplainProvider.dispose() });
// Create upstream preview WebView provider
const upstreamPreviewProvider = new UpstreamPreviewProvider(context);
context.subscriptions.push({ dispose: () => upstreamPreviewProvider.dispose() });
// Create upstream detail WebView provider
const upstreamDetailProvider = new UpstreamDetailProvider(context);
context.subscriptions.push({ dispose: () => upstreamDetailProvider.dispose() });
// Create promotion provider
const promotionProvider = new PromotionProvider(context);
const initializeConnectionContext = async () => {
const credentialManager = new CredentialManager(context);
const apiKey = await credentialManager.getApiKey();
if (!apiKey) {
return;
}
try {
const { ConnectionManager } = require("./util/connectionManager");
const connectionManager = new ConnectionManager(context);
await connectionManager.checkConnectivity(apiKey);
} catch {
await context.secrets.store("cloudsmith-vsc.isConnected", "false");
await setConnectedContext(false);
}
};
void initializeConnectionContext();
// Auto-scan dependencies on open if configured
const autoScanConfig = vscode.workspace.getConfiguration("cloudsmith-vsc");
if (autoScanConfig.get("autoScanOnOpen")) {
const scanWorkspace = autoScanConfig.get("dependencyScanWorkspace");
if (scanWorkspace) {
const scanRepo = autoScanConfig.get("dependencyScanRepo") || null;
// Delay to avoid blocking VS Code startup
setTimeout(() => {
dependencyHealthProvider.scan(scanWorkspace, scanRepo);
}, 2000);
} else {
vscode.window.showInformationMessage(
"Auto-scan is enabled but no Cloudsmith workspace is configured.",
"Configure"
).then((selection) => {
if (selection === "Configure") {
vscode.commands.executeCommand("workbench.action.openSettings", "cloudsmith-vsc.dependencyScanWorkspace");
}
});
}
}
// Shared post-authentication handler: connect, refresh all views, and prompt
// to set default workspace if only one workspace is available.
async function postAuthSuccess() {
const { ConnectionManager } = require("./util/connectionManager");
const connectionManager = new ConnectionManager(context);
const status = await connectionManager.connect();
// Refresh all three sidebar views
cloudsmithProvider.refresh();
searchProvider.refresh();
dependencyHealthProvider.refresh();
// If connected and no default workspace, offer to set the single workspace as default
if (status === "true" && !getDefaultWorkspace()) {
const workspaces = await getWorkspaces(context);
if (Array.isArray(workspaces) && workspaces.length === 1) {
const ws = workspaces[0];
const choice = await vscode.window.showInformationMessage(
`One workspace available: ${ws.name}. Set as default?`,
"Set as default", "Dismiss"
);
if (choice === "Set as default") {
const config = vscode.workspace.getConfiguration("cloudsmith-vsc");
await config.update("defaultWorkspace", ws.slug, vscode.ConfigurationTarget.Global);
await updateDefaultWorkspaceContext();
treeView.title = "Repositories";
treeView.description = ws.slug;
cloudsmithProvider.refresh();
}
}
}
return status;
}
// Auto-detect Cloudsmith CLI credentials on activation.
// If no API key is stored but CLI credentials exist, offer to import them.
setTimeout(async () => {
const existingKey = await context.secrets.get("cloudsmith-vsc.authToken");
if (!existingKey) {
const ssoManager = new SSOAuthManager(context);
if (ssoManager.hasCLICredentials()) {
const choice = await vscode.window.showInformationMessage(
"Cloudsmith CLI credentials detected. Import them?",
"Import", "Dismiss"
);
if (choice === "Import") {
const success = await ssoManager.importFromCLI();
if (success) {
await postAuthSuccess();
}
}
}
}
}, 3000);
// register general commands. Will move this over to command Manager in future release.
context.subscriptions.push(
// Register command to clear credentials
vscode.commands.registerCommand("cloudsmith-vsc.clearCredentials", () => {
const credentialManager = new CredentialManager(context);
credentialManager.clearCredentials();
}),
// Register command to set credentials — QuickPick with four auth methods
vscode.commands.registerCommand("cloudsmith-vsc.configureCredentials", async () => {
const authOptions = [
{ label: "$(key) Enter API key", description: "Paste a personal API key", _method: "apikey" },
{ label: "$(server) Enter service account API key", description: "Paste a service account API key", _method: "apikey" },
{ label: "$(folder-opened) Import from Cloudsmith CLI", description: "Import credentials from CLI config (~/.cloudsmith/config.ini)", _method: "import" },
{ label: "$(terminal) Sign in with SSO", description: "Run 'cloudsmith auth' in an integrated terminal", _method: "sso-terminal" },
];
const selected = await vscode.window.showQuickPick(authOptions, {
placeHolder: "Select an authentication method",
});
if (!selected) {
return;
}
if (selected._method === "sso-terminal") {
await vscode.commands.executeCommand("cloudsmith-vsc.ssoLogin");
} else if (selected._method === "import") {
await vscode.commands.executeCommand("cloudsmith-vsc.importCLICredentials");
} else {
const credentialManager = new CredentialManager(context);
const stored = await credentialManager.storeApiKey();
if (stored) {
await postAuthSuccess();
}
}
}),
// Register command to connect to Cloudsmith
vscode.commands.registerCommand("cloudsmith-vsc.connectCloudsmith", async () => {
await postAuthSuccess();
}),
// Register set default workspace command
vscode.commands.registerCommand("cloudsmith-vsc.setDefaultWorkspace", async () => {
const workspaces = await getWorkspaces(context);
if (!workspaces) {
return;
}
if (workspaces.length === 0) {
vscode.window.showErrorMessage("No workspaces found. Connect to Cloudsmith first.");
return;
}
const items = [
{ label: "$(close) Clear default workspace", description: "Show all workspaces", _clear: true },
];
for (const ws of workspaces) {
items.push({ label: ws.name, description: ws.slug });
}
const selected = await vscode.window.showQuickPick(items, {
placeHolder: "Select a default workspace",
});
if (!selected) {
return;
}
const config = vscode.workspace.getConfiguration("cloudsmith-vsc");
if (selected._clear) {
await config.update("defaultWorkspace", "", vscode.ConfigurationTarget.Global);
await updateDefaultWorkspaceContext();
treeView.title = "Workspaces";
treeView.description = "";
} else {
await config.update("defaultWorkspace", selected.description, vscode.ConfigurationTarget.Global);
await updateDefaultWorkspaceContext();
treeView.title = "Repositories";
treeView.description = selected.description;
}
cloudsmithProvider.refresh();
}),
// Register refresh command for main view
vscode.commands.registerCommand("cloudsmith-vsc.refreshView", () => {
cloudsmithProvider.refresh();
searchProvider.refresh();
dependencyHealthProvider.refresh();
}),
// Register the copy-to-clipboard command
vscode.commands.registerCommand("cloudsmith-vsc.copySelected", async (item) => {
// Handle the structured argument from PackageDetailsNode command
let value;
if (item && item._detailId !== undefined) {
value = item._detailValue;
} else if (item && item.label && item.label.id !== undefined) {
// Legacy double-wrapped format
value = item.label.value;
} else if (typeof item === "string") {
value = item;
} else {
vscode.window.showWarningMessage("Run this command from a package context menu.");
return;
}
if (value != null) {
await vscode.env.clipboard.writeText(String(value));
vscode.window.showInformationMessage("Value copied.");
} else {
vscode.window.showWarningMessage("Run this command from a package context menu.");
}
}),
// Register the inspect package command
vscode.commands.registerCommand(
"cloudsmith-vsc.inspectPackage",
async (item) => {
if (!item) {
item = await pickRecentPackage();
if (!item) return;
}
recentPackages.add(item);
const cloudsmithAPI = new CloudsmithAPI(context);
const name = typeof item === "string" ? item : item.name;
const workspace = typeof item === "string" ? item : item.namespace;
const identifier = unwrapValue(item.slug_perm);
const repo = typeof item === "string" ? item : item.repository;
if (identifier) {
const result = await cloudsmithAPI.get(
`packages/${workspace}/${repo}/${identifier}`
);
if (typeof result === "string") {
vscode.window.showErrorMessage(formatApiError(result));
return;
}
const jsonContent = JSON.stringify(result, null, 2);
const config = vscode.workspace.getConfiguration("cloudsmith-vsc");
const inspectOutput = await config.get("inspectOutput");
if (inspectOutput) {
const doc = await vscode.workspace.openTextDocument({
language: "json",
content: jsonContent,
});
await vscode.window.showTextDocument(doc, { preview: true });
} else {
const outputChannel =
vscode.window.createOutputChannel("Cloudsmith");
outputChannel.clear();
outputChannel.show(true);
outputChannel.append(jsonContent);
}
vscode.window.showInformationMessage(
`Inspecting package ${name} in repository ${repo}.`
);
} else {
vscode.window.showWarningMessage("Run this command from a package context menu.");
}
}
),
// Register the inspect package group command
vscode.commands.registerCommand(
"cloudsmith-vsc.inspectPackageGroup",
async (item) => {
if (!item) {
vscode.window.showWarningMessage("Run this command from a package context menu.");
return;
}
const cloudsmithAPI = new CloudsmithAPI(context);
const name = typeof item === "string" ? item : item.name;
const workspace = typeof item === "string" ? item : item.workspace;
const repo = typeof item === "string" ? item : item.repo;
if (name) {
const result = await cloudsmithAPI.get(
`packages/${workspace}/${repo}/?query=name:"${name}"`
);
if (typeof result === "string") {
vscode.window.showErrorMessage(formatApiError(result));
return;
}
const jsonContent = JSON.stringify(result, null, 2);
const config = vscode.workspace.getConfiguration("cloudsmith-vsc");
const inspectOutput = await config.get("inspectOutput");
if (inspectOutput) {
const doc = await vscode.workspace.openTextDocument({
language: "json",
content: jsonContent,
});
await vscode.window.showTextDocument(doc, { preview: true });
} else {
const outputChannel =
vscode.window.createOutputChannel("Cloudsmith");
outputChannel.clear();
outputChannel.show(true);
outputChannel.append(jsonContent);
}
vscode.window.showInformationMessage(
`Inspecting package group ${name}.`
);
} else {
vscode.window.showWarningMessage("Run this command from a package context menu.");
}
}
),
// Register the open package command
vscode.commands.registerCommand("cloudsmith-vsc.openPackage", async (item) => {
if (!item) {
item = await pickRecentPackage();
if (!item) return;
}
recentPackages.add(item);
const workspace = typeof item === "string" ? item : item.namespace;
const repo = typeof item === "string" ? item : item.repository;
const format = typeof item === "string" ? item : item.format;
const name = typeof item === "string" ? item : item.name;
const version = unwrapValue(item.version);
const identifier = unwrapValue(item.slug_perm);
//need to replace '/' in name as UI URL replaces these with _
const pkg = name.replaceAll("/", "_");
const config = vscode.workspace.getConfiguration("cloudsmith-vsc");
const useLegacyApp = await config.get("useLegacyWebApp");
if (identifier) {
if (useLegacyApp) {
const url = `https://cloudsmith.io/~${workspace}/repos/${repo}/packages/detail/${format}/${pkg}/${version}`;
vscode.env.openExternal(vscode.Uri.parse(url));
} else {
const url = `https://app.cloudsmith.com/${workspace}/${repo}/${format}/${pkg}/${version}/${identifier}`;
vscode.env.openExternal(vscode.Uri.parse(url));
}
} else {
vscode.window.showWarningMessage("Run this command from a package context menu.");
}
}),
// Register the open package group command
vscode.commands.registerCommand("cloudsmith-vsc.openPackageGroup", async (item) => {
if (!item) {
vscode.window.showWarningMessage("Run this command from a package context menu.");
return;
}
const workspace = typeof item === "string" ? item : item.workspace;
const repo = typeof item === "string" ? item : item.repo;
const name = typeof item === "string" ? item : item.name;
if (name) {
// Encode special characters for URL
const encodedName = name.replaceAll("/", "%2F").replaceAll(":", "%3A");
const url = `https://app.cloudsmith.com/${workspace}/${repo}?page=1&query=name:${encodedName}&sort=name`;
vscode.env.openExternal(vscode.Uri.parse(url));
} else {
vscode.window.showWarningMessage("Run this command from a package context menu.");
}
}),
// Register command to open extension settings
vscode.commands.registerCommand("cloudsmith-vsc.openSettings", () => {
vscode.commands.executeCommand(
"workbench.action.openSettings",
"@ext:Cloudsmith.cloudsmith-vsc"
);
}),
vscode.commands.registerCommand("cloudsmith-vscode-extension.cloudsmithDocs", () => {
vscode.env.openExternal(vscode.Uri.parse("https://docs.cloudsmith.com/"));
}),
// Register search packages command
vscode.commands.registerCommand("cloudsmith-vsc.searchPackages", async () => {
const defaultWsSlug = getDefaultWorkspace();
let workspaceSlug = defaultWsSlug;
let recentSearches = workspaceSlug ? new RecentSearches(context, workspaceSlug) : null;
if (!workspaceSlug) {
const workspaces = await getWorkspaces(context);
if (!workspaces) {
return;
}
if (workspaces.length === 0) {
vscode.window.showErrorMessage("No workspaces found. Connect to Cloudsmith first.");
return;
}
const items = [];
for (const ws of workspaces) {
items.push({ label: ws.name, description: ws.slug });
}
const selected = await vscode.window.showQuickPick(items, {
placeHolder: "Select a workspace",
});
if (!selected) {
return;
}
workspaceSlug = selected.description;
recentSearches = new RecentSearches(context, workspaceSlug);
}
const recent = recentSearches.getAll();
if (recent.length > 0) {
const items = [
{ label: "Recent searches", kind: vscode.QuickPickItemKind.Separator },
];
for (const r of recent) {
items.push({
label: `$(history) ${r.query}`,
description: r.workspace,
_recent: r,
});
}
items.push({ label: "New search", kind: vscode.QuickPickItemKind.Separator });
items.push({ label: `$(search) New search in ${workspaceSlug}`, _new: true });
const selected = await vscode.window.showQuickPick(items, {
placeHolder: `Search packages in ${workspaceSlug}`,
});
if (!selected) {
return;
}
if (selected._recent) {
await searchProvider.search(selected._recent.workspace, selected._recent.query);
return;
}
}
// Show search input
const query = await vscode.window.showInputBox({
placeHolder: "Search packages (e.g., name:flask, format:python)",
prompt: `Search packages in ${workspaceSlug}`,
});
if (!query) {
return;
}
const builtQuery = buildRawSearchQuery(query);
recentSearches.add({ workspace: workspaceSlug, query: builtQuery, scope: 'workspace' });
await searchProvider.search(workspaceSlug, builtQuery);
}),
// Register clear search command
vscode.commands.registerCommand("cloudsmith-vsc.clearSearch", () => {
searchProvider.clear();
diagnosticsPublisher.clear();
}),
// Register load next page command
vscode.commands.registerCommand("cloudsmith-vsc.searchNextPage", async () => {
await searchProvider.loadNextPage();
}),
// Register search in workspace (from workspace context menu or view title)
vscode.commands.registerCommand("cloudsmith-vsc.searchInWorkspace", async (item) => {
let workspace;
if (item && (item.slug || item.name)) {
workspace = item.slug || item.name;
} else {
// Called from view/title with no item — use default workspace
workspace = getDefaultWorkspace();
}
if (!workspace) {
vscode.window.showWarningMessage("Could not determine the workspace. Set a default workspace in settings.");
return;
}
const query = await vscode.window.showInputBox({
placeHolder: "Search packages (e.g., name:flask, format:python)",
prompt: `Search packages in ${workspace}`,
});
if (!query) {
return;
}
const recentSearches = new RecentSearches(context, workspace);
const builtQuery = buildRawSearchQuery(query);
recentSearches.add({ workspace: workspace, query: builtQuery, scope: 'workspace' });
await searchProvider.search(workspace, builtQuery);
}),
// Register guided search command
vscode.commands.registerCommand("cloudsmith-vsc.guidedSearch", async () => {
const defaultWsSlug = getDefaultWorkspace();
let workspaceSlug = defaultWsSlug;
let recentSearches = workspaceSlug ? new RecentSearches(context, workspaceSlug) : null;
if (!workspaceSlug) {
const workspaces = await getWorkspaces(context);
if (!workspaces) {
return;
}
if (workspaces.length === 0) {
vscode.window.showErrorMessage("No workspaces found. Connect to Cloudsmith first.");
return;
}
// Step 1: Select workspace
const wsItems = [];
for (const ws of workspaces) {
wsItems.push({ label: ws.name, description: ws.slug });
}
const selectedWs = await vscode.window.showQuickPick(wsItems, {
placeHolder: "Step 1: Select a workspace",
});
if (!selectedWs) {
return;
}
workspaceSlug = selectedWs.description;
recentSearches = new RecentSearches(context, workspaceSlug);
}
const recent = recentSearches.getAll();
if (recent.length > 0) {
const recentItems = [
{ label: "Recent searches", kind: vscode.QuickPickItemKind.Separator },
];
for (const r of recent) {
recentItems.push({
label: `$(history) ${r.query}`,
description: r.workspace,
_recent: r,
});
}
recentItems.push({ label: "Continue guided search", kind: vscode.QuickPickItemKind.Separator });
recentItems.push({ label: `$(search) Continue guided search in ${workspaceSlug}`, _new: true });
const selectedRecent = await vscode.window.showQuickPick(recentItems, {
placeHolder: `Recent searches in ${workspaceSlug}`,
});
if (!selectedRecent) {
return;
}
if (selectedRecent._recent) {
await searchProvider.search(selectedRecent._recent.workspace, selectedRecent._recent.query);
return;
}
}
// Step 2: Select scope
const scopeItems = [
{ label: "All repositories", description: "Search across the entire workspace" },
{ label: "Select specific repositories", description: "Choose one or more repositories" },
];
const selectedScope = await vscode.window.showQuickPick(scopeItems, {
placeHolder: "Step 2: Select a search scope",
});
if (!selectedScope) {
return;
}
let selectedRepos = null;
if (selectedScope.label === "Select specific repositories") {
const cloudsmithAPI = new CloudsmithAPI(context);
const repos = await cloudsmithAPI.get(`repos/${workspaceSlug}/?sort=name`);
if (typeof repos === 'string' || !repos || repos.length === 0) {
vscode.window.showErrorMessage("No repositories found in this workspace.");
return;
}
const repoItems = repos.map(r => ({ label: r.name, description: r.slug }));