-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDebugifier.cs
More file actions
1046 lines (864 loc) · 44.4 KB
/
Debugifier.cs
File metadata and controls
1046 lines (864 loc) · 44.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.RegularExpressions;
using CommandLine;
using CommandLine.Text;
using Spectre.Console;
namespace alma.debugify
{
[Verb("debug", isDefault:true, HelpText="Build your projects in debug mode and replace DLLs in the NuGet cache. Allows you to step through your package code while debugging applications that consume it.")]
public class DebugCommand
{
[Option("verbose", Required = false, HelpText = "Set output to verbose messages.")]
public bool Verbose{ get; set; }
[Option('p', "path", Required = false, HelpText = "Path to *.csproj file or a folder that contains it (directly or in subfolder(s))")]
public string Path { get; set; }
[Option('v', "version", Required=false,HelpText = "Specify the version you'd like to debugify")]
public string Version { get; set; }
[Option('c', "configuration", Required=false, Default = "Debug", HelpText = "Build configuration (Debug or Release). Default is Debug.")]
public string Configuration { get; set; }
[Option('r', "rebuild", Required=false, Default = false, HelpText = "Force a full rebuild of projects (slower but ensures fresh DLLs). Default is false.")]
public bool Rebuild { get; set; }
[Option( "buildargs", Required=false,HelpText = "Additional arguments for dotnet build. e.g. \" --no-restore\"")]
public string BuildArguments { get; set; }
[Option("packageid", Required=false, HelpText = "Override the package ID. Use this when the NuGet package ID differs from the project's PackageId/AssemblyName.")]
public string PackageId { get; set; }
[Usage(ApplicationAlias = "debugify")]
public static IEnumerable<Example> Examples
{
get
{
return new List<Example>() {
new Example("Debugify a specific version with Release configuration", new DebugCommand { Version = "1.6.6", Configuration = "Release" }),
new Example("Force a full rebuild", new DebugCommand { Rebuild = true }),
new Example("Specify a csproj file with a version", new DebugCommand { Path = "./MyProject.csproj", Version = "1.6.6" }),
new Example("Override package ID for Avalonia projects", new DebugCommand { Path = "./MyApp", PackageId = "Avalonia", Version = "11.0.0" }),
new Example("Verbose output with rebuild in Debug mode", new DebugCommand { Verbose = true, Rebuild = true, Configuration = "Debug" })
};
}
}
}
internal class Debugifier
{
private readonly ILogger _logger;
public Debugifier(ILogger logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public void Debugify(DebugCommand cmd)
{
if (!string.IsNullOrWhiteSpace(cmd.Version))
{
var versionValidator = new Regex(@"\d+\.\d+\.\d+(\.\d+)?[\d\w_-]*?");
if (!versionValidator.IsMatch(cmd.Version))
{
_logger.Error($"Error: '{cmd.Version}' is not a valid nuget package version");
return;
}
}
if (string.IsNullOrEmpty(cmd.Path))
{
if(cmd.Verbose) _logger.Debug($"No path provided. Will run in current directory: {Environment.CurrentDirectory}");
cmd.Path = Environment.CurrentDirectory;
}
else
{
if (!Path.IsPathRooted(cmd.Path))
cmd.Path = Path.GetFullPath(cmd.Path);
if (cmd.Verbose) _logger.Debug($"Path: {cmd.Path}");
}
// Validate packageid override if specified
if (!string.IsNullOrWhiteSpace(cmd.PackageId))
{
var packageIdValidator = new Regex(@"^[\w\.\-]+$");
if (!packageIdValidator.IsMatch(cmd.PackageId))
{
_logger.Error($"Error: '{cmd.PackageId}' is not a valid package ID. Package IDs can only contain alphanumeric characters, dots, and hyphens.");
return;
}
if (cmd.Verbose)
_logger.Debug($"Package ID override: {cmd.PackageId}");
}
// find it within the current solution
var solutionDir = File.Exists(cmd.Path) && string.Equals(Path.GetExtension(cmd.Path), ".sln",
StringComparison.InvariantCultureIgnoreCase)
? Path.GetDirectoryName(cmd.Path)
: RecursivelyFindSolutionDir(cmd.Path, cmd.Verbose);
if (solutionDir is null)
{
_logger.Warning($"Could not find any solution in '{(File.Exists(cmd.Path) ? Path.GetDirectoryName(cmd.Path) : cmd.Path)}'");
return;
}
if(cmd.Verbose) _logger.Debug($"Found sln directory: {solutionDir}");
// find all compatible project files
var projectFiles = EnumerateDebugifiableProjects(cmd).ToList();
if (!projectFiles.Any())
{
_logger.Warning($"Could not find any debugifiable *.csproj files in '{(File.Exists(cmd.Path) ? Path.GetDirectoryName(cmd.Path) : cmd.Path)}'");
return;
}
// resolve nuget package cache early to filter projects
var pathWithEnv = $@"%USERPROFILE%\.nuget\packages\";
var packageCachePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
if(cmd.Verbose) _logger.Info($"nuget package cache found at '{packageCachePath}'");
// filter to only projects that exist in the cache (avoid unnecessary builds)
var projectsInCache = projectFiles.Where(p =>
{
var packageBasePath = Path.Combine(packageCachePath, p.PackageId);
var existsInCache = Directory.Exists(packageBasePath);
if (!existsInCache && cmd.Verbose)
_logger.Debug($"Skipping {p.PackageId} - not found in cache at {packageBasePath}");
return existsInCache;
}).ToList();
if (!projectsInCache.Any())
{
_logger.Warning($"None of the {projectFiles.Count} project(s) were found in the nuget package cache. Please restore packages first.");
return;
}
if (projectsInCache.Count < projectFiles.Count)
{
_logger.Info($"Building {projectsInCache.Count} of {projectFiles.Count} project(s) (skipping projects not in cache)");
}
// Display operation settings
var settingsTable = new Table()
.BorderColor(Color.Grey)
.Border(TableBorder.Rounded)
.AddColumn(new TableColumn("[cyan]Setting[/]").LeftAligned())
.AddColumn(new TableColumn("[white]Value[/]").LeftAligned())
.AddRow("[grey]Configuration[/]", $"[yellow]{cmd.Configuration}[/]")
.AddRow("[grey]Rebuild[/]", cmd.Rebuild ? "[green]Enabled[/]" : "[dim]Disabled[/]")
.AddRow("[grey]Projects to build[/]", $"[cyan]{projectsInCache.Count}[/] of [white]{projectFiles.Count}[/]")
.AddRow("[grey]Version to build[/]", $"[cyan]{projectsInCache.FirstOrDefault()?.Version}[/]");
// Add package ID override row if specified
if (!string.IsNullOrWhiteSpace(cmd.PackageId))
{
settingsTable.AddRow("[grey]Package ID override[/]", $"[yellow]{cmd.PackageId}[/]");
}
AnsiConsole.Write(settingsTable);
AnsiConsole.WriteLine();
// build the projects in Debug configuration
var buildFailedCount = 0;
var erroredCsprojInfos = new List<CsprojInfo>();
// make sure the version files are restored afterwards
using (var cd = new CompositeDisposable(_logger))
{
// replace version in csproj files if specified
if (!string.IsNullOrWhiteSpace(cmd.Version))
{
foreach (var projectFile in projectsInCache)
{
try
{
if(cmd.Verbose) _logger.Debug($"changing package version of {Path.GetFileName(projectFile.Path)}");
cd.Add(projectFile.ReplaceVersion(cmd.Version));
}
catch (Exception x)
{
erroredCsprojInfos.Add(projectFile);
buildFailedCount++;
_logger.Error(x.Message);
}
}
}
var projectsToBuild = projectsInCache.Except(erroredCsprojInfos).ToList();
AnsiConsole.Progress()
.AutoClear(false)
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
new SpinnerColumn(),
})
.Start(ctx =>
{
var task = ctx.AddTask($"[cyan]Building {projectsToBuild.Count} project(s)[/]", maxValue: projectsToBuild.Count);
foreach (var projectFile in projectsToBuild)
{
task.Description = $"[cyan]Building[/] [white]{Path.GetFileName(projectFile.Path)}[/]";
if (!DotnetBuild(projectFile, cmd))
{
_logger.Error($"dotnet build failed for {Path.GetFileName(projectFile.Path)}");
buildFailedCount++;
erroredCsprojInfos.Add(projectFile);
}
task.Increment(1);
}
task.Description = buildFailedCount == 0
? $"[green]Built {projectsToBuild.Count} project(s) successfully[/]"
: $"[yellow]Built {projectsToBuild.Count - buildFailedCount}/{projectsToBuild.Count} project(s) successfully[/]";
});
if (buildFailedCount != 0)
_logger.Warning(
$"WARNING: Failed to build {buildFailedCount} of {projectsInCache.Count} projects");
}
// find and replace DLLs in the package cache with built binaries
var projectsToDebugify = projectsInCache.Except(erroredCsprojInfos).ToList();
var totalReplacedCount = 0;
AnsiConsole.Progress()
.AutoClear(false)
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
new SpinnerColumn(),
})
.Start(ctx =>
{
var task = ctx.AddTask($"[cyan]Debugifying {projectsToDebugify.Count} package(s)[/]", maxValue: projectsToDebugify.Count);
foreach (var projectFile in projectsToDebugify)
{
task.Description = $"[cyan]Debugifying[/] [white]{projectFile.PackageId}[/]";
// find bin\<Configuration> folder for this project
var projectDir = Path.GetDirectoryName(projectFile.Path);
var binConfigPath = Path.Combine(projectDir, "bin", cmd.Configuration);
if (!Directory.Exists(binConfigPath))
{
_logger.Error($"Could not find bin\\{cmd.Configuration} folder for {projectFile.PackageId}");
task.Increment(1);
continue;
}
// find all DLLs in bin\<Configuration> (recursively to handle different frameworks)
var builtDlls = Directory.EnumerateFiles(binConfigPath, "*.dll", SearchOption.AllDirectories).ToList();
var builtPdbs = Directory.EnumerateFiles(binConfigPath, "*.pdb", SearchOption.AllDirectories).ToList();
if (!builtDlls.Any())
{
_logger.Warning($"No DLLs found in {binConfigPath}");
task.Increment(1);
continue;
}
if(cmd.Verbose) _logger.Debug($"Found {builtDlls.Count} DLL(s) in {binConfigPath}");
// replace DLLs in the matching version of the package
var packageBasePath = Path.Combine(packageCachePath, projectFile.PackageId);
var replacedCount = FindAndReplaceDlls(cmd, packageBasePath, builtDlls, builtPdbs, projectFile.PackageId, projectFile.Version);
if (replacedCount > 0)
{
_logger.Success($"Successfully debugified {projectFile.PackageId} - replaced {replacedCount} file(s)");
totalReplacedCount += replacedCount;
}
else
_logger.Warning($"No matching DLLs found in cache for {projectFile.PackageId}");
task.Increment(1);
}
task.Description = totalReplacedCount > 0
? $"[green]Debugified {projectsToDebugify.Count} package(s) - {totalReplacedCount} file(s) replaced[/]"
: $"[yellow]Processed {projectsToDebugify.Count} package(s) - no files replaced[/]";
});
}
private IEnumerable<CsprojInfo> EnumerateDebugifiableProjects(DebugCommand cmd)
{
var path = cmd.Path;
var isCsprojFile = File.Exists(path) && string.Equals(Path.GetExtension(path), ".csproj", StringComparison.InvariantCultureIgnoreCase);
if (isCsprojFile)
{
// by default, ignore Test projects by convention
var fileName = Path.GetFileNameWithoutExtension(path);
if (fileName.EndsWith("Test", StringComparison.OrdinalIgnoreCase) ||
fileName.EndsWith("Tests", StringComparison.OrdinalIgnoreCase))
{
_logger.Debug(
$"Project file {Path.GetFileName(path)} seems to be a test project and is therefore ignored");
}
else
{
var csproj = path;
if (TryGetVersion(csproj, out string version) || !string.IsNullOrWhiteSpace(cmd.Version))
{
// to be sure that the csproj is nuget-compatible, ensure it is the new csproj format
if (!File.ReadLines(csproj).First().Trim().StartsWith("<Project Sdk="))
_logger.Warning(
$"Project file {Path.GetFileName(csproj)} is not supported: Only latest csproj format is supported");
else
{
var packageId = GetPackageId(csproj);
yield return new CsprojInfo(packageId, version ?? cmd.Version, csproj, cmd.PackageId);
}
}
else
_logger.Warning(
$"Project file {Path.GetFileName(csproj)} does not contain a <Version> element. Please specify a version using the -v commandline argument.");
}
}
else
{
// ensure path is a directory
path = Directory.Exists(path) ? path : Path.GetDirectoryName(path);
foreach(var csproj in Directory.EnumerateFiles(path, "*.csproj", SearchOption.AllDirectories))
{
if (TryGetVersion(csproj, out string version) || !string.IsNullOrWhiteSpace(cmd.Version))
{
// to be sure that the csproj is nuget-compatible, ensure it is the new csproj format
if (!File.ReadLines(csproj).First().Trim().StartsWith("<Project Sdk="))
_logger.Warning($"Project file {Path.GetFileName(csproj)} is not supported: Only latest csproj format is supported");
else
{
var packageId = GetPackageId(csproj);
yield return new CsprojInfo(packageId, version ?? cmd.Version, csproj, cmd.PackageId);
}
}
else
_logger.Warning($"Project file {Path.GetFileName(csproj)} does not contain a <Version> element. Please specify a version using the -v commandline argument.");
}
}
}
private bool TryGetVersion(string filePath, out string version)
{
EnsureCsprojFile(filePath);
var findVersion = new Regex(@"<Version>\s*(?<version>\d+\.\d+\.\d+(\.\d+)?(-[\w\.\-]+)?)\s*</Version>");
// First, try to find version in the csproj itself
var m = findVersion.Match(File.ReadAllText(filePath));
if (m.Success)
{
version = m.Groups["version"].Value;
return true;
}
// If not found in csproj, search for Directory.Build.props in parent hierarchy
var currentDir = Path.GetDirectoryName(filePath);
while (currentDir != null)
{
var candidatePath = Path.Combine(currentDir, "Directory.Build.props");
if (File.Exists(candidatePath))
{
// Try to find version in this Directory.Build.props
if (TryFindVersionInPropsFile(candidatePath, findVersion, out version))
{
return true;
}
}
// Move to parent directory
var parent = Directory.GetParent(currentDir);
currentDir = parent?.FullName;
}
version = null;
return false;
}
private bool TryFindVersionInPropsFile(string propsFilePath, Regex findVersion, out string version)
{
var content = File.ReadAllText(propsFilePath);
// Try to find version directly in this file
var m = findVersion.Match(content);
if (m.Success)
{
version = m.Groups["version"].Value;
return true;
}
// If not found, check for Import elements and search those files
var importRegex = new Regex(@"<Import\s+Project=""(?<path>[^""]+)""\s*/>");
var imports = importRegex.Matches(content);
foreach (Match import in imports)
{
var importPath = import.Groups["path"].Value;
// Resolve relative path based on the location of the props file
var baseDir = Path.GetDirectoryName(propsFilePath);
var resolvedPath = Path.GetFullPath(Path.Combine(baseDir, importPath));
if (File.Exists(resolvedPath))
{
var importedContent = File.ReadAllText(resolvedPath);
var importMatch = findVersion.Match(importedContent);
if (importMatch.Success)
{
version = importMatch.Groups["version"].Value;
return true;
}
}
}
version = null;
return false;
}
private bool TryFindDirectoryBuildProps(string startPath, out string buildPropsPath)
{
// Start from the directory containing the csproj
var currentDir = Path.GetDirectoryName(startPath);
// Walk up the directory hierarchy
while (currentDir != null)
{
var candidatePath = Path.Combine(currentDir, "Directory.Build.props");
if (File.Exists(candidatePath))
{
buildPropsPath = candidatePath;
return true;
}
// Move to parent directory
var parent = Directory.GetParent(currentDir);
currentDir = parent?.FullName;
}
buildPropsPath = null;
return false;
}
private string GetPackageId(string filePath)
{
EnsureCsprojFile(filePath);
if (TryFindXmlElement(filePath, "PackageId", out var packageId))
return packageId;
if (TryFindXmlElement(filePath, "AssemblyName", out var assemblyName))
return assemblyName;
return Path.GetFileNameWithoutExtension(filePath);
}
private static bool TryFindXmlElement(string filePath, string elementName, out string value)
{
var findPackageId = new Regex($@"<{elementName}>(?<packageId>[\w\.\-]+)</{elementName}>");
var m = findPackageId.Match(File.ReadAllText(filePath));
if (m.Success)
{
value = m.Groups["packageId"].Value;
return true;
}
value = null;
return false;
}
private static string ExtractTargetFrameworkFromPath(string filePath)
{
// Try to extract TFM from path like:
// bin\Debug\net6.0\MyLib.dll -> net6.0
// lib\netstandard2.0\MyLib.dll -> netstandard2.0
// Common TFM patterns: net6.0, net8.0, netstandard2.0, netstandard2.1, net472, net48, etc.
var pathParts = filePath.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
// Common TFM patterns (in order of priority)
var tfmPatterns = new[]
{
@"^net\d+\.\d+$", // net6.0, net8.0
@"^netstandard\d+\.\d+$", // netstandard2.0, netstandard2.1
@"^netcoreapp\d+\.\d+$", // netcoreapp3.1
@"^net\d+$", // net48, net472, net6, net8
@"^net\d{3}$", // net472, net48, etc.
};
// Search backwards through path parts to find TFM (usually closer to filename)
for (int i = pathParts.Length - 2; i >= 0; i--)
{
var part = pathParts[i];
foreach (var pattern in tfmPatterns)
{
if (Regex.IsMatch(part, pattern, RegexOptions.IgnoreCase))
{
return part.ToLowerInvariant();
}
}
}
return null;
}
private static string ExtractVersionFromPath(string versionDir)
{
// Extract version from path like: C:\Users\...\packages\PackageName\1.3.11\
var dirName = Path.GetFileName(versionDir.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
// Version pattern: major.minor.patch[.revision][-prerelease]
var versionPattern = new Regex(@"^(?<version>\d+\.\d+\.\d+(\.\d+)?([\d\w_-]*?)?)$");
var match = versionPattern.Match(dirName);
return match.Success ? match.Groups["version"].Value : null;
}
/// <summary>
/// Compares two version strings for equality, treating a missing fourth segment (revision)
/// as equivalent to zero. Supports prerelease suffixes (e.g., "1.6.8-alpha01").
/// </summary>
/// <param name="version1">The first version string to compare.</param>
/// <param name="version2">The second version string to compare.</param>
/// <returns>True if the versions are semantically equal; otherwise, false.</returns>
private static bool VersionsMatch(string version1, string version2)
{
if (string.IsNullOrWhiteSpace(version1) || string.IsNullOrWhiteSpace(version2))
return false;
return string.Equals(
NormalizeVersion(version1),
NormalizeVersion(version2),
StringComparison.OrdinalIgnoreCase
);
}
/// <summary>
/// Normalizes a version string by ensuring the numeric portion has exactly four segments,
/// appending ".0" for missing revision. Preserves any prerelease suffix.
/// </summary>
/// <param name="version">The version string to normalize.</param>
/// <returns>The normalized version string with four numeric segments.</returns>
private static string NormalizeVersion(string version)
{
var trimmed = version.Trim();
// Split off prerelease suffix (e.g., "-alpha01")
var hyphenIndex = trimmed.IndexOf('-');
var numericPart = hyphenIndex >= 0 ? trimmed[..hyphenIndex] : trimmed;
var suffix = hyphenIndex >= 0 ? trimmed[hyphenIndex..] : string.Empty;
// Ensure exactly 4 segments in numeric part
var segments = numericPart.Split('.');
if (segments.Length == 3)
numericPart += ".0";
return numericPart + suffix;
}
private int ProcessCacheFolder(DebugCommand cmd, string folderPath, string versionDir, List<string> debugDlls, List<string> debugPdbs, string folderType)
{
int replacedCount = 0;
if (!Directory.Exists(folderPath))
{
if (cmd.Verbose) _logger.Debug($"No '{folderType}' folder found in {versionDir}");
return 0;
}
// Find all DLLs and PDBs in the folder
var cachedDlls = Directory.EnumerateFiles(folderPath, "*.dll", SearchOption.AllDirectories).ToList();
var cachedPdbs = Directory.EnumerateFiles(folderPath, "*.pdb", SearchOption.AllDirectories).ToList();
// Match and replace DLLs by filename AND target framework
foreach (var cachedDll in cachedDlls)
{
var cachedFileName = Path.GetFileName(cachedDll);
var cachedTfm = ExtractTargetFrameworkFromPath(cachedDll);
var matchingDebugDll = debugDlls.FirstOrDefault(d =>
{
// Filename must match
if (!string.Equals(Path.GetFileName(d), cachedFileName, StringComparison.OrdinalIgnoreCase))
return false;
// If both have TFM, they must match
var debugTfm = ExtractTargetFrameworkFromPath(d);
if (cachedTfm != null && debugTfm != null)
return string.Equals(cachedTfm, debugTfm, StringComparison.OrdinalIgnoreCase);
// If at least one has no TFM, allow match (backward compatibility)
return true;
});
if (matchingDebugDll != null)
{
if (cmd.Verbose)
{
var relativePath = Path.GetRelativePath(versionDir, cachedDll);
_logger.Debug($" → {relativePath}");
}
File.Copy(matchingDebugDll, cachedDll, true);
replacedCount++;
}
}
// Match and replace PDBs by filename AND target framework
foreach (var cachedPdb in cachedPdbs)
{
var cachedFileName = Path.GetFileName(cachedPdb);
var cachedTfm = ExtractTargetFrameworkFromPath(cachedPdb);
var matchingDebugPdb = debugPdbs.FirstOrDefault(p =>
{
// Filename must match
if (!string.Equals(Path.GetFileName(p), cachedFileName, StringComparison.OrdinalIgnoreCase))
return false;
// If both have TFM, they must match
var debugTfm = ExtractTargetFrameworkFromPath(p);
if (cachedTfm != null && debugTfm != null)
return string.Equals(cachedTfm, debugTfm, StringComparison.OrdinalIgnoreCase);
// If at least one has no TFM, allow match (backward compatibility)
return true;
});
if (matchingDebugPdb != null)
{
if (cmd.Verbose)
{
var relativePath = Path.GetRelativePath(versionDir, cachedPdb);
_logger.Debug($" → {relativePath}");
}
File.Copy(matchingDebugPdb, cachedPdb, true);
replacedCount++;
}
}
return replacedCount;
}
private int FindAndReplaceDlls(DebugCommand cmd, string packageBasePath, List<string> debugDlls, List<string> debugPdbs, string packageId, string expectedVersion)
{
int replacedCount = 0;
// iterate through all versions of the package in the cache
foreach (var versionDir in Directory.EnumerateDirectories(packageBasePath))
{
// Extract version from directory name
var cachedVersion = ExtractVersionFromPath(versionDir);
// Skip if version doesn't match expected version
if (!VersionsMatch(cachedVersion, expectedVersion))
{
if (cmd.Verbose)
_logger.Debug($"Skipping version {cachedVersion} (expected {expectedVersion})");
continue;
}
// add marker file to know when to delete such a folder during cleanup
var markerFile = Path.Combine(versionDir, ".debugified.txt");
var timestamp = DateTime.UtcNow.ToString("o"); // ISO 8601 format
if (cmd.Verbose) _logger.Debug($"Writing .debugified.txt to {versionDir}");
File.WriteAllText(markerFile, $"Debugified at {timestamp} UTC");
// Process lib folder
var libPath = Path.Combine(versionDir, "lib");
replacedCount += ProcessCacheFolder(cmd, libPath, versionDir, debugDlls, debugPdbs, "lib");
// Process ref folder (reference assemblies)
var refPath = Path.Combine(versionDir, "ref");
replacedCount += ProcessCacheFolder(cmd, refPath, versionDir, debugDlls, debugPdbs, "ref");
}
return replacedCount;
}
private string RecursivelyFindSolutionDir(string path, bool verboseLogging)
{
var dir = Directory.Exists(path) ? path : Path.GetDirectoryName(path);
if(verboseLogging) _logger.Debug("Searching sln directory");
string sln = null;
for (int i = 0; i < 10; i++)
{
sln = Directory.EnumerateFiles(dir, "*.sln", SearchOption.TopDirectoryOnly).FirstOrDefault();
// if solution is not found within the current folder, proceed with the next parent folder
if (sln is null)
{
if(verboseLogging) _logger.Debug($" - No sln in '{dir}'");
dir = Path.GetDirectoryName(dir);
}
else
{
sln = Path.GetDirectoryName(sln);
break;
}
}
if (sln is null)
_logger.Error("Could not find any *.sln file within {path} or any of its 10 parent folders!");
return sln;
}
private bool DotnetBuild(CsprojInfo projectFile, DebugCommand cmd)
{
bool verbose = cmd.Verbose;
var csprojPath = projectFile.Path;
if (!Path.IsPathRooted(csprojPath))
throw new ArgumentException($"{nameof(csprojPath)} must be rooted");
// dotnet build -c <Configuration> [--no-incremental if rebuild requested]
// see: https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-build
var name = "dotnet";
var rebuildFlag = cmd.Rebuild ? "--no-incremental" : "";
var args = $"build -c {cmd.Configuration} {rebuildFlag} {cmd.BuildArguments}".Trim();
_logger.Info($"building {Path.GetFileName(projectFile.Path)} ({cmd.Configuration})");
var output = ExecuteProcess(name, args, csprojPath, verbose);
const string fallbackTraceMessage =
"error : If you are building projects that require targets from full MSBuild or MSBuildFrameworkToolsPath, you need to use desktop msbuild ('msbuild.exe') instead of 'dotnet build' or 'dotnet msbuild'";
var fallbackToMsBuildRequired = output.Output.Any(l => l.Contains(fallbackTraceMessage));
if (verbose)
{
foreach (var line in output.Output)
_logger.Debug(line);
_logger.Debug($"dotnet build returned {output.ExitCode}");
}
if (fallbackToMsBuildRequired)
{
if(verbose) _logger.Debug("falling back to full MSBuild as advanced targets are required...");
return MsBuildBuild(projectFile, cmd.Configuration, cmd.Rebuild, verbose);
}
// only if dotnet build returns 0, everything is fine
return output.ExitCode == 0;
}
private bool MsBuildBuild(CsprojInfo projectFile, string configuration, bool rebuild, bool verbose)
{
var workingDir = Path.GetDirectoryName(projectFile.Path);
// call vswhere - see: https://github.com/Microsoft/vswhere
var vswhereEnv = @"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe";
var vswherePath = Environment.ExpandEnvironmentVariables(vswhereEnv);
var o = ExecuteProcess(vswherePath,
@"-latest -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe",
workingDir, verbose);
var msBuildPath = o.ExitCode == 0 ? o.Output.Single() : null;
if (verbose && o.ExitCode == 0)
_logger.Debug($"found msbuild at '{msBuildPath}'");
if (o.ExitCode != 0)
{
_logger.Error("Could not find msbuild.exe. Please ensure that you have Visual Studio 2017 or higher installed on your machine!");
return false;
}
var target = rebuild ? "rebuild" : "build";
var o2 = ExecuteProcess(msBuildPath,
$"\"{projectFile.Path}\" /t:{target} /v:m /p:Configuration={configuration}",
workingDir, verbose);
if (verbose)
{
foreach (var l in o2.Output)
_logger.Verbose(l);
}
// only if msbuild build returns 0, everything is fine
return o2.ExitCode == 0;
}
private ProcessOutput ExecuteProcess(string name, string args, string workingDirectory, bool verbose)
{
if(verbose)
_logger.Info($"{name} {args}");
var pi = new ProcessStartInfo(name, args);
pi.RedirectStandardError = true;
pi.RedirectStandardOutput = true;
// if the user specified just a folder, set it as working dir
pi.WorkingDirectory = Path.GetDirectoryName(workingDirectory);
var result = new ProcessOutput();
var output = new DataReceivedEventHandler((s, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
result.Output.Add(e.Data);
});
var error = new DataReceivedEventHandler((s, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
result.Output.Add(e.Data);
});
// how to forward process output to console: https://stackoverflow.com/questions/4291912/process-start-how-to-get-the-output
var process = new Process();
process.StartInfo = pi;
process.EnableRaisingEvents = true;
process.OutputDataReceived += output;
process.ErrorDataReceived += error;
try
{
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
result.ExitCode = process.ExitCode;
return result;
}
finally
{
process.OutputDataReceived -= output;
process.ErrorDataReceived -= error;
}
}
private class ProcessOutput
{
public List<string> Output { get; } = new List<string>();
public int ExitCode { get; set; }
}
private void EnsureCsprojFile(string filePath)
{
if (!string.Equals(Path.GetExtension(filePath), ".csproj", StringComparison.InvariantCultureIgnoreCase))
throw new ArgumentException("filePath must point to *.csproj file");
}
[DebuggerDisplay("{" + nameof(NugetPackageName) + "}")]
private class CsprojInfo
{
public string PackageId { get; }
public string Version { get; private set; }
public string ActualVersion { get; private set; }
public string Path { get; }
public CsprojInfo(string packageId, string version, string path, string packageIdOverride = null)
{
PackageId = packageIdOverride ?? packageId;
Version = version;
Path = path;
ActualVersion = version;
}
public string NugetPackageName => $"{PackageId}.{ActualVersion}.symbols.nupkg";
public string NugetPackageNameShortVersion => $"{PackageId}.{GetActialVersionAsWithoutRevision()}.symbols.nupkg";
private string GetActialVersionAsWithoutRevision()
{
var longVersionString = ActualVersion.ExtractVersionNumber();
var shortVersionString = ActualVersion.ToThreeDigitVersion();
return ActualVersion.Replace(longVersionString, shortVersionString);
}
public IDisposable ReplaceVersion(string newVersion)
{
var findVersion = new Regex(@"<Version>\s*(?<version>\d+\.\d+\.\d+(\.\d+)?[\d\w_-]*?)\s*</Version>");
var txt = File.ReadAllText(Path);
var m = findVersion.Match(txt);
if (m.Success)
{
var versionElement = m.Value;
// if we do not have to replace the version, ignore
if (string.Equals(m.Groups["version"].Value, newVersion))
return NullDisposable.Instance;
// move original csproj to temp folder and afterwards back again so GIT does not complain about any changes
var tempFolder = System.IO.Path.Combine(System.IO.Path.GetTempPath(),
$"debugify_{DateTime.UtcNow:yyyMMddhhmmss}_{Guid.NewGuid():N}");
var tempPath = System.IO.Path.Combine(tempFolder,
System.IO.Path.GetFileName(Path));
Directory.CreateDirectory(tempFolder);
File.Move(Path, tempPath);
var newVersionElement = $"<Version>{newVersion}</Version>";
File.WriteAllText(Path, txt.Replace(versionElement, newVersionElement));
ActualVersion = newVersion;
return new VersionRestorer(Path, tempPath);
}
else
{
var findPropertyGroup = new Regex(@"</PackageId>");
var fm = findPropertyGroup.Match(txt);
if(!fm.Success)
throw new InvalidOperationException($"Not a single </PackageId> element could be found in '{Path}'");
// move original csproj to temp folder and afterwards back again so GIT does not complain about any changes
var tempFolder = System.IO.Path.Combine(System.IO.Path.GetTempPath(),
$"debugify_{DateTime.UtcNow:yyyMMddhhmmss}_{Guid.NewGuid():N}");
var tempPath = System.IO.Path.Combine(tempFolder,
System.IO.Path.GetFileName(Path));
Directory.CreateDirectory(tempFolder);
File.Move(Path, tempPath);
var newVersionElement = $"<Version>{newVersion}</Version>";
// sneak in version element by replacing the FIRST <PropertyGroup> element with a </PackageId>\n<Version>....</Version> element
File.WriteAllText(Path, findPropertyGroup.Replace(txt, $"</PackageId>\n" +newVersionElement, 1));
ActualVersion = newVersion;
return new VersionRestorer(Path, tempPath);
}
}
private class NullDisposable : IDisposable
{
public static IDisposable Instance = new NullDisposable();
private NullDisposable()
{ }
public void Dispose()
{ }
}
private class VersionRestorer : IDisposable
{
private readonly string _path;
private readonly string _tempPath;
public VersionRestorer(string path, string tempPath)
{
_path = path;
_tempPath = tempPath;
}
public void Dispose()
{
File.Delete(_path);
File.Move(_tempPath, _path);
// clean up temporary data
Directory.Delete(System.IO.Path.GetDirectoryName(_tempPath), true);
}
}
}
private class CompositeDisposable : IDisposable
{
private readonly ILogger _logger;
private readonly List<IDisposable> _disposables = new List<IDisposable>();
public CompositeDisposable(ILogger logger)
{
_logger = logger;
}
public void Add(IDisposable child) => _disposables.Add(child);
public void Dispose()
{
foreach(var d in _disposables)
{
try
{