@infly/libs 2.4.2 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +469 -459
- package/bin/cli.js +7 -4
- package/build/before-build.js +50 -0
- package/build/docker/docker-build-push.js +8 -3
- package/build/docker/minimal-context.js +32 -1
- package/build/docker/project-install.js +163 -0
- package/build/docker/release-identity.js +22 -0
- package/build/docker/source-snapshot.js +44 -0
- package/build/docker/target-release.js +860 -739
- package/package.json +1 -1
- package/script/git-automation/index.js +828 -858
- package/script/git-automation/root-update.js +31 -0
|
@@ -1,739 +1,860 @@
|
|
|
1
|
-
const fs = require("node:fs");
|
|
2
|
-
const os = require("node:os");
|
|
3
|
-
const path = require("node:path");
|
|
4
|
-
const { execFileSync } = require("node:child_process");
|
|
5
|
-
const { EXIT_SELECTION, inputText, selectOption, selectOptions } = require("../../cli/select-option");
|
|
6
|
-
const { composeRelease } = require("./compose-release");
|
|
7
|
-
const { formatCicdLink, healthCheckImage } = require("./docker-build-push");
|
|
8
|
-
const { loadDockerConfig } = require("./config-loader");
|
|
9
|
-
const { detectReleaseContext, detectReleaseMode } = require("./release-mode");
|
|
10
|
-
const { prepareMinimalMonorepoContext } = require("./minimal-context");
|
|
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
|
-
if (
|
|
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
|
-
const
|
|
134
|
-
const
|
|
135
|
-
const
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
if (profile.
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
throw new Error(`${target}
|
|
165
|
-
}
|
|
166
|
-
if (profile.
|
|
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
|
-
if (
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
const
|
|
247
|
-
const
|
|
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
|
-
if (component.repository
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
}
|
|
284
|
-
if (component.source) {
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
if (
|
|
290
|
-
throw new Error(`${name} source
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
destinations.
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
if (component.
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
throw new Error(`${name}
|
|
325
|
-
}
|
|
326
|
-
if (component.
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
throw new Error(`${name}
|
|
332
|
-
}
|
|
333
|
-
if (component.buildStrategy
|
|
334
|
-
throw new Error(`${name}
|
|
335
|
-
}
|
|
336
|
-
if (component.
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
}
|
|
357
|
-
if (component.
|
|
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
|
-
const
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
const
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
const
|
|
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
|
-
const
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
const
|
|
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
|
-
item.
|
|
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
|
-
const
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
:
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
1
|
+
const fs = require("node:fs");
|
|
2
|
+
const os = require("node:os");
|
|
3
|
+
const path = require("node:path");
|
|
4
|
+
const { execFileSync } = require("node:child_process");
|
|
5
|
+
const { EXIT_SELECTION, inputText, selectOption, selectOptions } = require("../../cli/select-option");
|
|
6
|
+
const { composeRelease } = require("./compose-release");
|
|
7
|
+
const { formatCicdLink, healthCheckImage } = require("./docker-build-push");
|
|
8
|
+
const { loadDockerConfig } = require("./config-loader");
|
|
9
|
+
const { detectReleaseContext, detectReleaseMode } = require("./release-mode");
|
|
10
|
+
const { prepareMinimalMonorepoContext, normalizeMonorepoContextFiles } = require("./minimal-context");
|
|
11
|
+
const { prepareProjectInstallContext, prepareStandaloneInstallContext } = require("./project-install");
|
|
12
|
+
const { prepareWorkspaceSnapshot, verifyWorkspaceRemote } = require("./source-snapshot");
|
|
13
|
+
const { createReleaseId, createBuildProvenance, readRegistryDigest } = require("./release-identity");
|
|
14
|
+
|
|
15
|
+
// Jenkins 构建页“镜像版本”与 Webhook 通知均按北京时间展示。
|
|
16
|
+
function beijingDateTime(now = new Date()) {
|
|
17
|
+
const parts = new Intl.DateTimeFormat("en-CA", {
|
|
18
|
+
timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit",
|
|
19
|
+
hour: "2-digit", minute: "2-digit", hourCycle: "h23",
|
|
20
|
+
}).formatToParts(now);
|
|
21
|
+
const values = Object.fromEntries(parts.filter((part) => part.type !== "literal").map((part) => [part.type, part.value]));
|
|
22
|
+
return `${values.year}-${values.month}-${values.day} ${values.hour}:${values.minute}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function checkDocker(run, projectDir, buildx = true, dependencies = {}, autoStart = true) {
|
|
26
|
+
const quiet = { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
|
|
27
|
+
try {
|
|
28
|
+
run("docker", ["info"], quiet);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
const detail = String(error.stderr || error.message || "").trim();
|
|
31
|
+
const env = dependencies.env || process.env;
|
|
32
|
+
const platform = dependencies.platform || process.platform;
|
|
33
|
+
if (autoStart && platform === "win32" && !env.CI && !env.JENKINS_URL && !env.DOCKER_HOST
|
|
34
|
+
&& /dockerDesktopLinuxEngine/i.test(detail)) {
|
|
35
|
+
// 只针对明确的本机 Desktop 管道启动软件,不切换 context,也不处理远端服务。
|
|
36
|
+
const log = dependencies.log || console.log;
|
|
37
|
+
log("Docker Desktop Linux 引擎未就绪,正在启动本机 Docker Desktop…");
|
|
38
|
+
run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
|
|
39
|
+
"Start-Process -FilePath 'C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe' -WindowStyle Hidden"], quiet);
|
|
40
|
+
const sleep = dependencies.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
41
|
+
for (let attempt = 0; attempt < 60; attempt++) {
|
|
42
|
+
await sleep(2000);
|
|
43
|
+
try { run("docker", ["info"], quiet); }
|
|
44
|
+
catch {
|
|
45
|
+
if (attempt % 10 === 9) log(`等待 Docker Linux 引擎就绪…${(attempt + 1) * 2}s`);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
log("Docker 引擎已就绪,继续构建。");
|
|
49
|
+
return checkDocker(run, projectDir, buildx, dependencies, false);
|
|
50
|
+
}
|
|
51
|
+
throw new Error("Docker Desktop 启动后 120 秒内 Linux 引擎仍未就绪,请检查 Docker Desktop 的启动错误后重试。", { cause: error });
|
|
52
|
+
}
|
|
53
|
+
const hint = error.code === "ENOENT"
|
|
54
|
+
? "未找到 Docker CLI,请安装 Docker 并确认 docker 位于 PATH。"
|
|
55
|
+
: /dockerDesktopLinuxEngine/i.test(detail)
|
|
56
|
+
? "无法连接 Docker Desktop Linux 引擎。请打开 Docker Desktop,等待 Linux 引擎启动,再运行 docker info 确认 Server 可访问。"
|
|
57
|
+
: "无法连接 Docker 引擎。请检查 docker context show、DOCKER_HOST 和 Docker 服务状态,再运行 docker info。";
|
|
58
|
+
throw new Error(`${hint}\n${detail}`, { cause: error });
|
|
59
|
+
}
|
|
60
|
+
if (buildx) {
|
|
61
|
+
try { run("docker", ["buildx", "version"], quiet); }
|
|
62
|
+
catch (error) { throw new Error("Docker 引擎已连接,但 Buildx 不可用。请检查 docker buildx version。", { cause: error }); }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function parseReleaseArgs(argv) {
|
|
67
|
+
const options = { push: false };
|
|
68
|
+
const keys = { "--target": "target", "--platform": "target", "--components": "components",
|
|
69
|
+
"--project-dir": "projectDir", "--backend-dir": "backendDir", "--config": "config", "--output": "output",
|
|
70
|
+
"--cicd-url": "cicdUrl" };
|
|
71
|
+
for (let i = 0; i < argv.length; i++) {
|
|
72
|
+
const [flag, ...suffix] = argv[i].split("=");
|
|
73
|
+
if (flag === "--") continue;
|
|
74
|
+
if (["--push", "--no-push", "--dry-run"].includes(flag) && suffix.length === 0) {
|
|
75
|
+
if (flag === "--dry-run") options.dryRun = true;
|
|
76
|
+
else options.push = flag === "--push";
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (!keys[flag]) throw new Error(`不支持的参数: ${argv[i]}`);
|
|
80
|
+
const value = suffix.length ? suffix.join("=") : argv[++i];
|
|
81
|
+
if (!value || value.startsWith("--")) throw new Error(`${flag} 缺少参数值`);
|
|
82
|
+
options[keys[flag]] = flag === "--components" ? value.split(",") : value;
|
|
83
|
+
}
|
|
84
|
+
return options;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function inside(root, relative) {
|
|
88
|
+
if (typeof relative !== "string" || !relative || path.isAbsolute(relative)) throw new Error(`必须配置相对路径: ${relative}`);
|
|
89
|
+
const result = path.resolve(root, relative);
|
|
90
|
+
const offset = path.relative(root, result);
|
|
91
|
+
if (offset === ".." || offset.startsWith(`..${path.sep}`)) throw new Error(`路径越界: ${relative}`);
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function confinedPath(root, relative, io = fs) {
|
|
96
|
+
const candidate = inside(root, relative);
|
|
97
|
+
let existing = candidate;
|
|
98
|
+
while (existing !== root && !io.existsSync(existing)) {
|
|
99
|
+
if (io.lstatSync) {
|
|
100
|
+
try {
|
|
101
|
+
if (io.lstatSync(existing).isSymbolicLink()) throw new Error(`无法解析链接路径: ${relative}`);
|
|
102
|
+
} catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
103
|
+
}
|
|
104
|
+
existing = path.dirname(existing);
|
|
105
|
+
}
|
|
106
|
+
if (io.realpathSync && io.existsSync(existing)) {
|
|
107
|
+
const offset = path.relative(io.realpathSync(root), io.realpathSync(existing));
|
|
108
|
+
if (offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw new Error(`链接路径越界: ${relative}`);
|
|
109
|
+
}
|
|
110
|
+
return candidate;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function normalizeSourceDirectories(value, name) {
|
|
114
|
+
const directories = Array.isArray(value) ? value : [value];
|
|
115
|
+
if (!directories.length || directories.some((item) => typeof item !== "string" || !item.trim())) {
|
|
116
|
+
throw new Error(`${name} source.directory 必须是非空路径字符串或非空路径数组`);
|
|
117
|
+
}
|
|
118
|
+
return [...new Set(directories.map((item) => item.trim()))];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function resolveSourceDirectories(projectDir, value, name) {
|
|
122
|
+
return normalizeSourceDirectories(value, name).map((directory) => path.resolve(projectDir, directory));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function trimPathInput(value) {
|
|
126
|
+
const trimmed = String(value || "").trim();
|
|
127
|
+
return trimmed.length >= 2 && ((trimmed.startsWith('"') && trimmed.endsWith('"'))
|
|
128
|
+
|| (trimmed.startsWith("'") && trimmed.endsWith("'")))
|
|
129
|
+
? trimmed.slice(1, -1).trim()
|
|
130
|
+
: trimmed;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const SAFE_GIT_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
|
|
134
|
+
const SAFE_DOCKER_PLATFORM = /^[a-z0-9]+\/[a-z0-9]+(?:\/[a-z0-9._-]+)?$/;
|
|
135
|
+
const SAFE_VERSION_REQUIREMENT = /^>=(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
|
|
136
|
+
const WINDOWS_PACKAGE_MANAGERS = new Set(["npm", "npx", "pnpm", "yarn"]);
|
|
137
|
+
const UNSAFE_WINDOWS_SHELL_TOKEN = /[\r\n\0&|<>^%!"]/;
|
|
138
|
+
const PRE_BUILD_MODES = new Set(["always", "monorepo", "standalone"]);
|
|
139
|
+
const BUILD_STRATEGIES = new Set(["artifact", "source"]);
|
|
140
|
+
|
|
141
|
+
function normalizePreBuildCommand(value, target) {
|
|
142
|
+
const entry = Array.isArray(value) ? { command: value, when: "always" } : value;
|
|
143
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)
|
|
144
|
+
|| !Array.isArray(entry.command) || entry.command.length === 0
|
|
145
|
+
|| entry.command.some((arg) => typeof arg !== "string" || !arg || /[\r\n\0]/.test(arg))
|
|
146
|
+
|| (entry.when != null && !PRE_BUILD_MODES.has(entry.when))) {
|
|
147
|
+
throw new Error(`${target} preBuild 必须是命令参数数组,或包含 command 与合法 when 的对象`);
|
|
148
|
+
}
|
|
149
|
+
return { command: entry.command, when: entry.when || "always" };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function validateReleaseProfile(profile, target) {
|
|
153
|
+
if (profile.recordConfigurationRevision != null && typeof profile.recordConfigurationRevision !== "boolean") {
|
|
154
|
+
throw new Error(`${target} recordConfigurationRevision 必须是布尔值`);
|
|
155
|
+
}
|
|
156
|
+
if (profile.pushBranch != null && (typeof profile.pushBranch !== "string"
|
|
157
|
+
|| !SAFE_GIT_NAME.test(profile.pushBranch) || profile.pushBranch.startsWith("-")
|
|
158
|
+
|| profile.pushBranch.includes(".."))) {
|
|
159
|
+
throw new Error(`${target} pushBranch 必须是合法 Git 分支名`);
|
|
160
|
+
}
|
|
161
|
+
if (profile.pushRef != null && (typeof profile.pushRef !== "string"
|
|
162
|
+
|| !SAFE_GIT_NAME.test(profile.pushRef) || profile.pushRef.startsWith("-")
|
|
163
|
+
|| profile.pushRef.includes("..") || !profile.pushRef.includes("/"))) {
|
|
164
|
+
throw new Error(`${target} pushRef 必须使用 remote/branch 格式`);
|
|
165
|
+
}
|
|
166
|
+
if ((profile.pushBranch == null) !== (profile.pushRef == null)) {
|
|
167
|
+
throw new Error(`${target} pushBranch 和 pushRef 必须同时配置`);
|
|
168
|
+
}
|
|
169
|
+
if (profile.requirements != null) {
|
|
170
|
+
if (!profile.requirements || typeof profile.requirements !== "object"
|
|
171
|
+
|| Array.isArray(profile.requirements)) throw new Error(`${target} requirements 必须是对象`);
|
|
172
|
+
for (const [tool, requirement] of Object.entries(profile.requirements)) {
|
|
173
|
+
if (!["node", "pnpm"].includes(tool) || typeof requirement !== "string"
|
|
174
|
+
|| !SAFE_VERSION_REQUIREMENT.test(requirement)) {
|
|
175
|
+
throw new Error(`${target} requirements 只支持 node/pnpm 的 >=x.y.z 版本约束`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (profile.preBuild != null && (!Array.isArray(profile.preBuild) || profile.preBuild.length === 0)) {
|
|
180
|
+
throw new Error(`${target} preBuild 必须是非空列表`);
|
|
181
|
+
}
|
|
182
|
+
for (const command of profile.preBuild || []) normalizePreBuildCommand(command, target);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function compareVersions(actual, required) {
|
|
186
|
+
const actualMatch = String(actual).trim().replace(/^v/, "").match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
|
|
187
|
+
const requiredMatch = String(required).match(SAFE_VERSION_REQUIREMENT);
|
|
188
|
+
if (!actualMatch || !requiredMatch) return false;
|
|
189
|
+
for (let index = 1; index <= 3; index++) {
|
|
190
|
+
const left = Number(actualMatch[index] || 0);
|
|
191
|
+
const right = Number(requiredMatch[index] || 0);
|
|
192
|
+
if (left !== right) return left > right;
|
|
193
|
+
}
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function windowsExecutable(command, platform = process.platform) {
|
|
198
|
+
return platform === "win32" && WINDOWS_PACKAGE_MANAGERS.has(command)
|
|
199
|
+
? `${command}.cmd`
|
|
200
|
+
: command;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function quoteWindowsShellToken(value) {
|
|
204
|
+
const token = String(value);
|
|
205
|
+
if (UNSAFE_WINDOWS_SHELL_TOKEN.test(token)) {
|
|
206
|
+
throw new Error(`Windows 包管理器参数包含不安全字符: ${token}`);
|
|
207
|
+
}
|
|
208
|
+
return /[\s()]/.test(token) ? `"${token}"` : token;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function buildExecutableSpawn(command, args, {
|
|
212
|
+
platform = process.platform,
|
|
213
|
+
env = process.env,
|
|
214
|
+
} = {}) {
|
|
215
|
+
if (platform !== "win32" || !WINDOWS_PACKAGE_MANAGERS.has(command)) {
|
|
216
|
+
return { command, args };
|
|
217
|
+
}
|
|
218
|
+
const shellCommand = [command, ...args].map(quoteWindowsShellToken).join(" ");
|
|
219
|
+
return {
|
|
220
|
+
command: env.ComSpec || "cmd.exe",
|
|
221
|
+
args: ["/d", "/s", "/c", shellCommand],
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function runReleasePreparation(profile, {
|
|
226
|
+
run,
|
|
227
|
+
capture,
|
|
228
|
+
projectDir,
|
|
229
|
+
push,
|
|
230
|
+
platform = process.platform,
|
|
231
|
+
env = process.env,
|
|
232
|
+
releaseMode = detectReleaseMode(projectDir),
|
|
233
|
+
log = console.log,
|
|
234
|
+
}) {
|
|
235
|
+
validateReleaseProfile(profile, profile.label || "Docker target");
|
|
236
|
+
const git = (...args) => capture("git", ["-C", projectDir, ...args]);
|
|
237
|
+
if (git("status", "--porcelain", "--untracked-files=all")) {
|
|
238
|
+
throw new Error("当前项目存在未提交改动,不能构建发布镜像");
|
|
239
|
+
}
|
|
240
|
+
if (push && profile.pushBranch) {
|
|
241
|
+
const branch = git("branch", "--show-current");
|
|
242
|
+
if (branch !== profile.pushBranch) {
|
|
243
|
+
throw new Error(`镜像只允许从 ${profile.pushBranch} 推送;当前分支: ${branch || "detached HEAD"}`);
|
|
244
|
+
}
|
|
245
|
+
const slash = profile.pushRef.indexOf("/");
|
|
246
|
+
const remote = profile.pushRef.slice(0, slash);
|
|
247
|
+
const remoteBranch = profile.pushRef.slice(slash + 1);
|
|
248
|
+
run("git", ["-C", projectDir, "fetch", remote, remoteBranch], { cwd: projectDir });
|
|
249
|
+
const commit = git("rev-parse", "HEAD").toLowerCase();
|
|
250
|
+
const remoteCommit = git("rev-parse", `${profile.pushRef}^{commit}`).toLowerCase();
|
|
251
|
+
if (commit !== remoteCommit) {
|
|
252
|
+
throw new Error(`${profile.pushBranch} 必须已推送并与 ${profile.pushRef} 同步`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
for (const [tool, requirement] of Object.entries(profile.requirements || {})) {
|
|
256
|
+
const args = tool === "node" ? ["--version"] : ["--version"];
|
|
257
|
+
const invocation = buildExecutableSpawn(tool, args, { platform, env });
|
|
258
|
+
const actual = capture(invocation.command, invocation.args);
|
|
259
|
+
if (!compareVersions(actual, requirement)) {
|
|
260
|
+
throw new Error(`${tool} 必须满足 ${requirement},当前版本: ${actual || "无法识别"}`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
for (const rawCommand of profile.preBuild || []) {
|
|
264
|
+
const { command: commandArgs, when } = normalizePreBuildCommand(
|
|
265
|
+
rawCommand,
|
|
266
|
+
profile.label || "Docker target",
|
|
267
|
+
);
|
|
268
|
+
const [command, ...args] = commandArgs;
|
|
269
|
+
if (when !== "always" && when !== releaseMode) {
|
|
270
|
+
log(`跳过发布准备(当前 ${releaseMode} 模式,仅 ${when} 执行): ${commandArgs.join(" ")}`);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
log(`执行发布准备: ${command} ${args.join(" ")}`);
|
|
274
|
+
const invocation = buildExecutableSpawn(command, args, { platform, env });
|
|
275
|
+
run(invocation.command, invocation.args, { cwd: projectDir });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function validateComponent(component, name, guardedByProfile = false) {
|
|
280
|
+
if (!component || !/^[a-z0-9][a-z0-9._:/-]*$/.test(component.repository || "") || component.repository.includes("@")) {
|
|
281
|
+
throw new Error(`${name} 必须配置有效的镜像 repository(不含标签)`);
|
|
282
|
+
}
|
|
283
|
+
if (component.repository.split("/").at(-1).includes(":")) throw new Error(`${name} repository 不得包含标签`);
|
|
284
|
+
if (!component.expectedRef && !component.source?.branch && !guardedByProfile) {
|
|
285
|
+
throw new Error(`${name} 必须配置 expectedRef、source.branch 或 target pushRef`);
|
|
286
|
+
}
|
|
287
|
+
if (component.source) {
|
|
288
|
+
normalizeSourceDirectories(component.source.directory, name);
|
|
289
|
+
if (component.source.standalone != null && typeof component.source.standalone !== "boolean") {
|
|
290
|
+
throw new Error(`${name} source.standalone 必须是布尔值`);
|
|
291
|
+
}
|
|
292
|
+
if (!component.source.branch || component.source.branch.startsWith("-")) {
|
|
293
|
+
throw new Error(`${name} source 必须配置合法 branch`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
inside("/config", component.dockerfile || "Dockerfile");
|
|
297
|
+
if (component.dockerfileFromConfig != null) {
|
|
298
|
+
inside("/config", component.dockerfileFromConfig);
|
|
299
|
+
if (!component.source || component.buildStrategy !== "source" || component.dockerfile != null) {
|
|
300
|
+
throw new Error(`${name} dockerfileFromConfig 只支持外部源码构建,不能同时配置 dockerfile`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (component.contextFiles != null) {
|
|
304
|
+
if (!component.source || component.buildStrategy !== "source" || !Array.isArray(component.contextFiles)
|
|
305
|
+
|| !component.contextFiles.length) throw new Error(`${name} contextFiles 只支持外部源码构建的非空列表`);
|
|
306
|
+
const destinations = new Set();
|
|
307
|
+
for (const entry of component.contextFiles) {
|
|
308
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)
|
|
309
|
+
|| Object.keys(entry).some((key) => !["from", "to"].includes(key))) throw new Error(`${name} contextFiles 仅支持 from/to`);
|
|
310
|
+
inside("/config", entry.from); inside("/config", entry.to);
|
|
311
|
+
const destination = path.normalize(entry.to);
|
|
312
|
+
if (destination === "." || destination.split(path.sep).includes(".git") || destinations.has(destination)) {
|
|
313
|
+
throw new Error(`${name} contextFiles 目标不能为根、Git 元数据或重复路径`);
|
|
314
|
+
}
|
|
315
|
+
destinations.add(destination);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
inside("/config", component.context || ".");
|
|
319
|
+
if (component.target != null && (typeof component.target !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(component.target))) {
|
|
320
|
+
throw new Error(`${name} target 必须是合法 Docker stage`);
|
|
321
|
+
}
|
|
322
|
+
if (component.platform != null && (typeof component.platform !== "string"
|
|
323
|
+
|| !SAFE_DOCKER_PLATFORM.test(component.platform))) {
|
|
324
|
+
throw new Error(`${name} platform 必须是 linux/amd64 等合法 Docker 平台`);
|
|
325
|
+
}
|
|
326
|
+
if (component.mutableTags != null && typeof component.mutableTags !== "boolean") {
|
|
327
|
+
throw new Error(`${name} mutableTags 必须是布尔值`);
|
|
328
|
+
}
|
|
329
|
+
if (component.tagPrefix != null && (typeof component.tagPrefix !== "string"
|
|
330
|
+
|| !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,87}$/.test(component.tagPrefix))) {
|
|
331
|
+
throw new Error(`${name} tagPrefix 必须是 1 到 88 位合法 Docker 标签前缀`);
|
|
332
|
+
}
|
|
333
|
+
if (component.buildStrategy != null && !BUILD_STRATEGIES.has(component.buildStrategy)) {
|
|
334
|
+
throw new Error(`${name} buildStrategy 只支持 artifact 或 source`);
|
|
335
|
+
}
|
|
336
|
+
if (component.buildStrategy === "source" && component.files != null) {
|
|
337
|
+
throw new Error(`${name} source 构建不能同时配置 files 产物上下文`);
|
|
338
|
+
}
|
|
339
|
+
if (component.monorepoContextFiles != null) {
|
|
340
|
+
if (component.buildStrategy !== "source") throw new Error(`${name} monorepoContextFiles 仅用于 source 构建`);
|
|
341
|
+
normalizeMonorepoContextFiles(component.monorepoContextFiles);
|
|
342
|
+
}
|
|
343
|
+
if (component.projectInstall != null) {
|
|
344
|
+
if (typeof component.projectInstall !== "boolean" || !component.source || component.buildStrategy !== "source" || component.monorepoContextFiles != null) {
|
|
345
|
+
throw new Error(`${name} projectInstall 必须是布尔值,只用于外部源码构建,不能与 monorepoContextFiles 同时配置`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (component.releaseIdentity != null && (typeof component.releaseIdentity !== "boolean"
|
|
349
|
+
|| component.buildStrategy !== "source" || !component.source)) {
|
|
350
|
+
throw new Error(`${name} releaseIdentity 仅支持外部 source 构建的布尔值`);
|
|
351
|
+
}
|
|
352
|
+
if (component.workspaceRef != null && (typeof component.workspaceRef !== "string"
|
|
353
|
+
|| !SAFE_GIT_NAME.test(component.workspaceRef) || !component.workspaceRef.includes("/") || component.workspaceRef.includes(".."))) {
|
|
354
|
+
throw new Error(`${name} workspaceRef 必须使用 remote/branch`);
|
|
355
|
+
}
|
|
356
|
+
if (component.releaseIdentity && (component.tagPrefix || "").length > 74) throw new Error(`${name} 唯一发布标签的前缀过长`);
|
|
357
|
+
if (component.releaseIdentity && !component.platform) throw new Error(`${name} 唯一发布必须明确声明 platform`);
|
|
358
|
+
if (component.releaseChannel != null && (typeof component.releaseChannel !== "boolean" || !component.releaseIdentity)) {
|
|
359
|
+
throw new Error(`${name} releaseChannel 仅支持启用 releaseIdentity 的布尔值`);
|
|
360
|
+
}
|
|
361
|
+
if (component.buildArgs != null && (!component.buildArgs || typeof component.buildArgs !== "object"
|
|
362
|
+
|| Array.isArray(component.buildArgs) || Object.entries(component.buildArgs).some(([key, value]) =>
|
|
363
|
+
!/^[A-Z_][A-Z0-9_]*$/.test(key) || !["string", "number", "boolean"].includes(typeof value)))) {
|
|
364
|
+
throw new Error(`${name} buildArgs 必须是合法构建参数对象`);
|
|
365
|
+
}
|
|
366
|
+
if (component.requiredFiles) {
|
|
367
|
+
if (!Array.isArray(component.requiredFiles)) throw new Error(`${name} requiredFiles 必须是数组`);
|
|
368
|
+
for (const file of component.requiredFiles) inside("/config", file);
|
|
369
|
+
}
|
|
370
|
+
if (component.files) {
|
|
371
|
+
if (!Array.isArray(component.files) || component.files.length === 0) throw new Error(`${name} files 必须是非空数组`);
|
|
372
|
+
for (const file of component.files) { inside("/config", file.from); inside("/config", file.to); }
|
|
373
|
+
}
|
|
374
|
+
if (component.check) {
|
|
375
|
+
const { entrypoint, args, addHosts = [] } = component.check;
|
|
376
|
+
if (typeof entrypoint !== "string" || !entrypoint || !Array.isArray(args)
|
|
377
|
+
|| !args.every((arg) => typeof arg === "string") || !Array.isArray(addHosts)
|
|
378
|
+
|| !addHosts.every((host) => typeof host === "string" && host.includes(":"))) {
|
|
379
|
+
throw new Error(`${name} check 必须配置 entrypoint、args 数组及可选 addHosts 数组`);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (component.health != null) {
|
|
383
|
+
const health = component.health;
|
|
384
|
+
if (!health || typeof health !== "object" || Array.isArray(health)
|
|
385
|
+
|| Object.keys(health).some((key) => !["timeoutSeconds", "addHost"].includes(key))
|
|
386
|
+
|| !Number.isInteger(health.timeoutSeconds) || health.timeoutSeconds < 1 || health.timeoutSeconds > 600
|
|
387
|
+
|| (health.addHost != null && (typeof health.addHost !== "string"
|
|
388
|
+
|| !/^[A-Za-z0-9][A-Za-z0-9._-]*:(?:[A-Fa-f0-9:.]+|host-gateway)$/.test(health.addHost)))) {
|
|
389
|
+
throw new Error(`${name} health 必须声明 1 到 600 秒的 timeoutSeconds 及可选 addHost`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function execute(command, args, options = {}) {
|
|
395
|
+
return execFileSync(command, args, { stdio: "inherit", ...options });
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
async function runTargetRelease(options = {}, dependencies = {}) {
|
|
399
|
+
const projectDir = path.resolve(options.projectDir || process.cwd());
|
|
400
|
+
const config = loadDockerConfig({ projectDir, configPath: options.config,
|
|
401
|
+
configObject: options.configObject, configDir: options.configDir });
|
|
402
|
+
const targets = config?.targets;
|
|
403
|
+
if (!targets || !Object.keys(targets).length) throw new Error("请配置 infly.docker.targets");
|
|
404
|
+
const releaseScripts = config?.releaseScripts || {};
|
|
405
|
+
const releaseContext = detectReleaseContext({ projectDir });
|
|
406
|
+
const log = dependencies.log || console.log;
|
|
407
|
+
const cicdLink = formatCicdLink(options.cicdUrl);
|
|
408
|
+
const target = options.target || await (dependencies.selectOption || selectOption)("请选择构建平台",
|
|
409
|
+
Object.entries(targets).map(([value, item]) => ({ value, label: item.label || value })));
|
|
410
|
+
if (target === EXIT_SELECTION) return { cancelled: true };
|
|
411
|
+
const profile = targets[target];
|
|
412
|
+
if (profile && !profile.components && profile.file) {
|
|
413
|
+
// 旧目标只有 Compose 文件,保留既有镜像/版本语义,不把前端目标静默升级为前后端生产发布。
|
|
414
|
+
const components = options.components || await (dependencies.selectOptions || selectOptions)("请选择构建范围",
|
|
415
|
+
[{ value: "frontend", label: "前端(Compose)" }]);
|
|
416
|
+
if (components === EXIT_SELECTION) return { cancelled: true };
|
|
417
|
+
if (!Array.isArray(components) || components.length !== 1 || components[0] !== "frontend") {
|
|
418
|
+
throw new Error(`平台 ${target} 只配置了 Compose 前端构建,不支持后端`);
|
|
419
|
+
}
|
|
420
|
+
log(`平台 ${profile.label || target} 使用 Compose 配置中的镜像标签,不自动升级版本;不生成 qc 镜像。`);
|
|
421
|
+
if (!options.dryRun) await checkDocker(dependencies.run || execute, projectDir, false, dependencies);
|
|
422
|
+
return (dependencies.composeRelease || composeRelease)({ projectDir, file: profile.file,
|
|
423
|
+
bump: "none", push: Boolean(options.push), dryRun: Boolean(options.dryRun) });
|
|
424
|
+
}
|
|
425
|
+
if (!profile?.components) throw new Error(`平台 ${target} 未配置 components`);
|
|
426
|
+
validateReleaseProfile(profile, target);
|
|
427
|
+
const components = options.components || await (dependencies.selectOptions || selectOptions)("请选择构建范围",
|
|
428
|
+
Object.entries(profile.components).map(([value, item]) => ({ value, label: item.label || value })));
|
|
429
|
+
if (components === EXIT_SELECTION) return { cancelled: true };
|
|
430
|
+
if (!Array.isArray(components) || !components.length || new Set(components).size !== components.length) {
|
|
431
|
+
throw new Error("请至少选择一个构建范围,且不能重复");
|
|
432
|
+
}
|
|
433
|
+
const io = dependencies.fs || fs;
|
|
434
|
+
const plan = components.map((name) => {
|
|
435
|
+
if (!Object.hasOwn(profile.components, name)) throw new Error(`不支持的构建范围: ${name}`);
|
|
436
|
+
const component = profile.components[name];
|
|
437
|
+
validateComponent(component, name, Boolean(profile.pushRef));
|
|
438
|
+
if (component.releaseChannel && !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(`${component.tagPrefix || ""}${target}-latest`)) {
|
|
439
|
+
throw new Error("环境最新镜像标签无效");
|
|
440
|
+
}
|
|
441
|
+
if (!component.source) return { name, ...component };
|
|
442
|
+
const configuredDirectory = name === "backend" && options.backendDir ? options.backendDir : component.source.directory;
|
|
443
|
+
const directoryCandidates = resolveSourceDirectories(projectDir, configuredDirectory, name);
|
|
444
|
+
return { name, ...component, source: { ...component.source,
|
|
445
|
+
directory: directoryCandidates[0], directoryCandidates } };
|
|
446
|
+
});
|
|
447
|
+
// dry-run 只解析配置,不联网、不调用 Git/Docker、不创建临时目录。
|
|
448
|
+
if (options.dryRun) { log(JSON.stringify({ target, push: Boolean(options.push), plan }, null, 2)); return { target, plan }; }
|
|
449
|
+
// 全部组件先预检,数组按顺序采用第一个 Git 仓;交互终端允许补录机器本地路径。
|
|
450
|
+
const stdin = dependencies.stdin || process.stdin;
|
|
451
|
+
const stdout = dependencies.stdout || process.stdout;
|
|
452
|
+
const interactive = dependencies.interactive ?? Boolean(stdin.isTTY && stdout.isTTY);
|
|
453
|
+
for (const item of plan.filter((candidate) => candidate.source)) {
|
|
454
|
+
const matched = item.source.directoryCandidates.find((directory) => io.existsSync(path.join(directory, ".git")));
|
|
455
|
+
if (matched) {
|
|
456
|
+
item.source.directory = matched;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (!interactive) continue;
|
|
460
|
+
log(`未在 ${item.name} 源码候选路径中找到 Git 仓库:`);
|
|
461
|
+
item.source.directoryCandidates.forEach((directory, index) => log(` ${index + 1}. ${directory}`));
|
|
462
|
+
const example = process.platform === "win32" ? "D:\\Repo\\equity_project" : "/opt/src/equity_project";
|
|
463
|
+
log(`请输入源码仓路径,例如:${example}`);
|
|
464
|
+
log(`也可以退出后使用 --backend-dir "${example}" 重新执行。`);
|
|
465
|
+
while (true) {
|
|
466
|
+
const entered = await (dependencies.inputText || inputText)(
|
|
467
|
+
`请输入 ${item.name} 源码 Git 仓库路径(例如 ${example})`,
|
|
468
|
+
{ stdin, stdout },
|
|
469
|
+
);
|
|
470
|
+
if (entered === EXIT_SELECTION) return { cancelled: true };
|
|
471
|
+
const normalized = trimPathInput(entered);
|
|
472
|
+
const candidate = normalized ? path.resolve(projectDir, normalized) : "";
|
|
473
|
+
if (candidate && io.existsSync(path.join(candidate, ".git"))) {
|
|
474
|
+
item.source.directory = candidate;
|
|
475
|
+
item.source.directoryCandidates.push(candidate);
|
|
476
|
+
log(`已使用 ${item.name} 源码仓:${candidate}`);
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
479
|
+
log(`路径不是有效 Git 仓库(缺少 .git):${candidate || "<空>"}`);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const missing = plan.filter((item) => item.source && !io.existsSync(path.join(item.source.directory, ".git")));
|
|
483
|
+
if (missing.length) {
|
|
484
|
+
for (const item of missing) {
|
|
485
|
+
const source = item.source;
|
|
486
|
+
const releaseScript = releaseScripts[item.name];
|
|
487
|
+
if (releaseScript && !/^[a-z0-9][a-z0-9:._-]*$/i.test(releaseScript)) {
|
|
488
|
+
throw new Error(`${item.name} releaseScripts 配置无效`);
|
|
489
|
+
}
|
|
490
|
+
log(`未找到 ${item.name} 源码仓: ${source.directory}`);
|
|
491
|
+
log("未执行任何构建或推送。请手动完成以下步骤:");
|
|
492
|
+
if (source.url) log(`1. git clone "${source.url}" "${source.directory}"`);
|
|
493
|
+
log(`${source.url ? "2" : "1"}. git -C "${source.directory}" fetch origin "${source.branch}"`);
|
|
494
|
+
const overrides = `${options.backendDir ? ` --backend-dir "${options.backendDir}"` : ""}${options.config ? ` --config "${options.config}"` : ""}`;
|
|
495
|
+
const rerun = releaseScript
|
|
496
|
+
? `pnpm run ${releaseScript} -- --platform ${target}${overrides}`
|
|
497
|
+
: `pnpm exec infly-libs release:docker --project-dir "${projectDir}" --target ${target} --components ${components.join(",")}${overrides} ${options.push ? "--push" : "--no-push"}`;
|
|
498
|
+
log(`${source.url ? "3" : "2"}. ${rerun}`);
|
|
499
|
+
}
|
|
500
|
+
return { target, missingSources: missing.map((item) => item.name) };
|
|
501
|
+
}
|
|
502
|
+
const run = dependencies.run || execute;
|
|
503
|
+
const capture = (command, args) => String(run(command, args, { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) || "").trim();
|
|
504
|
+
if (profile.pushRef || profile.requirements || profile.preBuild) {
|
|
505
|
+
runReleasePreparation(profile, { run, capture, projectDir, push: Boolean(options.push),
|
|
506
|
+
platform: dependencies.platform, env: dependencies.env,
|
|
507
|
+
releaseMode: releaseContext.mode, log });
|
|
508
|
+
}
|
|
509
|
+
await checkDocker(run, projectDir, true, dependencies);
|
|
510
|
+
const results = [];
|
|
511
|
+
const sources = new Map();
|
|
512
|
+
const workspaces = new Map();
|
|
513
|
+
const resources = [];
|
|
514
|
+
const publicSnapshots = new Map();
|
|
515
|
+
const verifyFrozen = ({ sourceDir, commit }, name) => {
|
|
516
|
+
const git = (...args) => capture("git", ["-C", sourceDir, ...args]);
|
|
517
|
+
if (git("status", "--porcelain", "--untracked-files=all")
|
|
518
|
+
|| git("rev-parse", "HEAD").toLowerCase() !== commit) {
|
|
519
|
+
throw new Error(`${name} 源码在冻结后发生变化,已停止本组构建及推送`);
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
let releaseError;
|
|
523
|
+
try {
|
|
524
|
+
let configuration;
|
|
525
|
+
if (profile.recordConfigurationRevision || plan.some((item) => item.dockerfileFromConfig || item.contextFiles)) {
|
|
526
|
+
const commit = capture("git", ["-C", projectDir, "rev-parse", "HEAD"]).toLowerCase();
|
|
527
|
+
if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error("无法冻结部署配置版本");
|
|
528
|
+
configuration = { sourceDir: projectDir, commit };
|
|
529
|
+
verifyFrozen(configuration, "部署配置");
|
|
530
|
+
workspaces.set(projectDir, configuration);
|
|
531
|
+
}
|
|
532
|
+
// 所有来源先冻结,再开始任何镜像构建。相同仓库和分支只 fetch 一次,
|
|
533
|
+
// worktree 使用完整 SHA,后续远端分支前移不会把同一组镜像拆成不同版本。
|
|
534
|
+
for (const item of plan) {
|
|
535
|
+
const directory = item.source?.directory || projectDir;
|
|
536
|
+
const sourceKey = JSON.stringify([directory, item.source?.branch || null]);
|
|
537
|
+
let frozen = sources.get(sourceKey);
|
|
538
|
+
if (!frozen) {
|
|
539
|
+
let sourceDir = projectDir;
|
|
540
|
+
let commit;
|
|
541
|
+
if (item.source) {
|
|
542
|
+
run("git", ["-C", directory, "fetch", "origin"], { cwd: projectDir });
|
|
543
|
+
commit = capture("git", ["-C", directory, "rev-parse", `origin/${item.source.branch}^{commit}`]).toLowerCase();
|
|
544
|
+
if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
|
|
545
|
+
const tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
|
|
546
|
+
sourceDir = path.join(tempRoot, "source");
|
|
547
|
+
// add 失败时也保留清理记录;不能安全移除 worktree 时留下目录供人工恢复。
|
|
548
|
+
resources.push({ tempRoot, worktree: sourceDir, repository: directory });
|
|
549
|
+
run("git", ["-C", directory, "worktree", "add", "--detach", sourceDir, commit], { cwd: projectDir });
|
|
550
|
+
} else {
|
|
551
|
+
commit = capture("git", ["-C", sourceDir, "rev-parse", "HEAD"]).toLowerCase();
|
|
552
|
+
}
|
|
553
|
+
if (!/^[a-f0-9]{40}$/.test(commit)) throw new Error(`${item.name} 无法冻结合法的源码提交`);
|
|
554
|
+
frozen = { sourceDir, commit };
|
|
555
|
+
sources.set(sourceKey, frozen);
|
|
556
|
+
}
|
|
557
|
+
const git = (...args) => capture("git", ["-C", frozen.sourceDir, ...args]);
|
|
558
|
+
if (git("status", "--porcelain", "--untracked-files=all")) throw new Error(`${item.name} 仓库存在未提交改动`);
|
|
559
|
+
const expectedRef = item.source ? null : item.expectedRef;
|
|
560
|
+
if (git("rev-parse", "HEAD").toLowerCase() !== frozen.commit || (expectedRef
|
|
561
|
+
&& frozen.commit !== git("rev-parse", `${expectedRef}^{commit}`).toLowerCase())) {
|
|
562
|
+
throw new Error(`${item.name} HEAD 与 ${expectedRef || "冻结提交"} 不一致,请先核对并 fetch 对应仓库`);
|
|
563
|
+
}
|
|
564
|
+
item.frozen = frozen;
|
|
565
|
+
item.releaseContext = item.source
|
|
566
|
+
? ((!item.source.standalone && (item.dockerfileFromConfig || item.contextFiles))
|
|
567
|
+
? (dependencies.detectReleaseContext || detectReleaseContext)({ projectDir: item.source.directory })
|
|
568
|
+
: { mode: "standalone", contextRoot: frozen.sourceDir, projectRelativeDir: "." })
|
|
569
|
+
: releaseContext;
|
|
570
|
+
if (item.source && item.releaseContext.mode === "standalone") {
|
|
571
|
+
item.releaseContext = { ...item.releaseContext, contextRoot: frozen.sourceDir, projectRelativeDir: "." };
|
|
572
|
+
}
|
|
573
|
+
if (item.buildStrategy === "source" && item.releaseContext.mode === "monorepo") {
|
|
574
|
+
const contextRoot = item.releaseContext.contextRoot;
|
|
575
|
+
let workspace = workspaces.get(contextRoot);
|
|
576
|
+
if (!workspace) {
|
|
577
|
+
const revision = capture("git", ["-C", contextRoot, "rev-parse", "HEAD"]).toLowerCase();
|
|
578
|
+
if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error(`${item.name} 无法解析合法的 monorepo revision`);
|
|
579
|
+
workspace = { sourceDir: contextRoot, commit: revision };
|
|
580
|
+
verifyFrozen(workspace, `${item.name} 的 monorepo 构建上下文`);
|
|
581
|
+
workspaces.set(contextRoot, workspace);
|
|
582
|
+
}
|
|
583
|
+
item.workspace = workspace;
|
|
584
|
+
if (item.projectInstall) {
|
|
585
|
+
const synchronized = dependencies.rootSynchronization;
|
|
586
|
+
if (synchronized?.verified && synchronized.workspaceRoot === contextRoot && synchronized.revision === workspace.commit) {
|
|
587
|
+
workspace.remote = { expectedRef: synchronized.expectedRef, revision: synchronized.revision, verified: true };
|
|
588
|
+
}
|
|
589
|
+
if (options.push && !workspace.remote) {
|
|
590
|
+
if (!item.workspaceRef) throw new Error(`${item.name} 正式源码发布必须配置 workspaceRef`);
|
|
591
|
+
workspace.remote = verifyWorkspaceRemote({ workspaceRoot: contextRoot, revision: workspace.commit,
|
|
592
|
+
expectedRef: item.workspaceRef, capture });
|
|
593
|
+
}
|
|
594
|
+
if (workspace.remote && item.workspaceRef !== workspace.remote.expectedRef) throw new Error("同一主仓不能使用不同的 workspaceRef");
|
|
595
|
+
if (!publicSnapshots.has(contextRoot)) {
|
|
596
|
+
const snapshot = (dependencies.prepareWorkspaceSnapshot || prepareWorkspaceSnapshot)({
|
|
597
|
+
workspaceRoot: contextRoot, revision: workspace.commit, run,
|
|
598
|
+
});
|
|
599
|
+
publicSnapshots.set(contextRoot, snapshot);
|
|
600
|
+
resources.push({ tempRoot: snapshot.contextRoot });
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
for (const item of plan) {
|
|
606
|
+
const { sourceDir, commit } = item.frozen;
|
|
607
|
+
let tempRoot;
|
|
608
|
+
verifyFrozen(item.frozen, item.name);
|
|
609
|
+
if (item.source) {
|
|
610
|
+
const sourceLabel = item.name === "backend" ? "后端" : (item.label || item.name);
|
|
611
|
+
log(`\x1b[0;32m✓ ${sourceLabel}构建分支:${item.source.branch}\x1b[0m`);
|
|
612
|
+
}
|
|
613
|
+
const buildStrategy = item.buildStrategy || "artifact";
|
|
614
|
+
const componentReleaseContext = item.releaseContext;
|
|
615
|
+
let buildProjectDir = componentReleaseContext.projectRelativeDir;
|
|
616
|
+
let context = buildStrategy === "source"
|
|
617
|
+
? componentReleaseContext.contextRoot
|
|
618
|
+
: inside(sourceDir, item.context || ".");
|
|
619
|
+
let dockerfile = inside(sourceDir, item.dockerfile || "Dockerfile");
|
|
620
|
+
let workspaceRevision;
|
|
621
|
+
let internalPackages;
|
|
622
|
+
if (buildStrategy === "source" && componentReleaseContext.mode === "standalone" && item.projectInstall) {
|
|
623
|
+
const prepared = (dependencies.prepareStandaloneInstallContext || prepareStandaloneInstallContext)({
|
|
624
|
+
sourceDir,
|
|
625
|
+
registryManifest: dependencies.registryManifest || ((name) => {
|
|
626
|
+
const invocation = buildExecutableSpawn("pnpm", ["view", `${name}@latest`, "version", "dependencies", "optionalDependencies", "peerDependencies", "--json"],
|
|
627
|
+
{ platform: dependencies.platform, env: dependencies.env });
|
|
628
|
+
return JSON.parse(capture(invocation.command, invocation.args));
|
|
629
|
+
}),
|
|
630
|
+
});
|
|
631
|
+
context = prepared.contextRoot;
|
|
632
|
+
tempRoot = context;
|
|
633
|
+
resources.push({ tempRoot });
|
|
634
|
+
internalPackages = prepared.packages;
|
|
635
|
+
buildProjectDir = ".";
|
|
636
|
+
}
|
|
637
|
+
if (buildStrategy === "source" && componentReleaseContext.mode === "monorepo") {
|
|
638
|
+
verifyFrozen(item.workspace, `${item.name} 的 monorepo 构建上下文`);
|
|
639
|
+
workspaceRevision = item.workspace.commit;
|
|
640
|
+
const prepared = item.projectInstall
|
|
641
|
+
? (dependencies.prepareProjectInstallContext || prepareProjectInstallContext)({
|
|
642
|
+
workspaceRoot: publicSnapshots.get(componentReleaseContext.contextRoot).contextRoot,
|
|
643
|
+
sourceDir,
|
|
644
|
+
})
|
|
645
|
+
: (dependencies.prepareMinimalMonorepoContext || prepareMinimalMonorepoContext)({
|
|
646
|
+
workspaceRoot: componentReleaseContext.contextRoot,
|
|
647
|
+
projectDir: item.source ? item.source.directory : sourceDir,
|
|
648
|
+
additionalFiles: item.monorepoContextFiles || [],
|
|
649
|
+
...(item.source ? { sourceDir } : {}),
|
|
650
|
+
io,
|
|
651
|
+
});
|
|
652
|
+
tempRoot = prepared.contextRoot;
|
|
653
|
+
resources.push({ tempRoot });
|
|
654
|
+
context = prepared.contextRoot;
|
|
655
|
+
internalPackages = prepared.packages;
|
|
656
|
+
buildProjectDir = prepared.projectRelativeDir;
|
|
657
|
+
dockerfile = inside(context, `${prepared.projectRelativeDir}/${item.dockerfile || "Dockerfile"}`);
|
|
658
|
+
log(item.projectInstall
|
|
659
|
+
? `项目安装上下文: 自身 workspace/lockfile + 临时源码安装锁 + ${prepared.packages.join(", ")}`
|
|
660
|
+
: `最小上下文: ${prepared.projectRelativeDir} + packages + 根安装文件 + ${item.monorepoContextFiles?.length || 0} 个显式声明文件`);
|
|
661
|
+
}
|
|
662
|
+
// 部署仓提供 Dockerfile/运行配置;独立模式也先复制上下文,绝不改写冻结源码。
|
|
663
|
+
if (item.contextFiles) {
|
|
664
|
+
if (!tempRoot) {
|
|
665
|
+
tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-context-"));
|
|
666
|
+
resources.push({ tempRoot });
|
|
667
|
+
context = path.join(tempRoot, "context");
|
|
668
|
+
io.cpSync(sourceDir, context, { recursive: true, dereference: false,
|
|
669
|
+
filter: (file) => !path.relative(sourceDir, file).split(path.sep).includes(".git") });
|
|
670
|
+
}
|
|
671
|
+
const destinationRoot = componentReleaseContext.mode === "monorepo"
|
|
672
|
+
? inside(context, buildProjectDir) : context;
|
|
673
|
+
for (const entry of item.contextFiles) {
|
|
674
|
+
const from = confinedPath(projectDir, entry.from, io);
|
|
675
|
+
const to = confinedPath(destinationRoot, entry.to, io);
|
|
676
|
+
if (!io.existsSync(from)) throw new Error(`缺少部署构建文件: ${entry.from}`);
|
|
677
|
+
io.mkdirSync(path.dirname(to), { recursive: true });
|
|
678
|
+
io.cpSync(from, to, { recursive: true, dereference: true,
|
|
679
|
+
filter: (file) => { confinedPath(projectDir, path.relative(projectDir, file), io); return true; } });
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
if (item.dockerfileFromConfig) dockerfile = confinedPath(projectDir, item.dockerfileFromConfig, io);
|
|
683
|
+
const effectiveBuildArgs = {
|
|
684
|
+
...(item.buildArgs || {}),
|
|
685
|
+
...(buildStrategy === "source" ? { BUILD_MODE: componentReleaseContext.mode, PROJECT_DIR: buildProjectDir } : {}),
|
|
686
|
+
...(item.projectInstall && componentReleaseContext.mode === "standalone" ? { REFRESH_INTERNAL: true } : {}),
|
|
687
|
+
};
|
|
688
|
+
let provenance;
|
|
689
|
+
const releaseId = item.releaseIdentity ? createReleaseId(commit, dependencies.releaseToken?.()) : commit;
|
|
690
|
+
if (item.releaseIdentity) {
|
|
691
|
+
if (!tempRoot) throw new Error("唯一发布标识必须使用隔离构建上下文");
|
|
692
|
+
provenance = createBuildProvenance({ releaseId, component: item.name, businessRevision: commit,
|
|
693
|
+
workspaceRevision, configurationRevision: configuration?.commit,
|
|
694
|
+
workspaceRemote: item.workspace?.remote, platform: item.platform || "linux/amd64",
|
|
695
|
+
mode: componentReleaseContext.mode, target, buildArgs: effectiveBuildArgs });
|
|
696
|
+
provenance.internalPackages = internalPackages || [];
|
|
697
|
+
io.writeFileSync(path.join(context, ".infly-release.json"), `${JSON.stringify(provenance, null, 2)}\n`);
|
|
698
|
+
}
|
|
699
|
+
for (const file of item.requiredFiles || []) {
|
|
700
|
+
if (!io.existsSync(inside(sourceDir, file))) throw new Error(`缺少必需构建产物: ${file}`);
|
|
701
|
+
}
|
|
702
|
+
if (item.files) {
|
|
703
|
+
if (!tempRoot) {
|
|
704
|
+
tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
|
|
705
|
+
resources.push({ tempRoot });
|
|
706
|
+
}
|
|
707
|
+
context = path.join(tempRoot, "context");
|
|
708
|
+
io.mkdirSync(context, { recursive: true });
|
|
709
|
+
for (const file of item.files) {
|
|
710
|
+
const from = inside(sourceDir, file.from);
|
|
711
|
+
const to = inside(context, file.to);
|
|
712
|
+
// 仅复制配置声明的产物,避免把整个 monorepo 发送给 Docker。
|
|
713
|
+
io.mkdirSync(path.dirname(to), { recursive: true });
|
|
714
|
+
io.cpSync(from, to, { recursive: true, dereference: false });
|
|
715
|
+
}
|
|
716
|
+
dockerfile = inside(context, item.dockerfile || "Dockerfile");
|
|
717
|
+
}
|
|
718
|
+
if (!io.existsSync(dockerfile)) throw new Error(`缺少 Dockerfile: ${dockerfile}`);
|
|
719
|
+
const image = `${item.repository}:${item.tagPrefix || ""}${releaseId}`;
|
|
720
|
+
const latestImage = item.mutableTags === false ? null : `${item.repository}:latest`;
|
|
721
|
+
// --load 只把当前构建节点平台的镜像载入本地镜像存储;发布流程直接使用单平台镜像。
|
|
722
|
+
const buildOptions = ["buildx", "build", "--load", "--file", dockerfile];
|
|
723
|
+
if (item.platform) buildOptions.push("--platform", item.platform);
|
|
724
|
+
if (item.target) buildOptions.push("--target", item.target);
|
|
725
|
+
const buildArgs = effectiveBuildArgs;
|
|
726
|
+
for (const [key, value] of Object.entries(buildArgs)) {
|
|
727
|
+
buildOptions.push("--build-arg", `${key}=${value}`);
|
|
728
|
+
}
|
|
729
|
+
run("docker", [...buildOptions,
|
|
730
|
+
"--label", `org.opencontainers.image.revision=${commit}`, "--label", `org.opencontainers.image.version=${releaseId}`,
|
|
731
|
+
...(item.releaseIdentity ? ["--label", `com.infly.release.id=${releaseId}`] : []),
|
|
732
|
+
...(workspaceRevision ? ["--label", `com.infly.workspace.revision=${workspaceRevision}`] : []),
|
|
733
|
+
...(configuration ? ["--label", `com.infly.deployment.revision=${configuration.commit}`] : []),
|
|
734
|
+
"--label", `com.infly.platform=${target}`, "--tag", image,
|
|
735
|
+
...(latestImage ? ["--tag", latestImage] : []), context], { cwd: projectDir });
|
|
736
|
+
if (capture("docker", ["image", "inspect", "--format", '{{ index .Config.Labels "org.opencontainers.image.revision" }}', image]) !== commit) {
|
|
737
|
+
throw new Error(`${item.name} 镜像 revision 校验失败`);
|
|
738
|
+
}
|
|
739
|
+
if (item.check) {
|
|
740
|
+
const hosts = (item.check.addHosts || []).flatMap((host) => ["--add-host", host]);
|
|
741
|
+
run("docker", ["run", "--rm", ...hosts, "--entrypoint", item.check.entrypoint, image, ...item.check.args], { cwd: projectDir });
|
|
742
|
+
}
|
|
743
|
+
if (item.health) {
|
|
744
|
+
await (dependencies.healthCheckImage || healthCheckImage)(image, {
|
|
745
|
+
cwd: projectDir, healthTimeout: String(item.health.timeoutSeconds), healthAddHost: item.health.addHost,
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
log(`${item.name}_commit=${commit}`);
|
|
749
|
+
log(`${item.name}=${image}`);
|
|
750
|
+
if (latestImage) log(`${item.name}_latest=${latestImage}`);
|
|
751
|
+
const identity = {};
|
|
752
|
+
if (item.releaseIdentity) {
|
|
753
|
+
identity.releaseId = releaseId;
|
|
754
|
+
identity.imageId = capture("docker", ["image", "inspect", "--format", "{{.Id}}", image]);
|
|
755
|
+
if (!/^sha256:[0-9a-f]{64}$/.test(identity.imageId)) throw new Error("本地镜像内容 ID 无效");
|
|
756
|
+
identity.provenance = provenance;
|
|
757
|
+
}
|
|
758
|
+
const channelImage = item.releaseChannel ? `${item.repository}:${item.tagPrefix || ""}${target}-latest` : null;
|
|
759
|
+
if (channelImage && !/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/.test(channelImage.slice(channelImage.lastIndexOf(":") + 1))) {
|
|
760
|
+
throw new Error("环境最新镜像标签无效");
|
|
761
|
+
}
|
|
762
|
+
results.push({ component: item.name, commit, image, latestImage, ...(channelImage ? { channelImage } : {}), pushed: false, ...identity });
|
|
763
|
+
}
|
|
764
|
+
for (const frozen of sources.values()) verifyFrozen(frozen, frozen.sourceDir);
|
|
765
|
+
for (const frozen of workspaces.values()) verifyFrozen(frozen, "monorepo 构建上下文");
|
|
766
|
+
// 整组构建及校验通过后才推送。Registry 的多次 push 不具备事务性,
|
|
767
|
+
// 网络失败可能留下部分镜像;不打印成功汇总,部署端仍需校验整组镜像齐备。
|
|
768
|
+
if (options.push) {
|
|
769
|
+
for (const result of results) {
|
|
770
|
+
run("docker", ["push", result.image], { cwd: projectDir });
|
|
771
|
+
if (result.releaseId) {
|
|
772
|
+
result.digest = readRegistryDigest(capture, result.image);
|
|
773
|
+
result.deployImage = `${result.image.slice(0, result.image.lastIndexOf(":"))}@${result.digest}`;
|
|
774
|
+
run("docker", ["pull", "--platform", result.provenance.platform, result.deployImage], { cwd: projectDir });
|
|
775
|
+
if (capture("docker", ["image", "inspect", "--format", "{{.Id}}", result.deployImage]) !== result.imageId) {
|
|
776
|
+
throw new Error("Registry digest 对应的内容与本地已验证镜像不一致");
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
if (result.latestImage) run("docker", ["push", result.latestImage], { cwd: projectDir });
|
|
780
|
+
result.pushed = true;
|
|
781
|
+
}
|
|
782
|
+
// 全组精确镜像均验证成功后才更新环境入口;部署端立即解析为 digest,之后不再读取可变标签。
|
|
783
|
+
for (const result of results.filter((entry) => entry.channelImage)) {
|
|
784
|
+
run("docker", ["tag", result.imageId, result.channelImage], { cwd: projectDir });
|
|
785
|
+
run("docker", ["push", result.channelImage], { cwd: projectDir });
|
|
786
|
+
if (readRegistryDigest(capture, result.channelImage) !== result.digest) throw new Error("环境最新镜像入口与本次发布内容不一致");
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
} catch (error) {
|
|
790
|
+
releaseError = error;
|
|
791
|
+
} finally {
|
|
792
|
+
const cleanupErrors = [];
|
|
793
|
+
for (const resource of resources.reverse()) {
|
|
794
|
+
try {
|
|
795
|
+
// 只移除本次创建的隔离 worktree;移除失败时不删除其父目录。
|
|
796
|
+
if (resource.worktree) run("git", ["-C", resource.repository, "worktree", "remove", "--force", resource.worktree], { cwd: projectDir });
|
|
797
|
+
io.rmSync(resource.tempRoot, { recursive: true, force: true });
|
|
798
|
+
} catch (error) {
|
|
799
|
+
log(`临时构建目录清理失败,已保留恢复路径:${resource.tempRoot}`);
|
|
800
|
+
cleanupErrors.push(new Error(`清理失败,保留恢复路径:${resource.tempRoot}`, { cause: error }));
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
if (cleanupErrors.length) releaseError = new globalThis.AggregateError(
|
|
804
|
+
[...(releaseError ? [releaseError] : []), ...cleanupErrors],
|
|
805
|
+
[releaseError?.message, ...cleanupErrors.map((error) => error.message)].filter(Boolean).join(";"),
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
if (releaseError) throw releaseError;
|
|
809
|
+
for (const result of results.filter((entry) => entry.releaseId)) {
|
|
810
|
+
const recordRoot = path.join(projectDir, "node_modules", ".cache", "infly-releases");
|
|
811
|
+
io.mkdirSync(recordRoot, { recursive: true });
|
|
812
|
+
const record = path.join(recordRoot, `${result.releaseId}.json`);
|
|
813
|
+
io.writeFileSync(record, `${JSON.stringify(result, null, 2)}\n`, { flag: "wx" });
|
|
814
|
+
log(`release_id=${result.releaseId}`);
|
|
815
|
+
if (result.deployImage) log(`deploy_image=${result.deployImage}`);
|
|
816
|
+
log(`release_record=${record}`);
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// 构建结果汇总(排版与 build:docker 保持一致:✅ 完成 + 可用标签 + 可选发布系统链接)。
|
|
820
|
+
// 构建时已逐组件打印 frontend_commit= 等机器行,供失败前人工留档;这里汇总为可直接复制到
|
|
821
|
+
// 输出同时面向本地核对与 Jenkins 下拉部署,避免再手工复制提交参数。
|
|
822
|
+
if (results.length) {
|
|
823
|
+
const usesMutableTags = results.some((item) => item.latestImage);
|
|
824
|
+
const pushNote = options.push
|
|
825
|
+
? profile.deployment?.ready === true
|
|
826
|
+
? usesMutableTags
|
|
827
|
+
? "已推送不可变提交标签和 latest 最新推送标签,可直接在 Jenkins 选择部署"
|
|
828
|
+
: "已推送不可变提交标签,可直接在 Jenkins 选择部署"
|
|
829
|
+
: usesMutableTags
|
|
830
|
+
? "已推送不可变提交标签和 latest 最新推送标签;该平台尚未开放 Jenkins 部署"
|
|
831
|
+
: "已推送不可变提交标签;该平台尚未开放 Jenkins 部署"
|
|
832
|
+
: "仅本地生成,未推送镜像";
|
|
833
|
+
log("");
|
|
834
|
+
log("\x1b[0;34m==========================================");
|
|
835
|
+
log("✅ 完成");
|
|
836
|
+
log("==========================================\x1b[0m");
|
|
837
|
+
log(`可用标签(${pushNote}):`);
|
|
838
|
+
for (const r of results) {
|
|
839
|
+
log(` ${r.component}=${r.image} (${r.releaseId ? "唯一发布版本" : "不可变提交版本"})`);
|
|
840
|
+
if (r.pushed && r.channelImage) log(` ${r.component}_channel=${r.channelImage} (默认部署入口,部署时固定 digest)`);
|
|
841
|
+
if (r.latestImage) log(` ${r.component}_latest=${r.latestImage} (最新推送镜像,即所选平台 registry 的 latest)`);
|
|
842
|
+
}
|
|
843
|
+
if (cicdLink && profile.deployment?.ready === true) {
|
|
844
|
+
log("");
|
|
845
|
+
// 单组件推送成功后把平台与完整提交预填进 Jenkins 参数,新平台首次部署无需从历史下拉选项挑选;
|
|
846
|
+
// 多组件对应对应多个任务时保持原链接,非 /build 地址由 formatCicdLink 原样返回。
|
|
847
|
+
const deployLink = options.push && profile.deployment?.ready === true
|
|
848
|
+
&& results.length === 1 && /^[a-z0-9]+$/.test(target)
|
|
849
|
+
? formatCicdLink(options.cicdUrl, { platform: target, platformLabel: profile.label,
|
|
850
|
+
tag: results[0].commit, releaseVersion: results[0].releaseId,
|
|
851
|
+
date: beijingDateTime((dependencies.now || (() => new Date()))()) })
|
|
852
|
+
: cicdLink;
|
|
853
|
+
log(deployLink);
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
return { target, results };
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
module.exports = { buildExecutableSpawn, compareVersions, detectReleaseContext, detectReleaseMode, normalizePreBuildCommand,
|
|
860
|
+
parseReleaseArgs, runReleasePreparation, runTargetRelease, validateReleaseProfile, windowsExecutable };
|