-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathextract_bazel_to_maven.test.mts
More file actions
1483 lines (1419 loc) · 48 KB
/
Copy pathextract_bazel_to_maven.test.mts
File metadata and controls
1483 lines (1419 loc) · 48 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
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { logger } from '@socketsecurity/registry/lib/logger'
// Mock collaborators BEFORE importing the orchestrator. The orchestrator
// composes pure-function discovery + the metadata cquery + a workspace
// walker; mocking these lets us drive end-to-end behaviour without a
// real Bazel toolchain.
vi.mock('./bazel-bin-detect.mts', () => ({
resolveBazelBinary: vi.fn(async () => '/usr/local/bin/bazel'),
}))
vi.mock('./bazel-output-base-check.mts', () => ({
validateOutputBase: vi.fn(),
}))
vi.mock('./bazel-java-shim.mts', () => ({
ensureJavaOnPath: vi.fn(),
}))
vi.mock('./bazel-python-shim.mts', () => ({
provisionPythonShim: vi.fn(async () => ({
augmentedEnv: undefined,
shimDir: undefined,
})),
}))
vi.mock('./bazel-workspace-detect.mts', () => ({
detectWorkspaceMode: vi.fn(),
getBazelInvocationFlags: vi.fn(() => []),
}))
vi.mock('./bazel-workspace-walk.mts', () => ({
findWorkspaceRoots: vi.fn(),
}))
vi.mock('./bazel-query-runner.mts', () => ({
buildMavenProbeFor: vi.fn(() => defaultMavenProbe),
runBazelModShowMavenExtension: vi.fn(),
}))
vi.mock('./bazel-repo-discovery.mts', async () => {
// Preserve `CONVENTIONAL_MAVEN_REPO_NAMES` + `probeCandidate` while
// overriding `parseShowExtensionOutput` with a spy.
const actual = await vi.importActual<
typeof import('./bazel-repo-discovery.mts')
>('./bazel-repo-discovery.mts')
return {
...actual,
parseShowExtensionOutput: vi.fn(actual.parseShowExtensionOutput),
}
})
vi.mock('./bazel-cquery.mts', () => ({
runMetadataCqueryForRepo: vi.fn(),
}))
// Quiet the spawn calls reapBazelServer makes during cleanup.
vi.mock('@socketsecurity/registry/lib/spawn', () => ({
spawn: vi.fn(async () => ({ code: 0, stdout: '', stderr: '' })),
}))
import { runMetadataCqueryForRepo } from './bazel-cquery.mts'
import {
buildMavenProbeFor,
runBazelModShowMavenExtension,
} from './bazel-query-runner.mts'
import { parseShowExtensionOutput } from './bazel-repo-discovery.mts'
import { detectWorkspaceMode } from './bazel-workspace-detect.mts'
import { findWorkspaceRoots } from './bazel-workspace-walk.mts'
import {
dedupArtifactsByCoord,
extractBazelToMaven,
normalizeToMavenInstallJson,
} from './extract_bazel_to_maven.mts'
import type { CqueryRepoResult, ExtractedArtifact } from './bazel-cquery.mts'
async function defaultMavenProbe(_: string): Promise<{
code: number
stdout: string
stderr: string
}> {
return {
code: 1,
stdout: '',
stderr: "ERROR: No repository visible as '@x' from main repository\n",
}
}
function readManifest(out: string, ...rel: string[]): unknown {
return JSON.parse(
readFileSync(
path.join(out, '.socket-auto-manifest', ...rel, 'maven_install.json'),
'utf8',
),
)
}
function readNamedManifest(
out: string,
fileName: string,
...rel: string[]
): unknown {
return JSON.parse(
readFileSync(
path.join(out, '.socket-auto-manifest', ...rel, fileName),
'utf8',
),
)
}
const mkResult = (over: Partial<CqueryRepoResult>): CqueryRepoResult => ({
artifacts: [],
durationMs: 0,
repoName: 'maven',
status: 'ok',
stderr: '',
unresolvedLabels: [],
workspaceRelPath: '',
...over,
})
const mkArt = (
coord: string,
ruleName: string,
over: Partial<ExtractedArtifact> = {},
): ExtractedArtifact => ({
deps: [],
mavenCoordinates: coord,
ruleKind: 'jvm_import',
ruleName,
sourceRepo: 'maven',
...over,
})
const SHOW_EXT_HUB_ONLY = `## @@rules_jvm_external+//:extensions.bzl%maven:
Fetched repositories:
- maven (imported by <root>)
`
describe('extractBazelToMaven', () => {
let tmp: string
beforeEach(() => {
tmp = mkdtempSync(path.join(os.tmpdir(), 'sock-bazel-x2m-'))
vi.mocked(detectWorkspaceMode).mockReturnValue({
bzlmod: true,
workspace: false,
})
vi.mocked(findWorkspaceRoots).mockReturnValue([tmp])
vi.mocked(runBazelModShowMavenExtension).mockResolvedValue({
code: 0,
stdout: SHOW_EXT_HUB_ONLY,
stderr: '',
})
vi.mocked(parseShowExtensionOutput).mockClear()
vi.mocked(runBazelModShowMavenExtension).mockClear()
vi.mocked(runMetadataCqueryForRepo).mockReset()
vi.mocked(buildMavenProbeFor).mockReset()
vi.mocked(buildMavenProbeFor).mockReturnValue(async () => ({
code: 1,
stdout: '',
stderr: "ERROR: No repository visible as '@x' from main repository\n",
}))
})
afterEach(() => {
rmSync(tmp, { recursive: true, force: true })
})
it('extracts a single Bzlmod workspace end-to-end', async () => {
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [
mkArt('com.google.guava:guava:33.0.0-jre', 'com_google_guava_guava'),
mkArt('androidx.annotation:annotation:1.8.2', 'androidx_annotation'),
],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('complete')
expect(result.artifactCount).toBe(2)
expect(result.manifestPaths).toHaveLength(1)
const manifest = readManifest(tmp) as {
artifacts: Record<string, { version: string }>
}
expect(Object.keys(manifest.artifacts).sort()).toEqual([
'androidx.annotation:annotation',
'com.google.guava:guava',
])
})
it('returns status:noEcosystem when no workspace roots are discovered', async () => {
vi.mocked(findWorkspaceRoots).mockReturnValue([])
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('noEcosystem')
expect(result.manifestPaths).toEqual([])
})
it('returns status:hardFailure when discovered repos write zero manifests', async () => {
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({ artifacts: [], status: 'empty', repoName: 'maven' }),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('hardFailure')
expect(result.manifestPaths).toEqual([])
})
it('writes one manifest per workspace at mirrored paths (no cross-workspace aggregation)', async () => {
const nested = path.join(tmp, 'examples', 'dagger')
mkdirSync(nested, { recursive: true })
vi.mocked(findWorkspaceRoots).mockReturnValue([tmp, nested])
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [
// A previously-conflicting g:a at a different version per workspace
// now lands in separate files without error.
mkArt('com.google.guava:guava:32.0.0-jre', 'com_google_guava_guava'),
],
repoName: 'maven',
workspaceRelPath: '',
}),
)
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [
mkArt('com.google.guava:guava:33.0.0-jre', 'com_google_guava_guava', {
sourceRepo: 'examples/dagger:maven',
}),
mkArt('com.google.dagger:dagger:2.50', 'com_google_dagger_dagger', {
sourceRepo: 'examples/dagger:maven',
}),
],
repoName: 'maven',
workspaceRelPath: 'examples/dagger',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('complete')
expect(result.manifestPaths).toHaveLength(2)
// Root workspace: one file at the manifest dir root.
const rootManifest = readManifest(tmp) as {
artifacts: Record<string, { version: string }>
}
expect(rootManifest.artifacts['com.google.guava:guava']?.version).toBe(
'32.0.0-jre',
)
// Nested workspace: mirrored path.
const nestedManifest = readManifest(tmp, 'examples', 'dagger') as {
artifacts: Record<string, { version: string }>
}
expect(Object.keys(nestedManifest.artifacts).sort()).toEqual([
'com.google.dagger:dagger',
'com.google.guava:guava',
])
expect(nestedManifest.artifacts['com.google.guava:guava']?.version).toBe(
'33.0.0-jre',
)
})
it('writes one manifest per hub in a single workspace', async () => {
vi.mocked(runBazelModShowMavenExtension).mockResolvedValue({
code: 0,
stdout: `## @@rules_jvm_external+//:extensions.bzl%maven:
Fetched repositories:
- maven (imported by <root>)
- maven_dev (imported by <root>)
`,
stderr: '',
})
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:b:1.0', 'b')],
repoName: 'maven_dev',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('complete')
expect(result.manifestPaths).toHaveLength(2)
expect(
Object.keys(
(readManifest(tmp) as { artifacts: Record<string, unknown> }).artifacts,
),
).toEqual(['com.example:a'])
expect(
Object.keys(
(
readNamedManifest(tmp, 'maven_dev_maven_install.json') as {
artifacts: Record<string, unknown>
}
).artifacts,
),
).toEqual(['com.example:b'])
})
it('unions resolved edges across deduped occurrences of a coordinate', () => {
// The dedup keeps one artifact per full coordinate but must union the
// resolved edges of every occurrence; otherwise edges resolved against a
// second workspace's targets would be silently dropped. Verified directly
// on the dedup+normalize path so the edge targets need to be listed.
const manifest = normalizeToMavenInstallJson(
dedupArtifactsByCoord([
mkArt('com.google.guava:guava:33.0.0-jre', 'guava', {
deps: ['com.google.dagger:dagger'],
}),
mkArt('com.google.guava:guava:33.0.0-jre', 'guava', {
deps: ['com.x:x'],
}),
mkArt('com.google.dagger:dagger:2.50', 'dagger'),
mkArt('com.x:x:1.0', 'x'),
]),
)
expect(
manifest.json.dependencies['com.google.guava:guava']?.sort(),
).toEqual(['com.google.dagger:dagger', 'com.x:x'])
expect(manifest.prunedEdges).toEqual([])
})
it('returns status:partial on a per-repo timeout but keeps the survivor', async () => {
// Two candidates: first times out, second succeeds. The orchestrator
// re-mints --output_user_root after the timeout and still writes the
// survivor's manifest.
vi.mocked(runBazelModShowMavenExtension).mockResolvedValue({
code: 0,
stdout: `## @@rules_jvm_external+//:extensions.bzl%maven:
Fetched repositories:
- maven (imported by <root>)
- maven_dev (imported by <root>)
`,
stderr: '',
})
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({ artifacts: [], status: 'timeout', repoName: 'maven' }),
)
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:after:1.0', 'after')],
repoName: 'maven_dev',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
perRepoTimeoutMs: 60_000,
verbose: false,
})
expect(result.status).toBe('partial')
expect(result.artifactCount).toBe(1)
expect(result.manifestPaths).toHaveLength(1)
expect(
Object.keys(
(
readNamedManifest(tmp, 'maven_dev_maven_install.json') as {
artifacts: Record<string, unknown>
}
).artifacts,
),
).toEqual(['com.example:after'])
})
it('returns status:partial when a hub reports unresolved dependency edges', async () => {
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
status: 'partial',
unresolvedLabels: ['@maven//:missing'],
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('partial')
expect(result.manifestPaths).toHaveLength(1)
})
it('returns status:partial when cquery itself reported partial (no unresolved labels)', async () => {
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
status: 'partial',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('partial')
expect(result.manifestPaths).toHaveLength(1)
})
it('does not abort the walk when a hub manifest write fails', async () => {
// Point `out` at a regular file so the manifest dir cannot be created;
// the write throws and must be swallowed into a hub failure, not abort.
const blocker = path.join(tmp, 'blocker')
writeFileSync(blocker, '')
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: blocker,
outLayout: 'flat',
verbose: false,
})
// The only hub failed to write, so zero manifests + ecosystem present.
expect(result.status).toBe('hardFailure')
expect(result.manifestPaths).toEqual([])
})
it('applies the default walker prune policy even when the caller passes none (A)', async () => {
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
const calls = vi.mocked(findWorkspaceRoots).mock.calls
const call = calls[calls.length - 1]![0]
const names = [...(call.ignoreDirNames ?? [])]
expect(names).toContain('node_modules')
expect(names).toContain('.git')
expect(names).toContain('.socket-auto-manifest')
expect(call.ignoreDirPrefixes).toContain('bazel-')
})
it('extends (not replaces) the default prune policy with caller-supplied dirs', async () => {
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
ignoreDirNames: new Set(['custom_dir']),
ignoreDirPrefixes: ['gen-'],
out: tmp,
outLayout: 'flat',
verbose: false,
})
const calls = vi.mocked(findWorkspaceRoots).mock.calls
const call = calls[calls.length - 1]![0]
const names = [...(call.ignoreDirNames ?? [])]
expect(names).toEqual(
expect.arrayContaining(['node_modules', 'custom_dir']),
)
expect(call.ignoreDirPrefixes).toEqual(
expect.arrayContaining(['bazel-', 'gen-']),
)
})
it('keeps only root-imported hubs, dropping transitive ruleset hubs (B)', async () => {
vi.mocked(runBazelModShowMavenExtension).mockResolvedValue({
code: 0,
stdout: `## @@rules_jvm_external+//:extensions.bzl%maven:
Fetched repositories:
- maven (imported by <root>)
- rules_jvm_external_deps (imported by rules_jvm_external@6.7)
- stardoc_maven (imported by stardoc@0.7.2)
`,
stderr: '',
})
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('complete')
// Only @maven is queried; the ruleset hubs are filtered out.
expect(runMetadataCqueryForRepo).toHaveBeenCalledTimes(1)
expect(vi.mocked(runMetadataCqueryForRepo).mock.calls[0]![0]).toMatchObject(
{ repoName: 'maven' },
)
})
it('falls back to conventional probing when show_extension lists only non-root hubs (E)', async () => {
vi.mocked(runBazelModShowMavenExtension).mockResolvedValue({
code: 0,
stdout: `## @@rules_jvm_external+//:extensions.bzl%maven:
Fetched repositories:
- stardoc_maven (imported by stardoc@0.7.2)
`,
stderr: '',
})
// All entries are non-root, so the filter yields zero kept hubs and the
// probe fallback must still run. The probe accepts conventional @maven.
vi.mocked(buildMavenProbeFor).mockReturnValue(async (name: string) => {
if (name === 'maven') {
return { code: 0, stdout: '@maven//:x\n', stderr: '' }
}
return {
code: 1,
stdout: '',
stderr: "ERROR: No repository visible as '@x' from main repository\n",
}
})
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('complete')
expect(runMetadataCqueryForRepo).toHaveBeenCalledTimes(1)
expect(vi.mocked(runMetadataCqueryForRepo).mock.calls[0]![0]).toMatchObject(
{ repoName: 'maven' },
)
})
it('probes conventional hub names in WORKSPACE mode', async () => {
vi.mocked(detectWorkspaceMode).mockReturnValue({
bzlmod: false,
workspace: true,
})
// Probe accepts the conventional `maven` hub; others return not-defined.
vi.mocked(buildMavenProbeFor).mockReturnValue(async (name: string) => {
if (name === 'maven') {
return { code: 0, stdout: '@maven//:foo\n', stderr: '' }
}
return {
code: 1,
stdout: '',
stderr: "ERROR: No repository visible as '@x' from main repository\n",
}
})
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:custom:1.0', 'custom')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('complete')
expect(result.artifactCount).toBe(1)
expect(runMetadataCqueryForRepo).toHaveBeenCalledTimes(1)
expect(vi.mocked(runMetadataCqueryForRepo).mock.calls[0]![0]).toMatchObject(
{ repoName: 'maven' },
)
// show_extension must NOT be called in pure WORKSPACE mode.
expect(runBazelModShowMavenExtension).not.toHaveBeenCalled()
})
it('narrates the per-hub cquery under verbose without changing the outcome', async () => {
const logSpy = vi.spyOn(logger, 'log').mockImplementation(() => logger)
try {
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: true,
})
expect(result.status).toBe('complete')
const logged = logSpy.mock.calls.map(c => String(c[0])).join('\n')
expect(logged).toMatch(/running metadata cquery for @maven/)
expect(logged).toMatch(/status=ok.*->.*maven_install\.json/)
} finally {
logSpy.mockRestore()
}
})
it('flags partial (never complete) when a probe is indeterminate but another hub succeeds', async () => {
// WORKSPACE mode so the conventional-name probe runs. `maven` succeeds and
// extracts; `maven_install` probe returns an unrecognized non-zero exit
// (indeterminate). The run must be partial, never complete, and carry the
// completeness signal.
vi.mocked(detectWorkspaceMode).mockReturnValue({
bzlmod: false,
workspace: true,
})
vi.mocked(buildMavenProbeFor).mockReturnValue(async (name: string) => {
if (name === 'maven') {
return { code: 0, stdout: '@maven//:foo\n', stderr: '' }
}
if (name === 'maven_install') {
// Unrecognized non-zero exit -> indeterminate.
return { code: 1, stdout: '', stderr: 'bazel internal error\n' }
}
return {
code: 1,
stdout: '',
stderr: "ERROR: No repository visible as '@x' from main repository\n",
}
})
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('partial')
expect(result.complete).toBe(false)
expect(result.manifestPaths).toHaveLength(1)
// The indeterminate hub is recorded in the completeness signal.
const hubStates = result.workspaceOutcomes.flatMap(w =>
w.hubs.map(h => h.state),
)
expect(hubStates).toContain('indeterminate')
})
it('hard-fails (never complete) when the only probe is indeterminate and nothing extracts', async () => {
vi.mocked(detectWorkspaceMode).mockReturnValue({
bzlmod: false,
workspace: true,
})
// Every conventional name probe returns an unrecognized non-zero exit.
vi.mocked(buildMavenProbeFor).mockReturnValue(async () => ({
code: 1,
stdout: '',
stderr: 'bazel internal error\n',
}))
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
// Nothing analyzable was produced, but a probe was indeterminate, so this
// is a hard failure, NOT noEcosystem (which would imply "no Maven here").
expect(result.status).toBe('hardFailure')
expect(result.complete).toBe(false)
})
it('skips emitting a hub manifest when a committed lockfile already covers it', async () => {
// A committed maven_install.json under the workspace means the server-side
// walker already ingests it; the CLI must NOT re-emit a synthetic copy.
writeFileSync(
path.join(tmp, 'maven_install.json'),
JSON.stringify({ artifacts: {}, dependencies: {} }),
'utf8',
)
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
// The hub was skipped, so no synthetic manifest and the cquery never runs.
expect(result.manifestPaths).toHaveLength(0)
expect(runMetadataCqueryForRepo).not.toHaveBeenCalled()
const skipped = result.workspaceOutcomes.flatMap(w =>
w.hubs.filter(h => h.state === 'skipped-lockfile').map(h => h.hub),
)
expect(skipped).toContain('maven')
})
it('extracts the root hub even when a nested dir holds a maven_install.json (no any-depth match)', async () => {
// The root @maven is UNCOVERED: there is no maven_install.json directly in
// the workspace root. A nested fixture/example holds its own
// maven_install.json, which covers ITS workspace, not the root hub. An
// any-depth gate would wrongly judge the root hub covered, skip its
// synthetic emit, and silently drop its distinct coordinates. The gate is
// depth-0, so the root hub must still be extracted.
const nested = path.join(tmp, 'examples', 'nested')
mkdirSync(nested, { recursive: true })
writeFileSync(
path.join(nested, 'maven_install.json'),
JSON.stringify({ artifacts: {}, dependencies: {} }),
'utf8',
)
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:rootonly:1.0', 'rootonly')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
// The root hub was NOT skipped: cquery ran and the synthetic manifest
// carrying the root's distinct coordinate was emitted.
expect(runMetadataCqueryForRepo).toHaveBeenCalledTimes(1)
expect(result.manifestPaths).toHaveLength(1)
const manifest = readManifest(tmp) as {
artifacts: Record<string, { version: string }>
}
expect(Object.keys(manifest.artifacts)).toEqual(['com.example:rootonly'])
const skipped = result.workspaceOutcomes.flatMap(w =>
w.hubs.filter(h => h.state === 'skipped-lockfile').map(h => h.hub),
)
expect(skipped).toEqual([])
})
it('reports complete:true with zero synthetic manifests when every hub is covered by a committed root-level lockfile', async () => {
// A committed maven_install.json sits directly in the workspace root, so
// the only discovered hub is covered. The CLI writes zero synthetic
// manifests and the run must headline complete:true.
writeFileSync(
path.join(tmp, 'maven_install.json'),
JSON.stringify({ artifacts: {}, dependencies: {} }),
'utf8',
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(result.status).toBe('complete')
expect(result.complete).toBe(true)
expect(result.manifestPaths).toHaveLength(0)
expect(runMetadataCqueryForRepo).not.toHaveBeenCalled()
// The emitted completeness summary also headlines complete:true.
const summary = JSON.parse(
readFileSync(
path.join(
tmp,
'.socket-auto-manifest',
'socket-bazel-manifest-summary.json',
),
'utf8',
),
) as { complete: boolean; status: string }
expect(summary.complete).toBe(true)
expect(summary.status).toBe('complete')
})
it('does not treat a prior-run synthetic manifest in the output dir as a committed lockfile', async () => {
// A previous run left a synthetic maven_install.json inside the output dir
// (.socket-auto-manifest). A later run must NOT read it as a committed
// lockfile and skip the hub; it must re-extract.
const outputDir = path.join(tmp, '.socket-auto-manifest')
mkdirSync(outputDir, { recursive: true })
writeFileSync(
path.join(outputDir, 'maven_install.json'),
JSON.stringify({ artifacts: {}, dependencies: {} }),
'utf8',
)
vi.mocked(runMetadataCqueryForRepo).mockResolvedValueOnce(
mkResult({
artifacts: [mkArt('com.example:a:1.0', 'a')],
repoName: 'maven',
}),
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
// The stale synthetic file did not gate the hub: cquery ran and a manifest
// was emitted.
expect(runMetadataCqueryForRepo).toHaveBeenCalledTimes(1)
expect(result.manifestPaths).toHaveLength(1)
const skipped = result.workspaceOutcomes.flatMap(w =>
w.hubs.filter(h => h.state === 'skipped-lockfile').map(h => h.hub),
)
expect(skipped).toEqual([])
})
it('maps a hub named maven to maven_install.json for the committed-lockfile gate', async () => {
// The default `maven` hub is covered by a committed `maven_install.json`.
writeFileSync(
path.join(tmp, 'maven_install.json'),
JSON.stringify({ artifacts: {}, dependencies: {} }),
'utf8',
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(runMetadataCqueryForRepo).not.toHaveBeenCalled()
const skipped = result.workspaceOutcomes.flatMap(w =>
w.hubs.filter(h => h.state === 'skipped-lockfile').map(h => h.hub),
)
expect(skipped).toContain('maven')
})
it('maps a non-default hub to <hub>_maven_install.json for the committed-lockfile gate', async () => {
// A non-default hub `maven_dev` is covered only by a committed file named
// `maven_dev_maven_install.json`. A bare `maven_install.json` must NOT
// cover it, and the prefixed file must.
vi.mocked(runBazelModShowMavenExtension).mockResolvedValue({
code: 0,
stdout: `## @@rules_jvm_external+//:extensions.bzl%maven:
Fetched repositories:
- maven_dev (imported by <root>)
`,
stderr: '',
})
writeFileSync(
path.join(tmp, 'maven_dev_maven_install.json'),
JSON.stringify({ artifacts: {}, dependencies: {} }),
'utf8',
)
const result = await extractBazelToMaven({
bazelFlags: undefined,
bazelOutputBase: undefined,
bazelRc: undefined,
bin: undefined,
cwd: tmp,
out: tmp,
outLayout: 'flat',
verbose: false,
})
expect(runMetadataCqueryForRepo).not.toHaveBeenCalled()
const skipped = result.workspaceOutcomes.flatMap(w =>
w.hubs.filter(h => h.state === 'skipped-lockfile').map(h => h.hub),
)
expect(skipped).toContain('maven_dev')
})
it('flags partial (never complete) when show_extension fails to evaluate the module graph but a probed hub extracts', async () => {
// show_extension hit a genuine module-graph EVALUATION failure (not merely
// "rules_jvm_external isn't a dependency"): authoritative hub enumeration
// is indeterminate, so custom-named hubs may have been missed. The
// conventional probe still finds @maven and extracts it, but the run must
// be partial — never silently complete.
// NOTE: exact bazel stderr wording for an eval failure should be confirmed
// against a live bazel run (sandbox blocks bazel here).
vi.mocked(runBazelModShowMavenExtension).mockResolvedValue({
code: 1,
stdout: '',
stderr: