-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNugetUtilProgram.cs
More file actions
630 lines (543 loc) · 25.8 KB
/
Copy pathNugetUtilProgram.cs
File metadata and controls
630 lines (543 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
using System.Reflection;
internal static class NugetUtilProgram
{
public static async Task<int> RunAsync(string[] args)
{
try
{
if (args.Any(a => string.Equals(a, "-h", StringComparison.OrdinalIgnoreCase) ||
string.Equals(a, "--help", StringComparison.OrdinalIgnoreCase) ||
string.Equals(a, "/?", StringComparison.OrdinalIgnoreCase)))
{
PrintUsage();
return ExitCodes.Success;
}
if (args.Any(a => string.Equals(a, "-v", StringComparison.OrdinalIgnoreCase) ||
string.Equals(a, "--version", StringComparison.OrdinalIgnoreCase)))
{
Console.WriteLine($"NugetUtil {GetToolVersion()}");
return ExitCodes.Success;
}
var parse = CliOptions.Parse(args);
if (!parse.Success)
{
Console.Error.WriteLine(parse.Error);
PrintUsage();
return ExitCodes.InvalidArgsOrConfig;
}
var options = parse.Options!;
Console.WriteLine($"Root path: {options.RootPath}");
var configResult = ConfigLoader.Load();
if (!configResult.Success)
{
Console.Error.WriteLine(configResult.Error);
return ExitCodes.InvalidArgsOrConfig;
}
var config = configResult.Config!;
var configuredOutput = string.IsNullOrWhiteSpace(options.OutputFolderOverride)
? (config.Behavior.OutputFolder ?? "artifacts\\nuget")
: options.OutputFolderOverride;
var effectiveSkipDuplicate = options.SkipDuplicateRequested || (config.Behavior.SkipDuplicate ?? true);
var outputFolder = Path.IsPathRooted(configuredOutput)
? configuredOutput
: Path.GetFullPath(Path.Combine(options.RootPath, configuredOutput));
Directory.CreateDirectory(outputFolder);
if (!string.IsNullOrWhiteSpace(options.DeployablePackagePath))
{
Console.WriteLine($"Dynamics 365 FO deployable package mode: {options.DeployablePackagePath}");
var foSources = ResolveFoPackageSources(options.DeployablePackagePath, options.ModelFilter);
if (!foSources.Success)
{
Console.Error.WriteLine(foSources.Error);
return ExitCodes.PackFailed;
}
var foPackResults = new List<FoDeployablePackResult>();
foreach (var sourcePath in foSources.SourcePaths!)
{
if (foSources.SourcePaths.Count > 1)
{
Console.WriteLine();
Console.WriteLine($"Packaging model folder: {sourcePath}");
}
var foPackResult = await FoDeployablePackageService.BuildAsync(
packageSourcePath: sourcePath,
outputFolder: outputFolder,
workingDirectory: options.RootPath,
saveNuspecToOutput: options.SaveFoNuspec,
isolateExportFolder: foSources.SourcePaths.Count > 1,
whatIf: options.WhatIf);
if (!foPackResult.Success)
{
Console.Error.WriteLine(foPackResult.Error);
return ExitCodes.PackFailed;
}
foPackResults.Add(foPackResult);
Console.WriteLine($"- PackageId: {foPackResult.PackageId}");
Console.WriteLine($"- Version: {foPackResult.Version}");
Console.WriteLine($"- Packed: {foPackResult.NupkgPath}");
if (!string.IsNullOrWhiteSpace(foPackResult.ExportedNuspecPath))
{
Console.WriteLine($"- Nuspec: {foPackResult.ExportedNuspecPath}");
}
}
if (!options.Push)
{
return ExitCodes.Success;
}
var foSourceName = string.IsNullOrWhiteSpace(options.Source) ? config.DefaultSource : options.Source;
if (string.IsNullOrWhiteSpace(foSourceName))
{
Console.Error.WriteLine("No source provided and no defaultSource set in config.");
return ExitCodes.InvalidArgsOrConfig;
}
var hasFoConfigSource = config.Sources.TryGetValue(foSourceName, out var foSourceConfig);
if (!hasFoConfigSource && string.IsNullOrWhiteSpace(options.ApiKey))
{
Console.Error.WriteLine($"Source '{foSourceName}' not found in config.");
return ExitCodes.InvalidArgsOrConfig;
}
var foApiKey = string.IsNullOrWhiteSpace(options.ApiKey) ? foSourceConfig?.ApiKey : options.ApiKey;
if (string.IsNullOrWhiteSpace(foApiKey))
{
Console.Error.WriteLine($"Source '{foSourceName}' must define apiKey.");
return ExitCodes.InvalidArgsOrConfig;
}
Console.WriteLine();
Console.WriteLine($"Push source: {foSourceName}");
var foNupkgPaths = foPackResults.Select(result => result.NupkgPath)
.Where(path => !string.IsNullOrWhiteSpace(path))
.Cast<string>()
.ToList();
if (foNupkgPaths.Count != foPackResults.Count)
{
Console.Error.WriteLine("One or more Dynamics 365 FO package paths are empty after packing.");
return ExitCodes.PackFailed;
}
if (!options.Yes && !options.WhatIf)
{
Console.Write($"Push {foNupkgPaths.Count} package(s)? [y/N]: ");
var answer = Console.ReadLine();
if (!string.Equals(answer, "y", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(answer, "yes", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Push cancelled.");
return ExitCodes.Success;
}
}
foreach (var foNupkgPath in foNupkgPaths)
{
var pushArgs = new List<string>
{
"push",
foNupkgPath,
"--source",
foSourceName,
"--api-key",
foApiKey,
"--interactive"
};
if (effectiveSkipDuplicate)
{
pushArgs.Add("--skip-duplicate");
}
var pushResult = await ProcessRunner.RunAsync(
fileName: "dotnet",
arguments: ["nuget", .. pushArgs],
workingDirectory: options.RootPath,
whatIf: options.WhatIf,
sensitiveValues: [foApiKey]);
if (!pushResult.Success)
{
return ExitCodes.PushFailed;
}
}
return ExitCodes.Success;
}
var discovery = ProjectDiscovery.Discover(options, config);
if (!discovery.Success)
{
Console.Error.WriteLine(discovery.Error);
return ExitCodes.InvalidArgsOrConfig;
}
var allProjects = discovery.Projects!;
var packageProjects = allProjects.Values.Where(p => p.IsPackage).OrderBy(p => p.Path, StringComparer.OrdinalIgnoreCase).ToList();
if (packageProjects.Count == 0)
{
Console.WriteLine("No package projects found.");
return ExitCodes.Success;
}
HashSet<string>? selectedPackagePathSet = null;
if (options.AutoBump)
{
if (options.Force)
{
Console.WriteLine("Auto bump force mode enabled: bumping all discovered packages.");
}
var autoBumpResult = AutoBumpService.Apply(
rootPath: options.RootPath,
allProjects: allProjects,
packageProjects: packageProjects,
bumpLevel: options.BumpLevel,
forceAll: options.Force,
whatIf: options.WhatIf);
if (!autoBumpResult.Success)
{
Console.Error.WriteLine(autoBumpResult.Error);
return ExitCodes.InvalidArgsOrConfig;
}
var bumped = autoBumpResult.BumpedVersions!;
if (bumped.Count == 0)
{
Console.WriteLine("No package updates detected.");
return ExitCodes.Success;
}
Console.WriteLine("Auto bump packages:");
foreach (var package in packageProjects.Where(p => bumped.ContainsKey(p.Path)).OrderBy(p => p.Path, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine($"- {package.PackageId}: {package.Version} -> {bumped[package.Path]}");
}
selectedPackagePathSet = bumped.Keys.ToHashSet(StringComparer.OrdinalIgnoreCase);
if (!options.WhatIf)
{
var refreshedDiscovery = ProjectDiscovery.Discover(options, config);
if (!refreshedDiscovery.Success)
{
Console.Error.WriteLine(refreshedDiscovery.Error);
return ExitCodes.InvalidArgsOrConfig;
}
allProjects = refreshedDiscovery.Projects!;
packageProjects = allProjects.Values.Where(p => p.IsPackage).OrderBy(p => p.Path, StringComparer.OrdinalIgnoreCase).ToList();
}
else
{
allProjects = allProjects.ToDictionary(
kv => kv.Key,
kv => bumped.TryGetValue(kv.Key, out var newVersion)
? kv.Value with { Version = newVersion }
: kv.Value,
StringComparer.OrdinalIgnoreCase);
packageProjects = allProjects.Values.Where(p => p.IsPackage).OrderBy(p => p.Path, StringComparer.OrdinalIgnoreCase).ToList();
}
}
else
{
if (options.Force)
{
selectedPackagePathSet = packageProjects.Select(p => p.Path).ToHashSet(StringComparer.OrdinalIgnoreCase);
Console.WriteLine("Force mode enabled: processing all discovered packages.");
}
else
{
var changedPackagesResult = AutoBumpService.DetectChangedPackages(options.RootPath, allProjects, packageProjects);
if (!changedPackagesResult.Success)
{
Console.Error.WriteLine(changedPackagesResult.Error);
return ExitCodes.InvalidArgsOrConfig;
}
var changedPaths = changedPackagesResult.PackagePaths!;
if (changedPaths.Count == 0)
{
Console.WriteLine("No package updates detected.");
if (!options.Push)
{
return ExitCodes.Success;
}
Console.WriteLine("Push requested: looking for existing packages in output folder.");
selectedPackagePathSet = [];
}
else
{
selectedPackagePathSet = changedPaths.ToHashSet(StringComparer.OrdinalIgnoreCase);
Console.WriteLine("Changed packages:");
foreach (var package in packageProjects.Where(p => selectedPackagePathSet.Contains(p.Path)).OrderBy(p => p.Path, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine($"- {package.PackageId} ({package.Version})");
}
}
}
}
var discoveredPackageIds = packageProjects
.Select(p => p.PackageId)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var latestPackageVersions = packageProjects
.GroupBy(p => p.PackageId, StringComparer.OrdinalIgnoreCase)
.ToDictionary(
g => g.Key,
g => g.Select(p => p.Version).OrderByDescending(v => v, NugetVersionComparer.Instance).First(),
StringComparer.OrdinalIgnoreCase);
if (selectedPackagePathSet is not null)
{
packageProjects = packageProjects
.Where(p => selectedPackagePathSet.Contains(p.Path))
.OrderBy(p => p.Path, StringComparer.OrdinalIgnoreCase)
.ToList();
}
Console.WriteLine("Discovered packages:");
foreach (var package in packageProjects)
{
Console.WriteLine($"- {package.PackageId} ({package.Path})");
}
var createdPackages = new List<string>();
foreach (var package in packageProjects)
{
Console.WriteLine();
Console.WriteLine($"Processing package: {package.PackageId}");
Console.WriteLine($"- Version: {package.Version}");
Console.WriteLine($"- TFM: {package.TargetFramework}");
var directReferencedProjects = package.ProjectReferences
.Select(pr => allProjects.TryGetValue(pr, out var found) ? found : null)
.Where(p => p is not null)
.Cast<ProjectInfo>()
.ToList();
var nonPackableRefs = directReferencedProjects.Where(p => !p.IsPackage).ToList();
if (nonPackableRefs.Count > 0)
{
Console.WriteLine($"- Nuspec mode required: references non-packable: {string.Join(", ", nonPackableRefs.Select(r => r.ProjectName))}");
}
else
{
Console.WriteLine("- Nuspec mode not required by references, using nuspec mode by default.");
}
var buildResult = await ProcessRunner.RunAsync(
fileName: "dotnet",
arguments: ["build", package.Path, "-c", options.Configuration],
workingDirectory: options.RootPath,
whatIf: options.WhatIf,
sensitiveValues: [],
printOutputOnSuccess: options.VerboseBuildOutput);
if (!buildResult.Success)
{
return ExitCodes.BuildFailed;
}
if (!options.VerboseBuildOutput)
{
Console.WriteLine("- Build: succeeded");
}
var dependencyResult = NuspecGenerator.BuildDependencies(package, allProjects, latestPackageVersions);
if (!dependencyResult.Success)
{
Console.Error.WriteLine(dependencyResult.Error);
return ExitCodes.InvalidArgsOrConfig;
}
var nuspecPath = Path.Combine(Path.GetDirectoryName(package.Path)!, $"{package.PackageId}.nuspec");
var nuspecWriteResult = NuspecGenerator.WriteNuspec(
nuspecPath,
package,
dependencyResult.Dependencies!,
nonPackableRefs,
options.Configuration);
if (!nuspecWriteResult.Success)
{
Console.Error.WriteLine(nuspecWriteResult.Error);
return ExitCodes.PackFailed;
}
Console.WriteLine($"- Nuspec: {nuspecPath}");
var packResult = await ProcessRunner.RunAsync(
fileName: "dotnet",
arguments:
[
"pack",
nuspecPath,
"-o",
outputFolder
],
workingDirectory: options.RootPath,
whatIf: options.WhatIf,
sensitiveValues: []);
if (!packResult.Success)
{
return ExitCodes.PackFailed;
}
var nupkgPath = Path.Combine(outputFolder, $"{package.PackageId}.{package.Version}.nupkg");
if (!options.WhatIf && !File.Exists(nupkgPath))
{
Console.Error.WriteLine($"Pack succeeded but expected file not found: {nupkgPath}");
return ExitCodes.PackFailed;
}
Console.WriteLine($"- Packed: {nupkgPath}");
createdPackages.Add(nupkgPath);
}
if (!options.Push)
{
if (!options.WhatIf)
{
var stateUpdateResult = AutoBumpService.SaveState(options.RootPath, allProjects, allProjects.Values.Where(p => p.IsPackage).ToList());
if (!stateUpdateResult.Success)
{
Console.Error.WriteLine(stateUpdateResult.Error);
return ExitCodes.InvalidArgsOrConfig;
}
}
return ExitCodes.Success;
}
var sourceName = string.IsNullOrWhiteSpace(options.Source) ? config.DefaultSource : options.Source;
if (string.IsNullOrWhiteSpace(sourceName))
{
Console.Error.WriteLine("No source provided and no defaultSource set in config.");
return ExitCodes.InvalidArgsOrConfig;
}
var hasConfigSource = config.Sources.TryGetValue(sourceName, out var sourceConfig);
if (!hasConfigSource && string.IsNullOrWhiteSpace(options.ApiKey))
{
Console.Error.WriteLine($"Source '{sourceName}' not found in config.");
return ExitCodes.InvalidArgsOrConfig;
}
var apiKey = string.IsNullOrWhiteSpace(options.ApiKey) ? sourceConfig?.ApiKey : options.ApiKey;
if (string.IsNullOrWhiteSpace(apiKey))
{
Console.Error.WriteLine($"Source '{sourceName}' must define apiKey.");
return ExitCodes.InvalidArgsOrConfig;
}
Console.WriteLine();
Console.WriteLine($"Push source: {sourceName}");
var packagesToPush = new List<string>(createdPackages);
if (packagesToPush.Count == 0)
{
var fallbackPackages = FindExistingPackagesToPush(outputFolder, discoveredPackageIds);
packagesToPush.AddRange(fallbackPackages);
if (packagesToPush.Count == 0)
{
Console.WriteLine("No matching existing packages found to push.");
return ExitCodes.Success;
}
Console.WriteLine($"Using existing packages from output folder: {packagesToPush.Count}");
foreach (var path in packagesToPush)
{
Console.WriteLine($"- {path}");
}
}
if (!options.Yes && !options.WhatIf)
{
Console.Write($"Push {packagesToPush.Count} package(s)? [y/N]: ");
var answer = Console.ReadLine();
if (!string.Equals(answer, "y", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(answer, "yes", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Push cancelled.");
return ExitCodes.Success;
}
}
foreach (var nupkg in packagesToPush)
{
var pushArgs = new List<string>
{
"push",
nupkg,
"--source",
sourceName,
"--api-key",
apiKey,
"--interactive"
};
if (effectiveSkipDuplicate)
{
pushArgs.Add("--skip-duplicate");
}
var pushResult = await ProcessRunner.RunAsync(
fileName: "dotnet",
arguments: ["nuget", .. pushArgs],
workingDirectory: options.RootPath,
whatIf: options.WhatIf,
sensitiveValues: [apiKey]);
if (!pushResult.Success)
{
return ExitCodes.PushFailed;
}
}
if (!options.WhatIf)
{
var stateUpdateResult = AutoBumpService.SaveState(options.RootPath, allProjects, allProjects.Values.Where(p => p.IsPackage).ToList());
if (!stateUpdateResult.Success)
{
Console.Error.WriteLine(stateUpdateResult.Error);
return ExitCodes.InvalidArgsOrConfig;
}
}
return ExitCodes.Success;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return ExitCodes.InvalidArgsOrConfig;
}
}
private static void PrintUsage()
{
Console.WriteLine($"NugetUtil {GetToolVersion()}");
Console.WriteLine("Usage: nugetutil [\"<path>\"] [options]");
Console.WriteLine(" or: nugetutil fopack \"<source>\" [options] (Dynamics 365 FO zip, model folder, or parent folder)");
Console.WriteLine(" <path> = optional repository root path (defaults to current directory)");
Console.WriteLine("Options:");
Console.WriteLine(" -save-nuspec (with fopack or -deployable-package, save generated nuspec to output)");
Console.WriteLine(" -filter \"<glob>\" (with fopack parent folder, match child model folder names)");
Console.WriteLine(" -push");
Console.WriteLine(" -source \"<name>\" (NuGet source name, e.g. \"MyFeed\")");
Console.WriteLine(" -configuration Release|Debug");
Console.WriteLine(" -output \"<folder>\"");
Console.WriteLine(" -skip-duplicate");
Console.WriteLine(" -verbose-build");
Console.WriteLine(" -force");
Console.WriteLine(" -autobump");
Console.WriteLine(" -bumplevel patch|minor|major");
Console.WriteLine(" -dryrun");
Console.WriteLine(" -yes");
Console.WriteLine(" -include \"<glob>\" (repeatable)");
Console.WriteLine(" -exclude \"<glob>\" (repeatable)");
Console.WriteLine(" -v|--version");
}
private static string GetToolVersion()
{
var assembly = typeof(NugetUtilProgram).Assembly;
var info = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
if (!string.IsNullOrWhiteSpace(info))
{
var plusIndex = info.IndexOf('+');
return plusIndex > 0 ? info[..plusIndex] : info;
}
return assembly.GetName().Version?.ToString() ?? "unknown";
}
private static FoPackageSourceResolution ResolveFoPackageSources(string sourcePath, string? filter)
{
if (File.Exists(sourcePath) || FoDeployablePackageService.IsFoModelDirectory(sourcePath))
{
return FoPackageSourceResolution.Ok([sourcePath]);
}
if (!Directory.Exists(sourcePath))
{
return FoPackageSourceResolution.Fail($"Dynamics 365 FO package source does not exist: {sourcePath}");
}
var modelDirectories = FoDeployablePackageService.DiscoverModelDirectories(sourcePath, filter);
if (modelDirectories.Count == 0)
{
var filterText = string.IsNullOrWhiteSpace(filter)
? string.Empty
: $" matching filter '{filter}'";
return FoPackageSourceResolution.Fail($"No Dynamics 365 FO model folders found under '{sourcePath}'{filterText}.");
}
return FoPackageSourceResolution.Ok(modelDirectories);
}
private static IReadOnlyList<string> FindExistingPackagesToPush(string outputFolder, IReadOnlySet<string> discoveredPackageIds)
{
if (!Directory.Exists(outputFolder) || discoveredPackageIds.Count == 0)
{
return [];
}
return Directory.EnumerateFiles(outputFolder, "*.nupkg", SearchOption.TopDirectoryOnly)
.Where(path =>
{
var name = Path.GetFileName(path);
if (name.Contains(".symbols.", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return discoveredPackageIds.Any(id => name.StartsWith(id + ".", StringComparison.OrdinalIgnoreCase));
})
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase)
.ToList();
}
}
internal sealed record FoPackageSourceResolution(bool Success, IReadOnlyList<string>? SourcePaths, string? Error)
{
public static FoPackageSourceResolution Ok(IReadOnlyList<string> sourcePaths) => new(true, sourcePaths, null);
public static FoPackageSourceResolution Fail(string error) => new(false, null, error);
}