Created
June 2, 2020 16:12
-
-
Save kbaley/2f93a9f4f20f44a66d01da9e41bbc6a6 to your computer and use it in GitHub Desktop.
Parse a list of dependencies out of a folder containing .csproj files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static async Task GetDependencies() | |
{ | |
var root = Path.Combine(Directory.GetCurrentDirectory(), "Projects"); | |
var files = Directory.EnumerateFiles(root, "*.csproj", SearchOption.AllDirectories); | |
var packages = new List<string>(); | |
var mapFile = Path.Combine(Directory.GetCurrentDirectory(), "projectPackageMap.tsv"); | |
File.Delete(mapFile); | |
// if (File.Exists(mapFile)) File.Delete(mapFile); | |
foreach (var file in files) | |
{ | |
var path = file.Split("/Projects/")[1]; | |
var projectName = path.Split("/")[0]; | |
var doc = XDocument.Load(file).Descendants("PackageReference"); | |
foreach (var packageReference in doc) | |
{ | |
var includeAttr = packageReference.Attributes() | |
.SingleOrDefault(a => Matches(a, "include")); | |
if (includeAttr == null) { | |
// Some PackageReference nodes don't have an 'Include' attribute | |
Console.WriteLine(path); | |
continue; | |
}; | |
var versionAttr = packageReference.Attributes() | |
.Single(a => Matches(a, "version")); | |
var package = includeAttr.Value; | |
var version = versionAttr.Value; | |
File.AppendAllText(mapFile, $"{projectName}\t{path}\t{package}\t{version}\n"); | |
var packageKey = $"{package}\t{version}"; | |
if (!packages.Contains(packageKey)) { | |
packages.Add(packageKey); | |
} | |
} | |
} | |
packages.Sort(); | |
var packagesFile = Path.Combine(Directory.GetCurrentDirectory(), "packages.tsv"); | |
File.WriteAllLines(packagesFile, packages); | |
} | |
public static bool Matches(XAttribute attribute, string nameToMatch) { | |
return attribute.Name.LocalName.Equals(nameToMatch, StringComparison.InvariantCultureIgnoreCase); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment