forked from microsoft/azure-pipelines-tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
1469 lines (1224 loc) · 75 KB
/
Program.cs
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
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using BuildConfigGen.Debugging;
namespace BuildConfigGen
{
internal class Knob
{
public static readonly Knob Default = new Knob { SourceDirectoriesMustContainPlaceHolders = false };
// when true, Source Directories must contain _buildConfigs placeholders for each build config
// _buildConfigs are written to each directory when --write-updates is specified
// setting to false for now so we're not forced to check in a lot of placeholders to tasks that don't use them
public bool SourceDirectoriesMustContainPlaceHolders { get; init; }
}
internal class Program
{
private const string filesOverriddenForConfigGoHereReadmeTxt = "FilesOverriddenForConfigGoHereREADME.txt";
private const string buildConfigs = "_buildConfigs";
static readonly JsonSerializerOptions jso = new System.Text.Json.JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
internal static class Config
{
public static readonly string[] ExtensionsToPreprocess = new[] { ".ts", ".json" };
public record ConfigRecord(string name, string constMappingKey, bool isDefault, bool isNode, string nodePackageVersion, bool isWif, string nodeHandler, string preprocessorVariableName, bool enableBuildConfigOverrides, bool deprecated, bool shouldUpdateTypescript, bool writeNpmrc, string? overriddenDirectoryName = null, bool shouldUpdateLocalPkgs = false, bool useGlobalVersion = false, bool useAltGeneratedPath = false);
public static readonly ConfigRecord Default = new ConfigRecord(name: nameof(Default), constMappingKey: "Default", isDefault: true, isNode: false, nodePackageVersion: "", isWif: false, nodeHandler: "", preprocessorVariableName: "DEFAULT", enableBuildConfigOverrides: false, deprecated: false, shouldUpdateTypescript: false, writeNpmrc: false);
public static readonly ConfigRecord Node16 = new ConfigRecord(name: nameof(Node16), constMappingKey: "Node16-219", isDefault: false, isNode: true, nodePackageVersion: "^16.11.39", isWif: false, nodeHandler: "Node16", preprocessorVariableName: "NODE16", enableBuildConfigOverrides: true, deprecated: true, shouldUpdateTypescript: false, writeNpmrc: false);
public static readonly ConfigRecord Node16_225 = new ConfigRecord(name: nameof(Node16_225), constMappingKey: "Node16-225", isDefault: false, isNode: true, isWif: false, nodePackageVersion: "^16.11.39", nodeHandler: "Node16", preprocessorVariableName: "NODE16", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: false, overriddenDirectoryName: "Node16", writeNpmrc: false);
public static readonly ConfigRecord Node20 = new ConfigRecord(name: nameof(Node20), constMappingKey: "Node20-225", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_228 = new ConfigRecord(name: nameof(Node20_228), constMappingKey: "Node20-228", isDefault: false, isNode: true, nodePackageVersion: "^20.11.0", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_1 = new ConfigRecord(name: nameof(Node20_229_1), constMappingKey: "Node20_229_1", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_2 = new ConfigRecord(name: nameof(Node20_229_2), constMappingKey: "Node20_229_2", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_3 = new ConfigRecord(name: nameof(Node20_229_3), constMappingKey: "Node20_229_3", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_4 = new ConfigRecord(name: nameof(Node20_229_4), constMappingKey: "Node20_229_4", isDefault: false, isNode: true, nodePackageVersion: "^20.11.0", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_5 = new ConfigRecord(name: nameof(Node20_229_5), constMappingKey: "Node20_229_5", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_6 = new ConfigRecord(name: nameof(Node20_229_6), constMappingKey: "Node20_229_6", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_7 = new ConfigRecord(name: nameof(Node20_229_7), constMappingKey: "Node20_229_7", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_8 = new ConfigRecord(name: nameof(Node20_229_8), constMappingKey: "Node20_229_8", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_9 = new ConfigRecord(name: nameof(Node20_229_9), constMappingKey: "Node20_229_9", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_10 = new ConfigRecord(name: nameof(Node20_229_10), constMappingKey: "Node20_229_10", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_11 = new ConfigRecord(name: nameof(Node20_229_11), constMappingKey: "Node20_229_11", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_12 = new ConfigRecord(name: nameof(Node20_229_12), constMappingKey: "Node20_229_12", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_13 = new ConfigRecord(name: nameof(Node20_229_13), constMappingKey: "Node20_229_13", isDefault: false, isNode: true, nodePackageVersion: "^20.11.0", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord Node20_229_14 = new ConfigRecord(name: nameof(Node20_229_14), constMappingKey: "Node20_229_14", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Node20", writeNpmrc: true);
public static readonly ConfigRecord WorkloadIdentityFederation = new ConfigRecord(name: nameof(WorkloadIdentityFederation), constMappingKey: "WorkloadIdentityFederation", isDefault: false, isNode: true, nodePackageVersion: "^16.11.39", isWif: true, nodeHandler: "Node16", preprocessorVariableName: "WORKLOADIDENTITYFEDERATION", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: false, writeNpmrc: false);
public static readonly ConfigRecord wif_242 = new ConfigRecord(name: nameof(wif_242), constMappingKey: "wif_242", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: true, nodeHandler: "Node20_1", preprocessorVariableName: "WIF", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "Wif", writeNpmrc: true);
public static readonly ConfigRecord LocalPackages = new ConfigRecord(name: nameof(LocalPackages), constMappingKey: "LocalPackages", isDefault: false, isNode: true, nodePackageVersion: "^20.3.1", isWif: false, nodeHandler: "Node20_1", preprocessorVariableName: "NODE20", enableBuildConfigOverrides: true, deprecated: false, shouldUpdateTypescript: true, overriddenDirectoryName: "LocalPackages", writeNpmrc: true, shouldUpdateLocalPkgs: true, useGlobalVersion: true, useAltGeneratedPath: true);
public static ConfigRecord[] Configs = { Default, Node16, Node16_225, Node20, Node20_228, Node20_229_1, Node20_229_2, Node20_229_3, Node20_229_4, Node20_229_5, Node20_229_6, Node20_229_7, Node20_229_8, Node20_229_9, Node20_229_10, Node20_229_11, Node20_229_12, Node20_229_13, Node20_229_14, WorkloadIdentityFederation, wif_242, LocalPackages };
}
static List<string> notSyncronizedDependencies = [];
// ensureUpdateModeVerifier wraps all writes. if writeUpdate=false, it tracks writes that would have occured
static EnsureUpdateModeVerifier? ensureUpdateModeVerifier;
/// <param name="task">The task to generate build configs for</param>
/// <param name="configs">List of configs to generate seperated by |</param>
/// <param name="currentSprint">Overide current sprint; omit to get from whatsprintis.it</param>
/// <param name="writeUpdates">Write updates if true, else validate that the output is up-to-date</param>
/// <param name="allTasks"></param>
/// <param name="getTaskVersionTable"></param>
/// <param name="debugAgentDir">When set to the local pipeline agent directory, this tool will produce tasks in debug mode with the corresponding visual studio launch configurations that can be used to attach to built tasks running on this agent</param>
/// <param name="includeLocalPackagesBuildConfig">Include LocalPackagesBuildConfig</param>
static void Main(string? task = null, string? configs = null, int? currentSprint = null, bool writeUpdates = false, bool allTasks = false, bool getTaskVersionTable = false, string? debugAgentDir = null, bool includeLocalPackagesBuildConfig = false)
{
try
{
ensureUpdateModeVerifier = new EnsureUpdateModeVerifier(!writeUpdates);
MainInner(task, configs, currentSprint, writeUpdates, allTasks, getTaskVersionTable, debugAgentDir, includeLocalPackagesBuildConfig);
}
catch (Exception e2)
{
// format exceptions nicer than the default formatting. This prevents a long callstack from DragonFruit and puts the exception on the bottom so it's easier to find.
// error handling strategy:
// 1. design: anything goes wrong, try to detect and crash as early as possible to preserve the callstack to make debugging easier.
// 2. we allow all exceptions to fall though. Non-zero exit code will be surfaced
// 3. Ideally default windows exception will occur and errors reported to WER/watson. I'm not sure this is happening, perhaps DragonFruit is handling the exception
var restore = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e2.ToString());
Console.ForegroundColor = restore;
Console.WriteLine();
Console.WriteLine("An exception occured generating configs. Exception message below: (full callstack above)");
Console.WriteLine(e2.Message);
Environment.Exit(1);
}
}
private static void MainInner(string? task, string? configs, int? currentSprintNullable, bool writeUpdates, bool allTasks, bool getTaskVersionTable, string? debugAgentDir, bool includeLocalPackagesBuildConfig)
{
if (allTasks)
{
NullOrThrow(task, "If allTasks specified, task must not be supplied");
NullOrThrow(configs, "If allTasks specified, configs must not be supplied");
}
else
{
NotNullOrThrow(task, "Task is required");
}
string currentDir = Environment.CurrentDirectory;
string gitRootPath = GitUtil.GetGitRootPath(currentDir);
string globalVersionPath = Path.Combine(gitRootPath, @"globalversion.txt");
TaskVersion? globalVersion = GetGlobalVersion(gitRootPath, globalVersionPath);
string generatedFolder = Path.Combine(gitRootPath, "_generated");
string altGeneratedFolder = Path.Combine(gitRootPath, "_generated_local"); // <-- added to .gitignore
if (getTaskVersionTable)
{
var tasks = MakeOptionsReader.ReadMakeOptions(gitRootPath);
Console.WriteLine("config\ttask\tversion");
foreach (var t in tasks.Values)
{
GetVersions(t.Name, string.Join('|', t.Configs), out var r, globalVersion, generatedFolder);
foreach (var z in r)
{
Console.WriteLine(string.Concat(z.config, "\t", z.task, "\t", z.version));
}
}
return;
}
IDebugConfigGenerator debugConfGen = string.IsNullOrEmpty(debugAgentDir)
? new NoDebugConfigGenerator()
: new VsCodeLaunchConfigGenerator(gitRootPath, debugAgentDir);
int maxPatchForCurrentSprint = 0;
int currentSprint;
if (currentSprintNullable.HasValue)
{
currentSprint = currentSprintNullable.Value;
}
else
{
currentSprint = GetCurrentSprint();
}
Dictionary<string, TaskStateStruct> taskVersionInfo = [];
{
var tasks = MakeOptionsReader.ReadMakeOptions(gitRootPath).AsEnumerable()
.Where(c => c.Value.Configs.Any()); // only tasks with configs
if (!allTasks)
{
var taskList = task!.Split(',', '|');
tasks = tasks.Where(s => taskList.Where(tl => string.Equals(tl, s.Key, StringComparison.OrdinalIgnoreCase)).Any());
}
foreach (var t in tasks)
{
taskVersionInfo.Add(t.Value.Name, new TaskStateStruct([], []));
}
foreach (var t in tasks)
{
IEnumerable<string> configsList = FilterConfigsForTask(configs, t);
HashSet<Config.ConfigRecord> targetConfigs = GetConfigRecords(configsList, writeUpdates);
UpdateVersionsForTask(t.Value.Name, taskVersionInfo[t.Value.Name], targetConfigs, currentSprint, globalVersionPath, ref maxPatchForCurrentSprint, globalVersion, generatedFolder);
CheckForDuplicates(t.Value.Name, taskVersionInfo[t.Value.Name].configTaskVersionMapping);
}
// bump patch number for global if any tasks invalidated.
if (taskVersionInfo.Values.Any(x => x.versionsUpdated.Any()))
{
maxPatchForCurrentSprint = maxPatchForCurrentSprint + 1;
}
foreach (var t in tasks)
{
IEnumerable<string> configsList = FilterConfigsForTask(configs, t);
if (includeLocalPackagesBuildConfig)
{
if (globalVersion is null)
{
globalVersion = new TaskVersion(0, currentSprint, maxPatchForCurrentSprint);
}
else
{
if (globalVersion.Minor == currentSprint)
{
globalVersion = globalVersion.CloneWithMinorAndPatch(currentSprint, Math.Max(maxPatchForCurrentSprint, globalVersion.Patch));
globalVersion = globalVersion.CloneWithMajor(taskVersionInfo[t.Value.Name].configTaskVersionMapping[Config.Default].Major);
}
else
{
// this could fail if there is a task with a future-sprint version, which should not be the case. If that happens, CheckForDuplicates will throw
globalVersion = globalVersion.CloneWithMinorAndPatch(currentSprint, 0);
globalVersion = globalVersion.CloneWithMajor(taskVersionInfo[t.Value.Name].configTaskVersionMapping[Config.Default].Major);
}
}
}
if (globalVersion is not null)
{
// populate global verison information
HashSet<Config.ConfigRecord> targetConfigs = GetConfigRecords(configsList, writeUpdates);
UpdateVersionsGlobal(t.Value.Name, taskVersionInfo[t.Value.Name], targetConfigs, globalVersion);
CheckForDuplicates(t.Value.Name, taskVersionInfo[t.Value.Name].configTaskVersionMapping);
}
}
if (globalVersion is not null)
{
ensureUpdateModeVerifier!.WriteAllText(globalVersionPath, globalVersion!.MinorPatchToString(), false);
}
ThrowWithUserFriendlyErrorToRerunWithWriteUpdatesIfVeriferError("(global)", skipContentCheck: false);
foreach (var t in tasks)
{
IEnumerable<string> configsList = FilterConfigsForTask(configs, t);
MainUpdateTask(taskVersionInfo[t.Value.Name], t.Value.Name, configsList, writeUpdates, currentSprint, debugConfGen, includeLocalPackagesBuildConfig, hasGlobalVersion: globalVersion is not null, generatedFolder: generatedFolder, altGeneratedFolder: altGeneratedFolder);
}
debugConfGen.WriteLaunchConfigurations();
if (notSyncronizedDependencies.Count > 0)
{
notSyncronizedDependencies.Insert(0, $"##vso[task.logissue type=error]There are problems with the dependencies in the buildConfig's package.json files. Please fix the following issues:");
throw new Exception(string.Join("\r\n", notSyncronizedDependencies));
}
}
}
private static IEnumerable<string> FilterConfigsForTask(string? configs, KeyValuePair<string, MakeOptionsReader.AgentTask> t)
{
var configsList = t.Value.Configs.AsEnumerable();
if (configs != null)
{
var configsList2 = configs!.Split(',', '|');
configsList = configsList.Where(s => configsList2.Where(tl => string.Equals(tl, s, StringComparison.OrdinalIgnoreCase)).Any());
}
return configsList;
}
private static void CheckForDuplicates(string task, Dictionary<Config.ConfigRecord, TaskVersion> configTaskVersionMapping)
{
var duplicateVersions = configTaskVersionMapping.GroupBy(x => x.Value).Select(x => new { version = x.Key, configName = String.Join(",", x.Select(x => x.Key.name)), count = x.Count() }).Where(x => x.count > 1);
if (duplicateVersions.Any())
{
StringBuilder dupConfigsStr = new StringBuilder();
foreach (var x in duplicateVersions)
{
dupConfigsStr.AppendLine($"task={task} version={x.version} specified in multiple configName={x.configName} config count={x.count}");
}
throw new Exception(dupConfigsStr.ToString());
}
}
private static void NullOrThrow<T>(T value, string message)
{
if (value != null)
{
throw new Exception(message);
}
}
private static void NotNullOrThrow<T>([NotNull] T value, string message)
{
if (value == null)
{
throw new Exception(message);
}
}
private static void GetVersions(string task, string configsString, out List<(string task, string config, string version)> versionList, TaskVersion? globalVersion, string generatedFolder)
{
versionList = new List<(string task, string config, string version)>();
if (string.IsNullOrEmpty(task))
{
throw new Exception("task expected!");
}
if (string.IsNullOrEmpty(configsString))
{
throw new Exception("configs expected!");
}
string currentDir = Environment.CurrentDirectory;
string gitRootPath = GitUtil.GetGitRootPath(currentDir);
string taskTargetPath = Path.Combine(gitRootPath, "Tasks", task);
if (!Directory.Exists(taskTargetPath))
{
throw new Exception($"expected {taskTargetPath} to exist!");
}
if (!Directory.Exists(generatedFolder))
{
throw new Exception("_generated does not exist");
}
string versionMapFile = Path.Combine(generatedFolder, @$"{task}.versionmap.txt");
try
{
if (ReadVersionMap(versionMapFile, out var versionMap, out var maxVersionNullable, globalVersion))
{
foreach (var version in versionMap)
{
versionList.Add((task, version.Key, version.Value));
}
}
else
{
throw new Exception($"versionMapFile {versionMapFile} does not exist");
}
ThrowWithUserFriendlyErrorToRerunWithWriteUpdatesIfVeriferError(task, skipContentCheck: false);
}
finally
{
if (ensureUpdateModeVerifier != null)
{
ensureUpdateModeVerifier.CleanupTempFiles();
}
}
}
private static int GetCurrentSprint()
{
// Scheduled time for Cortesy Push
var cortesyPushScheduleDay = DayOfWeek.Tuesday;
var cortesyPushUtcTime = new TimeOnly(8, 30); //UTC time
string url = "https://whatsprintis.it";
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
string json = httpClient.GetStringAsync(url).Result;
JsonDocument currentSprintData = JsonDocument.Parse(json);
int currentSprint = currentSprintData.RootElement.GetProperty("sprint").GetInt32();
int week = currentSprintData.RootElement.GetProperty("week").GetInt32();
if (week == 3) // if it is the end of the current sprint
{
var nowUtc = DateTime.UtcNow;
// Increase sprint number if scheduled pipeline was already triggered
if (nowUtc.DayOfWeek > cortesyPushScheduleDay)
{
currentSprint++;
}
else if (nowUtc.DayOfWeek == cortesyPushScheduleDay)
{
if (TimeOnly.FromDateTime(nowUtc) >= cortesyPushUtcTime)
{
currentSprint++;
}
}
}
return currentSprint;
}
private static void ThrowWithUserFriendlyErrorToRerunWithWriteUpdatesIfVeriferError(string task, bool skipContentCheck)
{
// if !writeUpdates, error if we have written any updates
var verifyErrors = ensureUpdateModeVerifier!.GetVerifyErrors(skipContentCheck).ToList();
if (verifyErrors.Count != 0)
{
Console.WriteLine("");
Console.WriteLine("Updates needed:");
foreach (var s in verifyErrors)
{
Console.WriteLine(s);
}
throw new Exception($"Updates needed, please run npm make.js --task {task} ");
}
}
private static void MainUpdateTask(
TaskStateStruct taskVersionState,
string task,
IEnumerable<string> configs,
bool writeUpdates,
int currentSprint,
IDebugConfigGenerator debugConfigGen,
bool includeLocalPackagesBuildConfig,
bool hasGlobalVersion,
string generatedFolder,
string altGeneratedFolder)
{
if (string.IsNullOrEmpty(task))
{
throw new Exception("task expected!");
}
HashSet<Config.ConfigRecord> targetConfigs = GetConfigRecords(configs, writeUpdates);
try
{
string currentDir = Environment.CurrentDirectory;
string gitRootPath = GitUtil.GetGitRootPath(currentDir);
string versionMapFile = GetVersionMapFile(task, gitRootPath, generatedFolder);
string taskTargetPath = Path.Combine(gitRootPath, "Tasks", task);
if (!Directory.Exists(taskTargetPath))
{
throw new Exception($"expected {taskTargetPath} to exist!");
}
string taskHandler = Path.Combine(taskTargetPath, "task.json");
JsonNode taskHandlerContents = JsonNode.Parse(ensureUpdateModeVerifier!.FileReadAllText(taskHandler))!;
if (targetConfigs.Any(x => x.isNode))
{
// Task may not have nodejs or packages.json (example: AutomatedAnalysisV0)
if (!HasNodeHandler(taskHandlerContents))
{
Console.WriteLine($"Skipping {task} because task doesn't have node handler does not exist");
return;
}
}
// Create _generated
if (!Directory.Exists(generatedFolder))
{
ensureUpdateModeVerifier!.DirectoryCreateDirectory(generatedFolder, false);
}
foreach (var config in targetConfigs)
{
if (config.useGlobalVersion && !hasGlobalVersion)
{
Console.WriteLine($"Info: MainUpdateTask: Skipping useGlobalVersion config for task b/c GlobalVersion not initialized. (to opt-in and start producing LocalBuildConfig, run with --include-local-packages-build-config. hasGlobalVersion={hasGlobalVersion} config.useGlobalVersion={config.useGlobalVersion}). Note: this is not an error!");
}
else
{
string taskOutput, taskConfigPath;
if (config.enableBuildConfigOverrides)
{
EnsureBuildConfigFileOverrides(config, taskTargetPath);
}
try
{
if (config.useAltGeneratedPath)
{
ensureUpdateModeVerifier.StartUnconditionalWrites(altGeneratedFolder);
}
bool versionUpdated = taskVersionState.versionsUpdated.Contains(config);
if (config.isDefault)
{
taskOutput = Path.Combine(generatedFolder, task);
}
else
{
string directoryName = config.name;
if (config.overriddenDirectoryName != null)
{
directoryName = config.overriddenDirectoryName;
}
if (config.useAltGeneratedPath)
{
if (!Directory.Exists(altGeneratedFolder))
{
ensureUpdateModeVerifier!.DirectoryCreateDirectory(altGeneratedFolder, false);
}
}
string targetGeneratedFolder = config.useAltGeneratedPath ? altGeneratedFolder : generatedFolder;
taskOutput = Path.Combine(targetGeneratedFolder, @$"{task}_{directoryName}");
}
taskConfigPath = Path.Combine(taskOutput, "task.json");
var taskConfigExists = File.Exists(taskConfigPath);
// only update task output if a new version was added, the config exists, the task contains preprocessor instructions, or the config targets Node (not Default)
// Note: CheckTaskInputContainsPreprocessorInstructions is expensive, so only call if needed
if (versionUpdated || taskConfigExists || HasTaskInputContainsPreprocessorInstructions(gitRootPath, taskTargetPath, config) || config.isNode)
{
CopyConfig(gitRootPath, taskTargetPath, taskOutput, skipPathName: buildConfigs, skipFileName: null, removeExtraFiles: true, throwIfNotUpdatingFileForApplyingOverridesAndPreProcessor: false, config: config, allowPreprocessorDirectives: true);
if (config.enableBuildConfigOverrides)
{
CopyConfigOverrides(gitRootPath, taskTargetPath, taskOutput, config);
}
// if some files aren't present in destination, stop as following code assumes they're present and we'll just get a FileNotFoundException
// don't check content as preprocessor hasn't run
ThrowWithUserFriendlyErrorToRerunWithWriteUpdatesIfVeriferError(task, skipContentCheck: true);
HandlePreprocessingInTarget(gitRootPath, taskOutput, config, validateAndWriteChanges: true, hasDirectives: out _);
WriteWIFInputTaskJson(taskOutput, config, "task.json", isLoc: false);
WriteWIFInputTaskJson(taskOutput, config, "task.loc.json", isLoc: true);
WriteTaskJson(taskOutput, taskVersionState.configTaskVersionMapping, config, "task.json");
WriteTaskJson(taskOutput, taskVersionState.configTaskVersionMapping, config, "task.loc.json");
}
WriteInputTaskJson(taskTargetPath, taskVersionState.configTaskVersionMapping, "task.json");
WriteInputTaskJson(taskTargetPath, taskVersionState.configTaskVersionMapping, "task.loc.json");
if (config.isNode)
{
GetBuildConfigFileOverridePaths(config, taskTargetPath, out string configTaskPath, out string readmePath);
string buildConfigPackageJsonPath = Path.Combine(taskTargetPath, buildConfigs, configTaskPath, "package.json");
if (File.Exists(buildConfigPackageJsonPath))
{
EnsureDependencyVersionsAreSyncronized(
task,
Path.Combine(taskTargetPath, "package.json"),
buildConfigPackageJsonPath);
}
WriteNodePackageJson(taskOutput, config.nodePackageVersion, config.shouldUpdateTypescript, config.shouldUpdateLocalPkgs);
}
}
finally
{
ensureUpdateModeVerifier.ResumeWriteBehavior();
}
debugConfigGen.WriteTypescriptConfig(taskOutput);
debugConfigGen.AddForTask(taskConfigPath);
}
}
// delay updating version map file until after buildconfigs generated
WriteVersionMapFile(versionMapFile, taskVersionState.configTaskVersionMapping, targetConfigs: targetConfigs);
ThrowWithUserFriendlyErrorToRerunWithWriteUpdatesIfVeriferError(task, skipContentCheck: false);
}
finally
{
if (ensureUpdateModeVerifier != null)
{
ensureUpdateModeVerifier.CleanupTempFiles();
}
}
}
private static string GetVersionMapFile(string task, string gitRootPath, string generatedFolder)
{
return Path.Combine(generatedFolder, @$"{task}.versionmap.txt");
}
private static HashSet<Config.ConfigRecord> GetConfigRecords(IEnumerable<string> configs, bool writeUpdates)
{
string errorMessage;
Dictionary<string, Config.ConfigRecord> configdefs = new(Config.Configs.Where(x => !x.isDefault).Select(x => new KeyValuePair<string, Config.ConfigRecord>(x.name, x)));
HashSet<Config.ConfigRecord> targetConfigs = new HashSet<Config.ConfigRecord>();
targetConfigs.Add(Config.Default);
foreach (var config in configs)
{
if (configdefs.TryGetValue(config, out var matchedConfig))
{
if (matchedConfig.deprecated && writeUpdates)
{
errorMessage = "The config with the name: " + matchedConfig.name + " is deprecated. Writing updates for deprecated configs is not allowed.";
throw new Exception(errorMessage);
}
targetConfigs.Add(matchedConfig);
}
else
{
errorMessage = $"Configs ({config}) specified must be one of: " + string.Join(',', Config.Configs.Where(x => !x.isDefault).Select(x => x.name));
throw new Exception(errorMessage);
}
}
return targetConfigs;
}
// originVersion buildConfigVersion
private static bool VersionIsGreaterThan(string version1, string version2)
{
if (version2.StartsWith("^"))
{
// if buildConfig version starts with ^, it's always up to date
return false;
}
const string versionRE = @"(\d+)\.(\d+)\.(\d+)";
var originMatch = Regex.Match(version1, versionRE);
var buildConfigMatch = Regex.Match(version2, versionRE);
if (originMatch.Success && buildConfigMatch.Success)
{
var originDependencyVersion = Version.Parse($"{originMatch.Groups[1].Value}.{originMatch.Groups[2].Value}.{originMatch.Groups[3].Value}");
var generatedDependencyVersion = Version.Parse($"{buildConfigMatch.Groups[1].Value}.{buildConfigMatch.Groups[2].Value}.{buildConfigMatch.Groups[3].Value}");
return originDependencyVersion.CompareTo(generatedDependencyVersion) > 0;
}
else
{
if (!originMatch.Success)
{
Console.WriteLine($"VersionIsGreaterThan: {version1} doesn't look like a version");
}
if (!buildConfigMatch.Success)
{
Console.WriteLine($"VersionIsGreaterThan: {version2} doesn't look like a version");
}
}
return false;
}
private static void EnsureDependencyVersionsAreSyncronized(
string task,
string originPackagePath,
string generatedPackagePath
)
{
NotNullOrThrow(ensureUpdateModeVerifier, "BUG: ensureUpdateModeVerifier is null");
JsonNode? originTaskPackage = JsonNode.Parse(ensureUpdateModeVerifier.FileReadAllText(originPackagePath));
JsonNode? buildConfigTaskPackage = JsonNode.Parse(ensureUpdateModeVerifier.FileReadAllText(generatedPackagePath));
NotNullOrThrow(originTaskPackage, $"BUG: originTaskPackage is null for {task}");
NotNullOrThrow(buildConfigTaskPackage, $"BUG: buildConfigTaskPackage is null for {task}");
var originDependencies = originTaskPackage["dependencies"];
NotNullOrThrow(originDependencies, $"BUG: origin dependencies in {task} is null");
foreach (var originDependency in originDependencies.AsObject())
{
string? originVersion = originDependency.Value?.ToString();
NotNullOrThrow(originVersion, $"BUG: origin dependency {originDependency.Key} version in {task} is null");
var buildConfigTaskDependencies = buildConfigTaskPackage["dependencies"];
NotNullOrThrow(buildConfigTaskDependencies, $"BUG: buildConfigs dependencies in {task} is null");
string? buildConfigDependencyVersion = buildConfigTaskDependencies[originDependency.Key]?.ToString();
if (buildConfigDependencyVersion is null)
{
notSyncronizedDependencies.Add($@"Dependency ""{originDependency.Key}"" in {task} is missing in buildConfig's package.json");
continue;
}
if (buildConfigDependencyVersion.StartsWith("file:")) // skip if config package is file reference
{
// do nothing
}
else
{
if (VersionIsGreaterThan(originVersion, buildConfigDependencyVersion))
{
notSyncronizedDependencies.Add($@"Dependency ""{originDependency.Key}"" in {generatedPackagePath} has {buildConfigDependencyVersion} version and should be updated to {originVersion} as in {originPackagePath}");
}
}
}
}
private static bool HasTaskInputContainsPreprocessorInstructions(string gitRootPath, string sourcePath, Config.ConfigRecord config)
{
HandlePreprocessingInTarget(gitRootPath, sourcePath, config, validateAndWriteChanges: false, hasDirectives: out bool hasPreprocessorDirectives);
return hasPreprocessorDirectives;
}
private static void EnsureBuildConfigFileOverrides(Config.ConfigRecord config, string taskTargetPath)
{
if (!config.enableBuildConfigOverrides)
{
throw new Exception("BUG: should not get here: !config.enableBuildConfigOverrides");
}
string path, readmeFile;
GetBuildConfigFileOverridePaths(config, taskTargetPath, out path, out readmeFile);
if (!Directory.Exists(path))
{
ensureUpdateModeVerifier!.DirectoryCreateDirectory(path, suppressValidationErrorIfTargetPathDoesntExist: !Knob.Default.SourceDirectoriesMustContainPlaceHolders);
}
ensureUpdateModeVerifier!.WriteAllText(readmeFile, "Place files overridden for this config in this directory", suppressValidationErrorIfTargetPathDoesntExist: !Knob.Default.SourceDirectoriesMustContainPlaceHolders);
}
private static void GetBuildConfigFileOverridePaths(Config.ConfigRecord config, string taskTargetPath, out string path, out string readmeFile)
{
string directoryName = config.name;
if (!config.enableBuildConfigOverrides)
{
throw new Exception("BUG: should not get here: !config.enableBuildConfigOverrides");
}
if (config.overriddenDirectoryName != null)
{
directoryName = config.overriddenDirectoryName;
}
path = Path.Combine(taskTargetPath, buildConfigs, directoryName);
readmeFile = Path.Combine(taskTargetPath, buildConfigs, directoryName, filesOverriddenForConfigGoHereReadmeTxt);
}
private static void CopyConfigOverrides(string gitRootPath, string taskTargetPath, string taskOutput, Config.ConfigRecord config)
{
if (!config.enableBuildConfigOverrides)
{
throw new Exception("BUG: should not get here: !config.enableBuildConfigOverrides");
}
string overridePathForBuildConfig;
GetBuildConfigFileOverridePaths(config, taskTargetPath, out overridePathForBuildConfig, out _);
bool doCopy;
if (Knob.Default.SourceDirectoriesMustContainPlaceHolders)
{
doCopy = false;
}
else
{
doCopy = Directory.Exists(overridePathForBuildConfig);
}
if (doCopy)
{
CopyConfig(gitRootPath, overridePathForBuildConfig, taskOutput, skipPathName: null, skipFileName: filesOverriddenForConfigGoHereReadmeTxt, removeExtraFiles: false, throwIfNotUpdatingFileForApplyingOverridesAndPreProcessor: true, config: config, allowPreprocessorDirectives: false);
}
}
private static void HandlePreprocessingInTarget(string gitRootPath, string taskOutput, Config.ConfigRecord config, bool validateAndWriteChanges, out bool hasDirectives)
{
var nonIgnoredFilesInTarget = new HashSet<string>(GitUtil.GetNonIgnoredFileListFromPath(gitRootPath, taskOutput));
hasDirectives = false;
foreach (var file in nonIgnoredFilesInTarget)
{
string taskOutputFile = Path.Combine(taskOutput, file);
PreprocessIfExtensionEnabledInConfig(taskOutputFile, config, validateAndWriteChanges, out bool madeChanges);
if (madeChanges)
{
hasDirectives = true;
}
}
}
private static void PreprocessIfExtensionEnabledInConfig(string file, Config.ConfigRecord config, bool validateAndWriteChanges, out bool madeChanges)
{
HashSet<string> extensions = new HashSet<string>(Config.ExtensionsToPreprocess);
bool preprocessExtension = extensions.Contains(Path.GetExtension(file));
if (preprocessExtension)
{
if (validateAndWriteChanges)
{
Console.WriteLine($"Preprocessing {file}...");
}
else
{
Console.WriteLine($"Checking if {file} has preprocessor directives ...");
}
Preprocessor.Preprocess(file, ensureUpdateModeVerifier!.FileReadAllLines(file), new HashSet<string>(Config.Configs.Select(s => s.preprocessorVariableName)), config.preprocessorVariableName, out string processedOutput, out var validationErrors, out madeChanges);
if (validateAndWriteChanges)
{
if (validationErrors.Count() != 0)
{
Console.WriteLine("Preprocessor validation errors:");
foreach (var error in validationErrors)
{
Console.WriteLine(error);
}
throw new Exception("Preprocessor validation errors occured");
}
if (madeChanges)
{
ensureUpdateModeVerifier!.WriteAllText(file, processedOutput, false);
Console.WriteLine("Done");
}
else
{
Console.WriteLine("No changes; skipping");
}
}
}
else
{
madeChanges = false;
}
}
private static void WriteTaskJson(string taskPath, Dictionary<Config.ConfigRecord, TaskVersion> configTaskVersionMapping, Config.ConfigRecord config, string fileName)
{
string outputTaskPath = Path.Combine(taskPath, fileName);
JsonNode outputTaskNode = JsonNode.Parse(ensureUpdateModeVerifier!.FileReadAllText(outputTaskPath))!;
outputTaskNode["version"]!["Major"] = configTaskVersionMapping[config].Major;
outputTaskNode["version"]!["Minor"] = configTaskVersionMapping[config].Minor;
outputTaskNode["version"]!["Patch"] = configTaskVersionMapping[config].Patch;
outputTaskNode.AsObject()?.Remove("_buildConfigMapping");
JsonObject configMapping = new JsonObject();
var configTaskVersionMappingSortedByConfig = configTaskVersionMapping.OrderBy(x => x.Key.name);
foreach (var cfg in configTaskVersionMappingSortedByConfig)
{
configMapping.Add(new(cfg.Key.constMappingKey, cfg.Value.ToString()));
}
outputTaskNode.AsObject().Add("_buildConfigMapping", configMapping);
if (config.isNode)
{
AddNodehandler(outputTaskNode, config.nodeHandler);
}
ensureUpdateModeVerifier!.WriteAllText(outputTaskPath, outputTaskNode.ToJsonString(jso), suppressValidationErrorIfTargetPathDoesntExist: false);
}
private static void WriteWIFInputTaskJson(string taskPath, Config.ConfigRecord config, string fileName, bool isLoc)
{
if (!config.isWif)
{
return;
}
string taskJsonOverridePath = Path.Combine(taskPath, isLoc ? "taskJsonOverride.loc.json" : "taskJsonOverride.json");
JsonNode inputTaskNode = JsonNode.Parse(ensureUpdateModeVerifier!.FileReadAllText(taskJsonOverridePath))!;
var clonedArray = JsonNode.Parse(inputTaskNode["inputs"]!.ToJsonString())!.AsArray();
string outputTaskPath = Path.Combine(taskPath, fileName);
JsonNode outputTaskNode = JsonNode.Parse(ensureUpdateModeVerifier!.FileReadAllText(outputTaskPath))!;
outputTaskNode["inputs"] = clonedArray;
ensureUpdateModeVerifier!.WriteAllText(outputTaskPath, outputTaskNode.ToJsonString(jso), suppressValidationErrorIfTargetPathDoesntExist: false);
}
private static void WriteNodePackageJson(string taskOutputNode, string nodeVersion, bool shouldUpdateTypescript, bool shouldUpdateTaskLib)
{
string outputNodePackagePath = Path.Combine(taskOutputNode, "package.json");
JsonNode outputNodePackagePathJsonNode = JsonNode.Parse(ensureUpdateModeVerifier!.FileReadAllText(outputNodePackagePath))!;
outputNodePackagePathJsonNode["dependencies"]!["@types/node"] = nodeVersion;
// Upgrade typescript version for Node 20
if (shouldUpdateTypescript)
{
outputNodePackagePathJsonNode["devDependencies"]!["typescript"] = "5.1.6";
}
if (shouldUpdateTaskLib)
{
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-task-lib", "file:../../task-lib/node/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-artifacts-common", "file:../../tasks-common/common-npm-packages/artifacts-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azp-tasks-az-blobstorage-provider", "file:../../tasks-common/common-npm-packages/az-blobstorage-provider/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-azure-arm-rest", "file:../../tasks-common/common-npm-packages/azure-arm-rest/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-azurermdeploycommon", "file:../../tasks-common/common-npm-packages/azurermdeploycommon/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-codeanalysis-common", "file:../../tasks-common/common-npm-packages/codeanalysis-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-codecoverage-tools", "file:../../tasks-common/common-npm-packages/codecoverage-tools/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-docker-common", "file:../../tasks-common/common-npm-packages/docker-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-ios-signing-common", "file:../../tasks-common/common-npm-packages/ios-signing-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-java-common", "file:../../tasks-common/common-npm-packages/java-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-kubernetes-common", "file:../../tasks-common/common-npm-packages/kubernetes-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-msbuildhelpers", "file:../../tasks-common/common-npm-packages/msbuildhelpers/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-packaging-common", "file:../../tasks-common/common-npm-packages/packaging-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-securefiles-common", "file:../../tasks-common/common-npm-packages/securefiles-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-utility-common", "file:../../tasks-common/common-npm-packages/utility-common/_build");
UpdateDepNode(outputNodePackagePathJsonNode, "azure-pipelines-tasks-webdeployment-common", "file:../../tasks-common/common-npm-packages/webdeployment-common/_build");
}
// We need to add newline since npm install command always add newline at the end of package.json
// https://github.com/npm/npm/issues/18545
string nodePackageContent = outputNodePackagePathJsonNode.ToJsonString(jso) + Environment.NewLine;
ensureUpdateModeVerifier!.WriteAllText(outputNodePackagePath, nodePackageContent, suppressValidationErrorIfTargetPathDoesntExist: false);
}
private static void UpdateDepNode(JsonNode outputNodePackagePathJsonNode, string module, string buildPath)
{
var depNode = outputNodePackagePathJsonNode["dependencies"];
var f = depNode![module];
if (f != null)
{
outputNodePackagePathJsonNode["dependencies"]![module] = buildPath;
}
}
private static bool HasNodeHandler(JsonNode taskHandlerContents)
{
var possibleExecutionHandlers = new[] { "prejobexecution", "execution", "postjobexecution" };
foreach (var possibleExecutor in possibleExecutionHandlers)
{
var handlers = taskHandlerContents[possibleExecutor]?.AsObject();
if (ExecutorHasNodeHandler(handlers)) { return true; }
}
return false;
}
private static bool ExecutorHasNodeHandler(JsonObject? executorHandlerContent)
{
if (executorHandlerContent == null) { return false; }
foreach (var k in executorHandlerContent)
{
if (k.Key.ToLower().StartsWith("node"))
{
return true;
}
}
return false;
}
private static void CopyConfig(string gitRootPath, string taskTargetPathOrUnderscoreBuildConfigPath, string taskOutput, string? skipPathName, string? skipFileName, bool removeExtraFiles, bool throwIfNotUpdatingFileForApplyingOverridesAndPreProcessor, Config.ConfigRecord config, bool allowPreprocessorDirectives)
{
var paths = GitUtil.GetNonIgnoredFileListFromPath(gitRootPath, taskTargetPathOrUnderscoreBuildConfigPath);
HashSet<string> pathsToRemoveFromOutput;
// In case if task was not generated yet, we don't need to get the list of files to remove, because taskOutput not exists yet
if (Directory.Exists(taskOutput) && !config.useAltGeneratedPath /* exclude alt which is .gitignore */)
{
pathsToRemoveFromOutput = new HashSet<string>(GitUtil.GetNonIgnoredFileListFromPath(gitRootPath, taskOutput));
}
else
{
pathsToRemoveFromOutput = new HashSet<string>();
}
if (allowPreprocessorDirectives)
{
// do nothing
}
else
{
if (!config.enableBuildConfigOverrides)
{
throw new Exception("BUG: should not get here: !config.enableBuildConfigOverrides");
}
var hasPreprocessorDirectives = HasTaskInputContainsPreprocessorInstructions(gitRootPath, taskTargetPathOrUnderscoreBuildConfigPath, config);
if (hasPreprocessorDirectives)
{
throw new Exception($"Preprocessor directives not supported in files in _buildConfigs taskTargetPathOrUnderscoreBuildConfigPath={taskTargetPathOrUnderscoreBuildConfigPath}");
}
}
foreach (var path in paths)
{
string sourcePath = Path.Combine(taskTargetPathOrUnderscoreBuildConfigPath, path);
if (skipPathName != null && sourcePath.Contains(string.Concat(skipPathName, Path.DirectorySeparatorChar)))
{
// skip the path! (this is used to skip _buildConfigs in the source task path)
}
else
{
_ = pathsToRemoveFromOutput.Remove(path);
string targetPath = Path.Combine(taskOutput, path);
if (skipFileName != null && sourcePath.Contains(string.Concat(Path.DirectorySeparatorChar.ToString(), skipFileName), StringComparison.OrdinalIgnoreCase))
{
// e.g. skip filesOverriddenForConfigGoHereReadmeTxt
}
else
{
if (throwIfNotUpdatingFileForApplyingOverridesAndPreProcessor && !File.Exists(targetPath))
{
throw new Exception($"Overriden file must exist in targetPath sourcePath={sourcePath} targetPath={targetPath}");
}