Datei: Make/build.cs

Last Commit (74c26c3)
1 -- File didn't exist --
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
New Commit (37abc99)
1 // NDO build script. The concept is described in Concepts/BuildProcess.md.
2 //
3 // Usage: dotnet run Make/build.cs [options]
4 //
5 //·· --dry-run············Show detected changes, propagated bumps, all file edits
6 //························and the build plan; change nothing.
7 //·· --no-build·········· Patch versions and references only.
8 //·· --all················Build all packages and all consumers.
9 //·· --only <id>··········Build only this package (repeatable); consumers that
10 //························depend on it are built as well.
11 //·· --rebuild <id>······ Rebuild a package without a version change (repeatable).
12 //·· --no-consumers······ Don't build consumers.
13 //·· --test·············· Run 'dotnet test' on the built test projects.
14 //·· --bump patch|minor·· Propagation policy (default: "propagation" in the manifest).
15 //·· -c <config>··········Configuration of packages (default: manifest).
16
17 using System.Diagnostics;
18 using System.Text;
19 using System.Text.Json;
20 using System.Text.Json.Nodes;
21 using System.Text.RegularExpressions;
22 using System.Xml.Linq;
23
24 try
25 {
26 ····return new Build(Options.Parse(args)).Run();
27 }
28 catch (BuildException ex)
29 {
30 ····Console.Error.WriteLine();
31 ····Console.Error.WriteLine("ERROR: " + ex.Message);
32 ····return 1;
33 }
34
35 class Options
36 {
37 ····public bool DryRun, NoBuild, All, NoConsumers, Test;
38 ····public List<string> Only = new(), Rebuild = new();
39 ····public string? Bump, Configuration;
40
41 ····public static Options Parse(string[] args)
42 ····{
43 ········var o = new Options();
44 ········for (int i = 0; i < args.Length; i++)
45 ········{
46 ············string Next() => i + 1 < args.Length ? args[++i] : throw new BuildException($"Option {args[i]} needs a value.");
47 ············switch (args[i])
48 ············{
49 ················case "--dry-run": o.DryRun = true; break;
50 ················case "--no-build": o.NoBuild = true; break;
51 ················case "--all": o.All = true; break;
52 ················case "--only": o.Only.Add(Next()); break;
53 ················case "--rebuild": o.Rebuild.Add(Next()); break;
54 ················case "--no-consumers": o.NoConsumers = true; break;
55 ················case "--test": o.Test = true; break;
56 ················case "--bump": o.Bump = Next(); break;
57 ················case "-c": case "--configuration": o.Configuration = Next(); break;
58 ················default: throw new BuildException($"Unknown option '{args[i]}'.");
59 ············}
60 ········}
61 ········return o;
62 ····}
63 }
64
65 class BuildException(string message) : Exception(message);
66
67 /// <summary>A version without pre-release suffix. A 4th part is accepted if it is 0.</summary>
68 readonly record struct PackageVersion(int Major, int Minor, int Patch) : IComparable<PackageVersion>
69 {
70 ····public static PackageVersion Parse(string s, string context)
71 ····{
72 ········if (!TryParse(s, out var v))
73 ············throw new BuildException($"{context}: '{s}' is not a version of the form major.minor.patch.");
74 ········return v;
75 ····}
76
77 ····public static bool TryParse(string s, out PackageVersion v)
78 ····{
79 ········v = default;
80 ········var parts = s.Trim().Split('.');
81 ········if (parts.Length < 2 || parts.Length > 4)
82 ············return false;
83 ········var n = new int[4];
84 ········for (int i = 0; i < parts.Length; i++)
85 ············if (!int.TryParse(parts[i], out n[i]) || n[i] < 0)
86 ················return false;
87 ········if (n[3] != 0)
88 ············return false;
89 ········v = new PackageVersion(n[0], n[1], n[2]);
90 ········return true;
91 ····}
92
93 ····public PackageVersion Bump(string policy) => policy switch
94 ····{
95 ········"patch" => this with { Patch = Patch + 1 },
96 ········"minor" => new PackageVersion(Major, Minor + 1, 0),
97 ········_ => throw new BuildException($"Unknown propagation policy '{policy}'. Use patch or minor."),
98 ····};
99
100 ····public int CompareTo(PackageVersion o) =>
101 ········Major != o.Major ? Major.CompareTo(o.Major) : Minor != o.Minor ? Minor.CompareTo(o.Minor) : Patch.CompareTo(o.Patch);
102
103 ····public override string ToString() => $"{Major}.{Minor}.{Patch}";
104 ····public string AssemblyVersion => $"{Major}.{Minor}.{Patch}.0";
105 }
106
107 /// <summary>A project or nuspec file. Edits are done on the text to keep the formatting.</summary>
108 class ProjectFile
109 {
110 ····public string Path = "";
111 ····public string Text = "";
112 ····public string OriginalText = "";
113 ····public Encoding Encoding = new UTF8Encoding(false);
114 ····public XDocument? Xml;
115 ····public List<string> ProjectReferences = new();·· // full paths
116 ····public List<string> PackageReferences = new();·· // package ids as written
117 ····public List<string> Edits = new();
118
119 ····public bool IsDirty => Text != OriginalText;
120
121 ····public static ProjectFile Load(string path)
122 ····{
123 ········var bytes = File.ReadAllBytes(path);
124 ········bool bom = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF;
125 ········var encoding = new UTF8Encoding(bom);
126 ········var text = encoding.GetString(bytes, bom ? 3 : 0, bytes.Length - (bom ? 3 : 0));
127 ········var file = new ProjectFile { Path = path, Text = text, OriginalText = text, Encoding = encoding };
128 ········try
129 ········{
130 ············file.Xml = XDocument.Parse(text);
131 ········}
132 ········catch (Exception ex)
133 ········{
134 ············throw new BuildException($"{path} can't be parsed: {ex.Message}");
135 ········}
136 ········var dir = System.IO.Path.GetDirectoryName(path)!;
137 ········foreach (var e in file.Xml.Descendants().Where(e => e.Name.LocalName == "ProjectReference"))
138 ········{
139 ············var include = (string?)e.Attribute("Include");
140 ············if (include != null)
141 ················file.ProjectReferences.Add(System.IO.Path.GetFullPath(System.IO.Path.Combine(dir, include.Replace('\\', System.IO.Path.DirectorySeparatorChar))));
142 ········}
143 ········foreach (var e in file.Xml.Descendants().Where(e => e.Name.LocalName == "PackageReference"))
144 ········{
145 ············var include = (string?)e.Attribute("Include");
146 ············if (include != null)
147 ················file.PackageReferences.Add(include);
148 ········}
149 ········return file;
150 ····}
151
152 ····public string? Property(string name) =>
153 ········Xml!.Descendants().FirstOrDefault(e => e.Name.LocalName == name && e.Parent?.Name.LocalName == "PropertyGroup")?.Value.Trim();
154
155 ····public void Save()
156 ····{
157 ········var bytes = Encoding.GetPreamble().Concat(Encoding.GetBytes(Text)).ToArray();
158 ········File.WriteAllBytes(Path, bytes);
159 ····}
160 }
161
162 record BuildStep(string Project, string Builder, string? Configuration);
163
164 class Package
165 {
166 ····public string Id = "";
167 ····public string Project = "";
168 ····public string Builder = "dotnet";
169 ····public PackageVersion Manifest, Current, Target;
170 ····public List<string> VersionFollowers = new();
171 ····public List<BuildStep> BuildFirst = new();
172 ····public HashSet<Package> Dependencies = new();
173 ····public string? Change;·· // null, "manual" or "propagated"
174 ····public bool IsNuspec => Project.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase);
175 }
176
177 record Consumer(string Project, bool Test, string? Configuration)
178 {
179 ····public HashSet<Package> Dependencies { get; } = new();
180 }
181
182 class Build(Options options)
183 {
184 ····static readonly StringComparer PathComparer = StringComparer.OrdinalIgnoreCase;
185 ····static readonly string[] SkippedDirectories = { "bin", "obj", "packages", ".vs", ".git", "node_modules" };
186
187 ····static readonly Regex PropertyGroupRx = new(@"<PropertyGroup\b(?:[^>]*[^/>])?>.*?</PropertyGroup>", RegexOptions.Singleline);
188 ····static readonly Regex MetadataRx = new(@"<metadata\b[^>]*>.*?</metadata>", RegexOptions.Singleline);
189 ····static readonly Regex PackageReferenceRx = new(@"<PackageReference\b(?<attrs>[^>]*?)(?:/>|>(?<body>.*?)</PackageReference>)", RegexOptions.Singleline);
190 ····static readonly Regex IncludeRx = new(@"\bInclude\s*=\s*""(?<v>[^""]*)""");
191 ····static readonly Regex VersionAttributeRx = new(@"(?<pre>\bVersion\s*=\s*"")(?<v>[^""]*)(?<post>"")");
192 ····static readonly Regex VersionElementRx = new(@"(?<pre><Version>)(?<v>[^<]*)(?<post></Version>)");
193
194 ····readonly Dictionary<string, ProjectFile> files = new(PathComparer);
195 ····readonly List<string> warnings = new();
196 ····readonly List<Package> packages = new();
197 ····readonly List<Consumer> consumers = new();
198 ····readonly HashSet<string> pinned = new(PathComparer);
199 ····readonly List<string> exclude = new();
200 ····readonly List<BuildStep> consumersBuildFirst = new();
201 ····readonly HashSet<string> referencesUpdated = new(PathComparer);
202 ····string? enhancer;
203 ····string root = "", manifestPath = "", manifestText = "", packageSource = "", configuration = "", policy = "";
204
205 ····public int Run()
206 ····{
207 ········LoadManifest();
208 ········var scanned = ScanProjects();
209 ········BuildGraph();
210 ········var order = SortTopologically();
211 ········DetectChanges(order);
212 ········PatchProducers();
213 ········PatchConsumers(scanned);
214 ········PatchEnhancer(scanned);
215
216 ········var toBuild = SelectPackages(order);
217 ········var consumersToBuild = SelectConsumers(toBuild);
218 ········Report(order, toBuild, consumersToBuild);
219
220 ········if (options.DryRun)
221 ········{
222 ············Console.WriteLine("Dry run – nothing changed.");
223 ············return 0;
224 ········}
225
226 ········SaveChanges();
227 ········if (options.NoBuild)
228 ············return 0;
229
230 ········foreach (var p in toBuild)
231 ············BuildPackage(p);
232 ········var failed = new List<string>();
233 ········if (consumersToBuild.Count > 0 && consumersBuildFirst.Count > 0)
234 ········{
235 ············Header("Prerequisites of the consumers");
236 ············foreach (var step in consumersBuildFirst)
237 ················BuildProject(step.Project, step.Builder, step.Configuration ?? configuration);
238 ········}
239 ········foreach (var c in consumersToBuild)
240 ············if (!BuildConsumer(c))
241 ················failed.Add(Rel(c.Project));
242
243 ········Console.WriteLine();
244 ········Console.WriteLine($"Built packages: {(toBuild.Count == 0 ? "none" : string.Join(", ", toBuild.Select(p => $"{p.Id} {p.Target}")))}");
245 ········if (failed.Count > 0)
246 ········{
247 ············Console.Error.WriteLine("Failed consumers:");
248 ············failed.ForEach(f => Console.Error.WriteLine("··" + f));
249 ············return 1;
250 ········}
251 ········return 0;
252 ····}
253
254 ····// ---------------------------------------------------------------- manifest
255
256 ····void LoadManifest()
257 ····{
258 ········var scriptDir = AppContext.GetData("EntryPointFileDirectoryPath") as string ?? FindMakeDirectory();
259 ········manifestPath = Path.Combine(scriptDir, "packages.json");
260 ········if (!File.Exists(manifestPath))
261 ············throw new BuildException($"Manifest {manifestPath} not found.");
262 ········root = Path.GetFullPath(Path.Combine(scriptDir, ".."));
263 ········manifestText = File.ReadAllText(manifestPath);
264
265 ········var json = JsonNode.Parse(manifestText, documentOptions: new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true })!;
266 ········packageSource = Path.GetFullPath(Path.Combine(scriptDir, (string?)json["packageSource"] ?? "../BuiltPackages"));
267 ········configuration = options.Configuration ?? (string?)json["configuration"] ?? "Release";
268 ········policy = options.Bump ?? (string?)json["propagation"] ?? "patch";
269 ········new PackageVersion(0, 0, 0).Bump(policy);·· // validates the policy
270
271 ········foreach (var e in json["exclude"]?.AsArray() ?? new JsonArray())
272 ············exclude.Add(Abs((string)e!));
273 ········foreach (var e in json["pinned"]?.AsArray() ?? new JsonArray())
274 ············pinned.Add(Abs((string)e!));
275
276 ········foreach (var node in json["packages"]!.AsArray())
277 ········{
278 ············var id = (string?)node!["id"] ?? throw new BuildException("A package in the manifest has no id.");
279 ············var p = new Package
280 ············{
281 ················Id = id,
282 ················Project = Abs((string?)node["project"] ?? throw new BuildException($"Package {id} has no project.")),
283 ················Builder = (string?)node["builder"] ?? "dotnet",
284 ················Manifest = PackageVersion.Parse((string?)node["version"] ?? "", $"Manifest version of {id}"),
285 ············};
286 ············foreach (var f in node["versionFollowers"]?.AsArray() ?? new JsonArray())
287 ················p.VersionFollowers.Add(Abs((string)f!));
288 ············p.BuildFirst.AddRange(ParseBuildSteps(node["buildFirst"]));
289 ············if (packages.Any(x => x.Id.Equals(id, StringComparison.OrdinalIgnoreCase)))
290 ················throw new BuildException($"Package {id} is listed twice in the manifest.");
291 ············packages.Add(p);
292 ········}
293
294 ········foreach (var node in json["consumers"]?.AsArray() ?? new JsonArray())
295 ········{
296 ············var c = new Consumer(Abs((string)node!["project"]!), (bool?)node["test"] ?? false, (string?)node["configuration"]);
297 ············if (packages.Any(p => PathComparer.Equals(p.Project, c.Project)))
298 ················throw new BuildException($"{Rel(c.Project)} is listed as package and as consumer.");
299 ············consumers.Add(c);
300 ········}
301
302 ········consumersBuildFirst.AddRange(ParseBuildSteps(json["consumersBuildFirst"]));
303 ········if ((string?)json["enhancer"] is { } enhancerProject)
304 ············enhancer = Abs(enhancerProject);
305
306 ········foreach (var id in options.Only.Concat(options.Rebuild))
307 ············if (FindPackage(id) == null)
308 ················throw new BuildException($"Unknown package id '{id}'.");
309 ····}
310
311 ····IEnumerable<BuildStep> ParseBuildSteps(JsonNode? node) =>
312 ········(node?.AsArray() ?? new JsonArray()).Select(s => s is JsonValue
313 ············? new BuildStep(Abs((string)s!), "dotnet", null)
314 ············: new BuildStep(Abs((string)s!["project"]!), (string?)s["builder"] ?? "dotnet", (string?)s["configuration"]));
315
316 ····static string FindMakeDirectory()
317 ····{
318 ········for (var dir = new DirectoryInfo(Directory.GetCurrentDirectory()); dir != null; dir = dir.Parent)
319 ········{
320 ············var make = Path.Combine(dir.FullName, "Make");
321 ············if (File.Exists(Path.Combine(make, "packages.json")))
322 ················return make;
323 ········}
324 ········throw new BuildException("Make/packages.json not found.");
325 ····}
326
327 ····// ---------------------------------------------------------------- graph
328
329 ····List<ProjectFile> ScanProjects()
330 ····{
331 ········var result = new List<ProjectFile>();
332 ········void Walk(string dir)
333 ········{
334 ············if (exclude.Contains(dir, PathComparer))
335 ················return;
336 ············foreach (var f in Directory.EnumerateFiles(dir, "*.csproj"))
337 ············{
338 ················try
339 ················{
340 ····················result.Add(GetFile(f));
341 ················}
342 ················catch (BuildException ex)
343 ················{
344 ····················warnings.Add(ex.Message + " The project is skipped.");
345 ················}
346 ············}
347 ············foreach (var d in Directory.EnumerateDirectories(dir))
348 ················if (!SkippedDirectories.Contains(Path.GetFileName(d), StringComparer.OrdinalIgnoreCase))
349 ····················Walk(d);
350 ········}
351 ········Walk(root);
352 ········return result;
353 ····}
354
355 ····ProjectFile GetFile(string path)
356 ····{
357 ········if (!files.TryGetValue(path, out var file))
358 ········{
359 ············if (!System.IO.File.Exists(path))
360 ················throw new BuildException($"{Rel(path)} doesn't exist.");
361 ············files[path] = file = ProjectFile.Load(path);
362 ········}
363 ········return file;
364 ····}
365
366 ····Package? FindPackage(string id) => packages.FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
367 ····Package? PackageOfProject(string path) => packages.FirstOrDefault(p => PathComparer.Equals(p.Project, path));
368
369 ····/// <summary>All packages reachable from the given projects, through project and package references.</summary>
370 ····HashSet<Package> Reachable(IEnumerable<string> start)
371 ····{
372 ········var result = new HashSet<Package>();
373 ········var visited = new HashSet<string>(PathComparer);
374 ········var stack = new Stack<string>(start);
375 ········while (stack.Count > 0)
376 ········{
377 ············var path = stack.Pop();
378 ············if (!visited.Add(path) || path.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase))
379 ················continue;
380 ············if (!System.IO.File.Exists(path))
381 ············{
382 ················warnings.Add($"Referenced project {Rel(path)} doesn't exist.");
383 ················continue;
384 ············}
385 ············var file = GetFile(path);
386 ············foreach (var r in file.ProjectReferences)
387 ············{
388 ················if (PackageOfProject(r) is { } p)
389 ····················result.Add(p);
390 ················stack.Push(r);
391 ············}
392 ············if (pinned.Contains(path))
393 ················continue;
394 ············foreach (var id in file.PackageReferences)
395 ················if (FindPackage(id) is { } p && result.Add(p))
396 ····················stack.Push(p.Project);
397 ········}
398 ········return result;
399 ····}
400
401 ····void BuildGraph()
402 ····{
403 ········foreach (var p in packages)
404 ········{
405 ············var start = new List<string>();
406 ············if (!p.IsNuspec)
407 ················start.Add(p.Project);
408 ············start.AddRange(p.VersionFollowers);
409 ············start.AddRange(p.BuildFirst.Select(s => s.Project));
410 ············p.Dependencies = Reachable(start);
411 ············if (p.Dependencies.Contains(p))
412 ················throw new BuildException($"Package {p.Id} depends on itself (cycle in the dependency graph).");
413
414 ············if (!p.IsNuspec)
415 ············{
416 ················var file = GetFile(p.Project);
417 ················var packageId = file.Property("PackageId") ?? file.Property("AssemblyName") ?? Path.GetFileNameWithoutExtension(p.Project);
418 ················if (!packageId.Equals(p.Id, StringComparison.OrdinalIgnoreCase))
419 ····················warnings.Add($"{Rel(p.Project)}: PackageId '{packageId}' differs from manifest id '{p.Id}'.");
420 ············}
421 ········}
422 ········foreach (var c in consumers)
423 ············c.Dependencies.UnionWith(Reachable(new[] { c.Project }));
424 ····}
425
426 ····List<Package> SortTopologically()
427 ····{
428 ········var order = new List<Package>();
429 ········var remaining = new List<Package>(packages);
430 ········while (remaining.Count > 0)
431 ········{
432 ············var next = remaining.FirstOrDefault(p => p.Dependencies.All(order.Contains))
433 ················?? throw new BuildException("Cycle in the dependency graph: " + string.Join(", ", remaining.Select(p => p.Id)));
434 ············order.Add(next);
435 ············remaining.Remove(next);
436 ········}
437 ········return order;
438 ····}
439
440 ····// ---------------------------------------------------------------- versions
441
442 ····void DetectChanges(List<Package> order)
443 ····{
444 ········foreach (var p in order)
445 ········{
446 ············p.Current = ReadVersion(p);
447 ············if (p.Manifest.CompareTo(p.Current) != 0)
448 ············{
449 ················p.Change = "manual";
450 ················p.Target = p.Manifest;
451 ················if (p.Manifest.CompareTo(p.Current) < 0)
452 ····················warnings.Add($"{p.Id}: manifest version {p.Manifest} is lower than the project version {p.Current}.");
453 ············}
454 ············else if (p.Dependencies.Any(d => d.Change != null))
455 ············{
456 ················p.Change = "propagated";
457 ················p.Target = p.Current.Bump(policy);
458 ················UpdateManifestVersion(p);
459 ············}
460 ············else
461 ············{
462 ················p.Target = p.Current;
463 ············}
464 ········}
465 ····}
466
467 ····PackageVersion ReadVersion(Package p)
468 ····{
469 ········var file = GetFile(p.Project);
470 ········if (p.IsNuspec)
471 ········{
472 ············var v = file.Xml!.Descendants().FirstOrDefault(e => e.Name.LocalName == "version" && e.Parent?.Name.LocalName == "metadata")?.Value
473 ················?? throw new BuildException($"{Rel(p.Project)} has no <version>.");
474 ············return PackageVersion.Parse(v, Rel(p.Project));
475 ········}
476 ········var version = file.Property("Version") ?? throw new BuildException($"{Rel(p.Project)} has no <Version> property.");
477 ········return PackageVersion.Parse(version, Rel(p.Project));
478 ····}
479
480 ····void UpdateManifestVersion(Package p)
481 ····{
482 ········var idMatch = new Regex(@"""id""\s*:\s*""" + Regex.Escape(p.Id) + @"""").Match(manifestText);
483 ········var nextId = new Regex(@"""id""\s*:").Match(manifestText, idMatch.Index + idMatch.Length);
484 ········var versionMatch = new Regex(@"(""version""\s*:\s*"")[^""]*("")").Match(manifestText, idMatch.Index);
485 ········if (!idMatch.Success || !versionMatch.Success || (nextId.Success && nextId.Index < versionMatch.Index))
486 ············throw new BuildException($"The version of {p.Id} can't be located in {manifestPath}.");
487 ········manifestText = manifestText[..versionMatch.Index]
488 ············+ versionMatch.Groups[1].Value + p.Target + versionMatch.Groups[2].Value
489 ············+ manifestText[(versionMatch.Index + versionMatch.Length)..];
490 ····}
491
492 ····// ---------------------------------------------------------------- patching
493
494 ····void PatchProducers()
495 ····{
496 ········foreach (var p in packages)
497 ········{
498 ············var file = GetFile(p.Project);
499 ············if (p.IsNuspec)
500 ················file.Text = MetadataRx.Replace(file.Text, m => ReplaceElement(file, m.Value, "version", p.Target.ToString()));
501 ············else
502 ················PatchVersionProperties(file, p.Target);
503 ············foreach (var f in p.VersionFollowers)
504 ················PatchVersionProperties(GetFile(f), p.Target);
505 ········}
506 ····}
507
508 ····void PatchVersionProperties(ProjectFile file, PackageVersion v)
509 ····{
510 ········file.Text = PropertyGroupRx.Replace(file.Text, m =>
511 ········{
512 ············var block = ReplaceElement(file, m.Value, "Version", v.ToString());
513 ············block = ReplaceElement(file, block, "AssemblyVersion", v.AssemblyVersion);
514 ············return ReplaceElement(file, block, "FileVersion", v.AssemblyVersion);
515 ········});
516 ····}
517
518 ····static string ReplaceElement(ProjectFile file, string text, string name, string value) =>
519 ········new Regex($@"(<{name}>)\s*([^<]*?)\s*(</{name}>)").Replace(text, m =>
520 ········{
521 ············if (m.Groups[2].Value == value)
522 ················return m.Value;
523 ············file.Edits.Add($"{name} {m.Groups[2].Value} -> {value}");
524 ············return m.Groups[1].Value + value + m.Groups[3].Value;
525 ········});
526
527 ····static readonly Regex TargetFrameworkRx = new(@"\bnet(\d+)\.(\d+)\b");
528 ····static readonly Regex EnhancerTargetFrameworkRx = new(@"<TargetFrameworks?>[^<]*</TargetFrameworks?>");
529 ····static readonly Regex EnhancerPathRx = new(@"(?<=NDOEnhancer[\\/]bin[\\/](?:debug|release)[\\/])net\d+\.\d+(?=[\\/])", RegexOptions.IgnoreCase);
530
531 ····/// <summary>
532 ····/// The enhancer targets only the highest .NET version of the package projects.
533 ····/// Every path to the enhancer's output (Exec tasks of test projects, nuspec files) follows that version.
534 ····/// </summary>
535 ····void PatchEnhancer(List<ProjectFile> scanned)
536 ····{
537 ········if (enhancer == null)
538 ············return;
539 ········var frameworks = packages.Where(p => !p.IsNuspec)
540 ············.Select(p => GetFile(p.Project))
541 ············.SelectMany(f => TargetFrameworkRx.Matches(f.Property("TargetFrameworks") ?? f.Property("TargetFramework") ?? ""))
542 ············.Select(m => (Major: int.Parse(m.Groups[1].Value), Minor: int.Parse(m.Groups[2].Value)))
543 ············.ToList();
544 ········if (frameworks.Count == 0)
545 ············throw new BuildException("The highest .NET version of the package projects can't be determined.");
546 ········var (major, minor) = frameworks.Max();
547 ········var tfm = $"net{major}.{minor}";
548
549 ········var enhancerFile = GetFile(enhancer);
550 ········enhancerFile.Text = PropertyGroupRx.Replace(enhancerFile.Text, m => EnhancerTargetFrameworkRx.Replace(m.Value, t =>
551 ········{
552 ············var replacement = $"<TargetFramework>{tfm}</TargetFramework>";
553 ············if (t.Value != replacement)
554 ················enhancerFile.Edits.Add($"{t.Value} -> {replacement}");
555 ············return replacement;
556 ········}));
557
558 ········foreach (var file in scanned.Concat(packages.Where(p => p.IsNuspec).Select(p => GetFile(p.Project))).Distinct())
559 ········{
560 ············file.Text = EnhancerPathRx.Replace(file.Text, m =>
561 ············{
562 ················if (m.Value == tfm)
563 ····················return m.Value;
564 ················file.Edits.Add($"NDOEnhancer path {m.Value} -> {tfm}");
565 ················return tfm;
566 ············});
567 ········}
568 ····}
569
570 ····void PatchConsumers(List<ProjectFile> scanned)
571 ····{
572 ········foreach (var file in scanned.Where(f => !pinned.Contains(f.Path)))
573 ········{
574 ············file.Text = PackageReferenceRx.Replace(file.Text, m =>
575 ············{
576 ················var id = IncludeRx.Match(m.Groups["attrs"].Value).Groups["v"].Value;
577 ················var p = FindPackage(id);
578 ················if (p == null)
579 ····················return m.Value;
580 ················var rx = VersionAttributeRx.IsMatch(m.Groups["attrs"].Value) ? VersionAttributeRx : VersionElementRx;
581 ················var vm = rx.Match(m.Value);
582 ················if (!vm.Success)
583 ················{
584 ····················warnings.Add($"{Rel(file.Path)}: PackageReference {id} has no version.");
585 ····················return m.Value;
586 ················}
587 ················var current = vm.Groups["v"].Value;
588 ················if (!PackageVersion.TryParse(current, out var cv))
589 ················{
590 ····················warnings.Add($"{Rel(file.Path)}: PackageReference {id} uses version '{current}', which isn't patched.");
591 ····················return m.Value;
592 ················}
593 ················if (cv.CompareTo(p.Target) == 0 && current == p.Target.ToString())
594 ····················return m.Value;
595 ················referencesUpdated.Add(file.Path);
596 ················file.Edits.Add($"PackageReference {id} {current} -> {p.Target}");
597 ················return m.Value[..vm.Index] + vm.Groups["pre"].Value + p.Target + vm.Groups["post"].Value + m.Value[(vm.Index + vm.Length)..];
598 ············});
599 ········}
600 ····}
601
602 ····void SaveChanges()
603 ····{
604 ········foreach (var file in files.Values.Where(f => f.IsDirty))
605 ············file.Save();
606 ········if (manifestText != System.IO.File.ReadAllText(manifestPath))
607 ············System.IO.File.WriteAllText(manifestPath, manifestText, new UTF8Encoding(false));
608 ····}
609
610 ····// ---------------------------------------------------------------- planning and report
611
612 ····List<Package> SelectPackages(List<Package> order)
613 ····{
614 ········if (options.Only.Count > 0)
615 ············return order.Where(p => options.Only.Contains(p.Id, StringComparer.OrdinalIgnoreCase)).ToList();
616 ········return order.Where(p => options.All
617 ············|| p.Change != null
618 ············|| referencesUpdated.Contains(p.Project)
619 ············|| !System.IO.File.Exists(Path.Combine(packageSource, $"{p.Id}.{p.Target}.nupkg"))
620 ············|| options.Rebuild.Contains(p.Id, StringComparer.OrdinalIgnoreCase)).ToList();
621 ····}
622
623 ····List<Consumer> SelectConsumers(List<Package> toBuild)
624 ····{
625 ········if (options.NoConsumers)
626 ············return new();
627 ········return consumers.Where(c => options.All || c.Dependencies.Overlaps(toBuild)).ToList();
628 ····}
629
630 ····void Report(List<Package> order, List<Package> toBuild, List<Consumer> consumersToBuild)
631 ····{
632 ········Console.WriteLine("Version changes:");
633 ········var changed = order.Where(p => p.Change != null).ToList();
634 ········if (changed.Count == 0)
635 ············Console.WriteLine("··none");
636 ········var width = order.Max(p => p.Id.Length);
637 ········foreach (var p in changed)
638 ············Console.WriteLine($"··{p.Id.PadRight(width)}··{p.Current,-8} -> {p.Target,-8}··({p.Change})");
639
640 ········Console.WriteLine("File edits:");
641 ········var edited = files.Values.Where(f => f.Edits.Count > 0).OrderBy(f => f.Path, PathComparer).ToList();
642 ········if (edited.Count == 0)
643 ············Console.WriteLine("··none");
644 ········foreach (var f in edited)
645 ········{
646 ············Console.WriteLine("··" + Rel(f.Path));
647 ············f.Edits.ForEach(e => Console.WriteLine("······" + e));
648 ········}
649 ········if (manifestText != System.IO.File.ReadAllText(manifestPath))
650 ············Console.WriteLine($"··{Rel(manifestPath)}\n······propagated versions");
651
652 ········if (warnings.Count > 0)
653 ········{
654 ············Console.WriteLine("Warnings:");
655 ············warnings.ForEach(w => Console.WriteLine("··" + w));
656 ········}
657
658 ········if (!options.NoBuild)
659 ········{
660 ············Console.WriteLine($"Packages to build ({configuration}):");
661 ············Console.WriteLine("··" + (toBuild.Count == 0 ? "none" : string.Join(", ", toBuild.Select(p => p.Id))));
662 ············Console.WriteLine("Consumers to build:");
663 ············if (consumersToBuild.Count == 0)
664 ················Console.WriteLine("··none");
665 ············else if (consumersBuildFirst.Count > 0)
666 ················Console.WriteLine("··first: " + string.Join(", ", consumersBuildFirst.Select(s => $"{Path.GetFileNameWithoutExtension(s.Project)} ({s.Configuration ?? configuration})")));
667 ············foreach (var c in consumersToBuild)
668 ················Console.WriteLine($"··{Rel(c.Project)}{(c.Test && options.Test ? " (+ test)" : "")}");
669 ········}
670 ········Console.WriteLine();
671 ····}
672
673 ····// ---------------------------------------------------------------- building
674
675 ····void BuildPackage(Package p)
676 ····{
677 ········Header($"Package {p.Id} {p.Target}");
678 ········Directory.CreateDirectory(packageSource);
679 ········DeleteFromNuGetCache(p);
680 ········foreach (var step in p.BuildFirst)
681 ············BuildProject(step.Project, step.Builder, step.Configuration ?? configuration);
682
683 ········if (p.Builder == "nuget")
684 ········{
685 ············Exec(Path.Combine(root, "nuget", "NuGet.exe"), Path.GetDirectoryName(p.Project)!,
686 ················"pack", Path.GetFileName(p.Project), "-Version", p.Target.ToString(), "-OutputDirectory", packageSource);
687 ············if (!System.IO.File.Exists(Path.Combine(packageSource, $"{p.Id}.{p.Target}.nupkg")))
688 ················throw new BuildException($"nuget pack didn't produce {p.Id}.{p.Target}.nupkg.");
689 ············return;
690 ········}
691
692 ········BuildProject(p.Project, p.Builder, configuration);
693 ········var outputDir = Path.Combine(Path.GetDirectoryName(p.Project)!, "bin", configuration);
694 ········var copied = 0;
695 ········foreach (var ext in new[] { ".nupkg", ".snupkg" })
696 ········{
697 ············var name = $"{p.Id}.{p.Target}{ext}";
698 ············var source = Directory.Exists(outputDir)
699 ················? Directory.EnumerateFiles(outputDir, "*" + ext).FirstOrDefault(f => Path.GetFileName(f).Equals(name, StringComparison.OrdinalIgnoreCase))
700 ················: null;
701 ············if (source == null)
702 ················continue;
703 ············System.IO.File.Copy(source, Path.Combine(packageSource, Path.GetFileName(source)), overwrite: true);
704 ············Console.WriteLine($"Copied {Path.GetFileName(source)} to {Rel(packageSource)}");
705 ············if (ext == ".nupkg")
706 ················copied++;
707 ········}
708 ········if (copied == 0)
709 ············throw new BuildException($"{p.Id}.{p.Target}.nupkg not found in {Rel(outputDir)}.");
710 ····}
711
712 ····bool BuildConsumer(Consumer c)
713 ····{
714 ········var config = c.Configuration ?? configuration;
715 ········Header($"Consumer {Rel(c.Project)}");
716 ········try
717 ········{
718 ············BuildProject(c.Project, "dotnet", config);
719 ············if (c.Test && options.Test)
720 ················Exec("dotnet", root, "test", c.Project, "-c", config, "--no-build");
721 ············return true;
722 ········}
723 ········catch (BuildException ex)
724 ········{
725 ············Console.Error.WriteLine(ex.Message);
726 ············return false;
727 ········}
728 ····}
729
730 ····void BuildProject(string project, string builder, string config)
731 ····{
732 ········switch (builder)
733 ········{
734 ············case "dotnet":
735 ················Exec("dotnet", root, "restore", project, "--force");
736 ················Exec("dotnet", root, "build", project, "-c", config, "--no-restore");
737 ················break;
738 ············case "msbuild":
739 ················Exec(FindMSBuild(), root, project, "-restore", "-nologo", "-v:minimal", $"-p:Configuration={config}");
740 ················break;
741 ············default:
742 ················throw new BuildException($"Unknown builder '{builder}' for {Rel(project)}.");
743 ········}
744 ····}
745
746 ····void DeleteFromNuGetCache(Package p)
747 ····{
748 ········var cache = Environment.GetEnvironmentVariable("NUGET_PACKAGES")
749 ············?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages");
750 ········var dir = Path.Combine(cache, p.Id.ToLowerInvariant(), p.Target.ToString());
751 ········if (Directory.Exists(dir))
752 ········{
753 ············Console.WriteLine($"Deleting {dir}");
754 ············Directory.Delete(dir, recursive: true);
755 ········}
756 ····}
757
758 ····string? msbuild;
759
760 ····string FindMSBuild()
761 ····{
762 ········if (msbuild != null)
763 ············return msbuild;
764 ········var vswhere = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft Visual Studio", "Installer", "vswhere.exe");
765 ········if (!System.IO.File.Exists(vswhere))
766 ············throw new BuildException("vswhere.exe not found. Visual Studio is needed to build old-style projects.");
767 ········var psi = new ProcessStartInfo(vswhere) { RedirectStandardOutput = true, UseShellExecute = false };
768 ········foreach (var a in new[] { "-latest", "-prerelease", "-products", "*", "-requires", "Microsoft.Component.MSBuild", "-find", @"MSBuild\**\Bin\MSBuild.exe" })
769 ············psi.ArgumentList.Add(a);
770 ········using var process = Process.Start(psi)!;
771 ········var output = process.StandardOutput.ReadToEnd();
772 ········process.WaitForExit();
773 ········msbuild = output.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).FirstOrDefault()
774 ············?? throw new BuildException("MSBuild.exe of Visual Studio not found.");
775 ········return msbuild;
776 ····}
777
778 ····void Exec(string fileName, string workingDirectory, params string[] arguments)
779 ····{
780 ········Console.WriteLine($"> {Path.GetFileName(fileName)} {string.Join(" ", arguments.Select(a => a.Contains(' ') ? $"\"{a}\"" : a))}");
781 ········var psi = new ProcessStartInfo(fileName) { WorkingDirectory = workingDirectory, UseShellExecute = false };
782 ········foreach (var a in arguments)
783 ············psi.ArgumentList.Add(a);
784 ········using var process = Process.Start(psi) ?? throw new BuildException($"{fileName} can't be started.");
785 ········process.WaitForExit();
786 ········if (process.ExitCode != 0)
787 ············throw new BuildException($"'{Path.GetFileName(fileName)} {string.Join(" ", arguments)}' failed with exit code {process.ExitCode}.");
788 ····}
789
790 ····static void Header(string text)
791 ····{
792 ········Console.WriteLine();
793 ········Console.WriteLine(new string('=', 78));
794 ········Console.WriteLine(text);
795 ········Console.WriteLine(new string('=', 78));
796 ····}
797
798 ····string Abs(string relative) => Path.GetFullPath(Path.Combine(root.Length > 0 ? root : ".", relative.Replace('\\', Path.DirectorySeparatorChar)));
799 ····string Rel(string path) => Path.GetRelativePath(root, path).Replace('\\', '/');
800 }
801