Repository navigation
feat(workflow): Project Native .NET Graph and Input Ownership #1047
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
112 changes: 112 additions & 0 deletions
112
src/private/app/workflow-delivery/Repository/DotNetGraph.cs
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| using Microsoft.Build.Execution; | ||
| using Microsoft.Build.Graph; | ||
|
|
||
| namespace WorkflowDelivery.Repository; | ||
|
|
||
| internal sealed record DotNetGraphRequest(string Revision, string Root, string Entry, | ||
| Dictionary<string, string> Globals, string Destination, string[] CommittedPaths); | ||
| internal sealed record DotNetNodeIdentity(string Project, Dictionary<string, string> Globals); | ||
| internal sealed record DotNetGraphNode(DotNetNodeIdentity Identity, bool OuterBuild, | ||
| MsBuildDimension Dimension, string TargetFrameworks, string RuntimeIdentifiers, | ||
| string[] OwnedPaths); | ||
| internal sealed record DotNetGraphEdge(DotNetNodeIdentity Consumer, DotNetNodeIdentity Dependency); | ||
| internal sealed record DotNetGraphInput(string Path, string Role, string Stage, | ||
| DotNetNodeIdentity Consumer); | ||
| internal sealed record DotNetGraphResponse(string Revision, string Root, string Entry, | ||
| DotNetGraphNode[] Nodes, DotNetGraphEdge[] Edges, DotNetGraphInput[] Inputs); | ||
|
|
||
| // Called only inside the endpoint-selected MSBuild process. MSBuild owns graph construction. | ||
| internal static class DotNetGraph | ||
| { | ||
| private static readonly string[] CallerVariantSelectors = ["TargetFramework", | ||
| "TargetFrameworks", "RuntimeIdentifier", "RuntimeIdentifiers"]; | ||
| private static readonly string[] EvaluatedInputTypes = ["Compile", "EmbeddedResource", | ||
| "Content", "None", "AdditionalFiles", "Analyzer", "EditorConfigFiles", | ||
| "GlobalAnalyzerConfigFiles", "ApplicationDefinition", "Page", "Resource", | ||
| "SplashScreen"]; | ||
|
|
||
| internal static DotNetGraphResponse Read(DotNetGraphRequest request) | ||
| { | ||
| if (request.Revision.Length != 40 || | ||
| request.Revision.Any(value => !char.IsAsciiHexDigit(value))) | ||
| throw new InvalidDataException("Native graph requires an exact endpoint revision."); | ||
| string root = Path.TrimEndingDirectorySeparator(Absolute(request.Root)); | ||
| string entry = Absolute(request.Entry); | ||
| string relative = Path.GetRelativePath(root, entry); | ||
| if (Path.IsPathRooted(relative) || relative == ".." || | ||
| relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) | ||
| throw new InvalidDataException("Native graph entry is outside its endpoint."); | ||
| if (!File.Exists(entry)) | ||
| throw new InvalidDataException("Native graph entry is unavailable."); | ||
| if (request.Globals.Keys.Any(name => CallerVariantSelectors.Contains(name, | ||
| StringComparer.OrdinalIgnoreCase))) | ||
| throw new InvalidDataException( | ||
| "Native graph discovery does not accept caller variant selectors."); | ||
| if (!request.Globals.TryGetValue("Configuration", out string? configuration) || | ||
| configuration != "Debug" || | ||
| !request.Globals.TryGetValue("ContinuousIntegrationBuild", out string? ci) || | ||
| ci != "true" || | ||
| !request.Globals.TryGetValue("RestoreLockedMode", out string? locked) || | ||
| locked != "true") | ||
| throw new InvalidDataException("Native graph requires the supported CI operation."); | ||
|
hcoona marked this conversation as resolved.
|
||
| var graph = new ProjectGraph(entry, request.Globals); | ||
| var identities = graph.ProjectNodes.ToDictionary(node => node, | ||
| node => Identity(node.ProjectInstance)); | ||
| var ownership = new DotNetOwnership(root, graph.ProjectNodes.Select(node => | ||
| node.ProjectInstance), request.CommittedPaths); | ||
| DotNetGraphNode[] nodes = graph.ProjectNodes.Select(node => | ||
| { | ||
| ProjectInstance project = node.ProjectInstance; | ||
| string outer = project.GetPropertyValue("IsCrossTargetingBuild"); | ||
| if (outer != "" && !bool.TryParse(outer, out _)) | ||
| throw new InvalidDataException("Unsupported native outer-build identity."); | ||
| return new DotNetGraphNode(identities[node], | ||
| string.Equals(outer, "true", StringComparison.OrdinalIgnoreCase), | ||
| new(project.GetPropertyValue("Configuration"), | ||
| project.GetPropertyValue("TargetFramework"), | ||
| project.GetPropertyValue("RuntimeIdentifier")), | ||
| project.GetPropertyValue("TargetFrameworks"), | ||
| project.GetPropertyValue("RuntimeIdentifiers"), ownership.Read(project)); | ||
| }).ToArray(); | ||
| DotNetGraphEdge[] edges = graph.ProjectNodes.SelectMany(node => | ||
| node.ProjectReferences.Select(dependency => | ||
| new DotNetGraphEdge(identities[node], identities[dependency]))).ToArray(); | ||
| DotNetGraphInput[] inputs = graph.ProjectNodes.SelectMany(node => | ||
| { | ||
| ProjectInstance project = node.ProjectInstance; | ||
| DotNetNodeIdentity consumer = identities[node]; | ||
| return new[] { new DotNetGraphInput(Absolute(project.FullPath), "Project", | ||
| "Evaluation", consumer) } | ||
| .Concat(project.ImportPaths.Select(path => new DotNetGraphInput(Absolute(path), | ||
| "Import", "Evaluation", consumer))) | ||
| .Concat(EvaluatedInputTypes.SelectMany(type => project.GetItems(type) | ||
| .Select(item => new DotNetGraphInput( | ||
| Absolute(item.GetMetadataValue("FullPath")), type, | ||
| "Evaluation", consumer)))); | ||
| }).ToArray(); | ||
| return new(request.Revision, root, entry, nodes, edges, inputs); | ||
|
|
||
| DotNetNodeIdentity Identity(ProjectInstance project) | ||
| { | ||
| var globals = new Dictionary<string, string>(StringComparer.Ordinal); | ||
| foreach (var property in project.GlobalProperties.OrderBy(property => | ||
| property.Key, StringComparer.Ordinal)) | ||
| { | ||
| if (property.Value.Replace('\\', '/').Contains(root.Replace('\\', '/'), | ||
| OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : | ||
| StringComparison.Ordinal)) | ||
| throw new InvalidDataException( | ||
| "Endpoint-dependent native semantic global: " + property.Key); | ||
| globals.Add(property.Key, property.Value); | ||
| } | ||
| return new(Absolute(project.FullPath), globals); | ||
| } | ||
| } | ||
|
|
||
| private static string Absolute(string path) | ||
| { | ||
| if (!Path.IsPathFullyQualified(path)) | ||
| throw new InvalidDataException("Native graph coordinates must be absolute."); | ||
| return Path.GetFullPath(path); | ||
| } | ||
| } | ||
26 changes: 26 additions & 0 deletions
26
src/private/app/workflow-delivery/Repository/DotNetGraphTask.cs
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| using System.Text.Json; | ||
| using Microsoft.Build.Framework; | ||
|
|
||
| namespace WorkflowDelivery.Repository; | ||
|
|
||
| // The existing application supplies this entry; ordinary MSBuild loads its dependencies. | ||
| public sealed class DotNetGraphTask : ITask | ||
| { | ||
| public IBuildEngine BuildEngine { get; set; } = null!; | ||
| public ITaskHost HostObject { get; set; } = null!; | ||
|
|
||
| [Required] | ||
| public string RequestFile { get; set; } = ""; | ||
|
|
||
| public bool Execute() | ||
| { | ||
| DotNetGraphRequest request = JsonSerializer.Deserialize(File.ReadAllText(RequestFile), | ||
| TransferJson.Default.DotNetGraphRequest) | ||
| ?? throw new InvalidDataException("Missing native graph request."); | ||
| DotNetGraphResponse response = DotNetGraph.Read(request); | ||
| using var output = new FileStream(request.Destination, FileMode.CreateNew, | ||
| FileAccess.Write, FileShare.None); | ||
| JsonSerializer.Serialize(output, response, TransferJson.Default.DotNetGraphResponse); | ||
| return true; | ||
| } | ||
| } |
76 changes: 76 additions & 0 deletions
76
src/private/app/workflow-delivery/Repository/DotNetOwnership.cs
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| using Microsoft.Build.Evaluation; | ||
| using Microsoft.Build.Execution; | ||
| using Microsoft.Build.Globbing; | ||
|
|
||
| namespace WorkflowDelivery.Repository; | ||
|
|
||
| // Git supplies committed entries; the selected MSBuild supplies region exclusions. | ||
| internal sealed class DotNetOwnership | ||
| { | ||
| private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() | ||
| ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; | ||
| private readonly string[] _regions; | ||
| private readonly string[] _paths; | ||
|
|
||
| internal DotNetOwnership(string root, IEnumerable<ProjectInstance> projects, | ||
| string[] committedPaths) | ||
| { | ||
| _regions = projects.Where(IsManagedProject).Select(project => | ||
| Path.GetDirectoryName(project.FullPath)!) | ||
| .Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : | ||
| StringComparer.Ordinal).OrderByDescending(path => path.Length).ToArray(); | ||
| _paths = committedPaths.Select(path => | ||
| { | ||
| if (!Path.IsPathFullyQualified(path)) | ||
| throw new InvalidDataException( | ||
| "Committed ownership coordinates must be absolute."); | ||
| string full = Path.GetFullPath(path); | ||
| if (!Inside(root, full)) | ||
| throw new InvalidDataException( | ||
| "Committed ownership entry is outside its endpoint."); | ||
| return full; | ||
| }).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); | ||
| } | ||
|
|
||
| internal string[] Read(ProjectInstance project) | ||
| { | ||
| if (!IsManagedProject(project)) return []; | ||
| string directory = Path.GetDirectoryName(project.FullPath)!; | ||
| MSBuildGlob[] excludes = Excludes("DefaultItemExcludes") | ||
| .Concat(Excludes("DefaultExcludesInProjectFolder")).ToArray(); | ||
| return _paths.Where(path => | ||
| string.Equals(_regions.FirstOrDefault(region => Inside(region, path)), directory, | ||
| PathComparison) && !excludes.Any(glob => glob.IsMatch(path))).ToArray(); | ||
|
|
||
| IEnumerable<MSBuildGlob> Excludes(string name) | ||
| { | ||
| ProjectPropertyInstance? property = project.GetProperty(name); | ||
| if (property is null) yield break; | ||
| // Split while escaped so a literal semicolon cannot become a list separator. | ||
| foreach (string spec in ProjectInstance.GetPropertyValueEscaped(property) | ||
| .Split(';', StringSplitOptions.RemoveEmptyEntries | | ||
| StringSplitOptions.TrimEntries)) | ||
| { | ||
| if (spec.Contains("%2a", StringComparison.OrdinalIgnoreCase) || | ||
| spec.Contains("%3f", StringComparison.OrdinalIgnoreCase)) | ||
| throw new InvalidDataException( | ||
| "Unsupported escaped native ownership wildcard."); | ||
| MSBuildGlob glob = MSBuildGlob.Parse(directory, ProjectCollection.Unescape(spec)); | ||
| if (!glob.IsLegal) | ||
| throw new InvalidDataException("Illegal native ownership filespec: " + name); | ||
| yield return glob; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static bool IsManagedProject(ProjectInstance project) | ||
| { | ||
| string extension = Path.GetExtension(project.FullPath); | ||
| return extension.Equals(".csproj", StringComparison.OrdinalIgnoreCase) || | ||
| extension.Equals(".fsproj", StringComparison.OrdinalIgnoreCase) || | ||
| extension.Equals(".vbproj", StringComparison.OrdinalIgnoreCase); | ||
| } | ||
|
|
||
| private static bool Inside(string directory, string path) => path.StartsWith( | ||
| Path.TrimEndingDirectorySeparator(directory) + Path.DirectorySeparatorChar, PathComparison); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.