Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@

namespace Microsoft.AspNetCore.StaticWebAssets.Tasks;

public class GenerateStaticWebAssetEndpointsManifest : Task
[MSBuildMultiThreadableTask]
public class GenerateStaticWebAssetEndpointsManifest : Task, IMultiThreadableTask
{
/// <inheritdoc/>
public TaskEnvironment TaskEnvironment { get; set; } = TaskEnvironment.Fallback;

[Required]
public ITaskItem[] Assets { get; set; } = [];

Expand All @@ -32,12 +36,16 @@ public class GenerateStaticWebAssetEndpointsManifest : Task

public override bool Execute()
{
var manifestAbsolutePath = !string.IsNullOrEmpty(ManifestPath) ? TaskEnvironment.GetAbsolutePath(ManifestPath).Value : ManifestPath;
var cacheAbsolutePath = !string.IsNullOrEmpty(CacheFilePath) ? TaskEnvironment.GetAbsolutePath(CacheFilePath).Value : CacheFilePath;
var exclusionCacheAbsolutePath = !string.IsNullOrEmpty(ExclusionPatternsCacheFilePath) ? TaskEnvironment.GetAbsolutePath(ExclusionPatternsCacheFilePath).Value : ExclusionPatternsCacheFilePath;

var (patternString, parsedPatterns) = ParseAndSortPatterns(ExclusionPatterns);
var existingPatternString = !string.IsNullOrEmpty(ExclusionPatternsCacheFilePath) && File.Exists(ExclusionPatternsCacheFilePath)
? File.ReadAllText(ExclusionPatternsCacheFilePath)
var existingPatternString = !string.IsNullOrEmpty(ExclusionPatternsCacheFilePath) && File.Exists(exclusionCacheAbsolutePath)
? File.ReadAllText(exclusionCacheAbsolutePath)
: null;
existingPatternString = string.IsNullOrEmpty(existingPatternString) ? null : existingPatternString;
if (!string.IsNullOrEmpty(CacheFilePath) && File.Exists(ManifestPath) && File.GetLastWriteTimeUtc(ManifestPath) > File.GetLastWriteTimeUtc(CacheFilePath))
if (!string.IsNullOrEmpty(CacheFilePath) && File.Exists(manifestAbsolutePath) && File.GetLastWriteTimeUtc(manifestAbsolutePath) > File.GetLastWriteTimeUtc(cacheAbsolutePath))
{
// Check if exclusion patterns cache is also up to date
if (string.Equals(patternString, existingPatternString, StringComparison.Ordinal))
Expand All @@ -60,10 +68,10 @@ public override bool Execute()
try
{
// Update exclusion patterns cache if needed
UpdateExclusionPatternsCache(existingPatternString, patternString);
UpdateExclusionPatternsCache(existingPatternString, patternString, manifestAbsolutePath, exclusionCacheAbsolutePath);

// Get the list of the asset that need to be part of the manifest (this is similar to GenerateStaticWebAssetsDevelopmentManifest)
var assets = StaticWebAsset.FromTaskItemGroup(Assets);
var assets = StaticWebAsset.FromTaskItemGroup(Assets, TaskEnvironment);
var manifestAssets = ComputeManifestAssets(assets, ManifestType)
.ToDictionary(a => a.ResolvedAsset.Identity, a => a, OSPath.PathComparer);

Expand Down Expand Up @@ -95,15 +103,15 @@ public override bool Execute()
var match = exclusionMatcher.Match(route);
if (match.IsMatch)
{
if (!updatedManifest && File.Exists(ManifestPath))
if (!updatedManifest && File.Exists(manifestAbsolutePath))
{
updatedManifest = true;
// Touch the manifest if we are excluding endpoints to ensure we don't keep reporting out of date
// for the excluded endpoints.
// (The SWA manifest we use as cache might get updated, but if we filter out the new endpoints, we won't
// update the endpoints manifest file and on the next build we will re-enter this loop).
Log.LogMessage(MessageImportance.Low, "Updating manifest timestamp '{0}'.", ManifestPath);
File.SetLastWriteTime(ManifestPath, DateTime.UtcNow);
File.SetLastWriteTime(manifestAbsolutePath, DateTime.UtcNow);
}
Log.LogMessage(MessageImportance.Low, "Excluding endpoint '{0}' based on exclusion patterns", route);
continue;
Expand All @@ -128,7 +136,7 @@ public override bool Execute()
Endpoints = [.. filteredEndpoints]
};

this.PersistFileIfChanged(manifest, ManifestPath, StaticWebAssetsJsonSerializerContext.RelaxedEscaping.StaticWebAssetEndpointsManifest);
this.PersistFileIfChanged(manifest, manifestAbsolutePath, StaticWebAssetsJsonSerializerContext.RelaxedEscaping.StaticWebAssetEndpointsManifest);
}
Comment thread
jankratochvilcz marked this conversation as resolved.
Resolved
catch (Exception ex)
{
Expand Down Expand Up @@ -194,27 +202,27 @@ private static (string, string[]) ParseAndSortPatterns(string patterns)
return (string.Join(Environment.NewLine, parsed), parsed);
}

private void UpdateExclusionPatternsCache(string existingPatternString, string patternString)
private void UpdateExclusionPatternsCache(string existingPatternString, string patternString, string manifestAbsolutePath, string exclusionCacheAbsolutePath)
{
if (string.IsNullOrEmpty(ExclusionPatternsCacheFilePath))
{
return;
}

if (!File.Exists(ExclusionPatternsCacheFilePath) ||
if (!File.Exists(exclusionCacheAbsolutePath) ||
!string.Equals(existingPatternString, patternString, StringComparison.Ordinal))
{
var directoryName = Path.GetDirectoryName(ExclusionPatternsCacheFilePath);
var directoryName = Path.GetDirectoryName(exclusionCacheAbsolutePath);
if (directoryName != null)
{
Directory.CreateDirectory(directoryName);
}
File.WriteAllText(ExclusionPatternsCacheFilePath, patternString);
File.WriteAllText(exclusionCacheAbsolutePath, patternString);
// We need to touch the file because otherwise we will keep thinking that is out of date in the future.
// This file might not be rewritten if the results are unchanged.
if (File.Exists(ManifestPath))
if (File.Exists(manifestAbsolutePath))
{
File.SetLastWriteTime(ManifestPath, DateTime.UtcNow);
File.SetLastWriteTime(manifestAbsolutePath, DateTime.UtcNow);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#nullable disable

using Microsoft.AspNetCore.StaticWebAssets.Tasks;
using Microsoft.Build.Framework;
using Moq;

namespace Microsoft.NET.Sdk.StaticWebAssets.Tests;

// Test parallelization is disabled assembly-wide: the MSTest.Sdk project sets
// MSTestParallelizeScope=None, which emits [assembly: DoNotParallelize] and runs
// tests sequentially, isolating the process-CWD mutation this test performs.
[TestClass]
public class GenerateStaticWebAssetEndpointsManifestMultiThreadingTest
{
// Deliberately short: the layout below nests several levels under the test binary
// directory and Directory.SetCurrentDirectory is still limited to MAX_PATH on Windows.
private const string TestRootName = "GSWAEndpointsManifestMT";

[TestMethod]
public void WritesEndpointsManifestAndExclusionCacheRelativeToTaskEnvironmentProjectDirectory_NotProcessCurrentDirectory()
{
// Layout: place project and decoy in disjoint subtrees so that the same
// relative path produces different absolute paths from each root.
// <testRoot>/p/output/ <-- TaskEnvironment.ProjectDirectory
// <testRoot>/d/s/ <-- process CWD (the "decoy")
// <testRoot>/d/s/output/ <-- where the pre-migration code would write
// Path segments are kept short because Directory.SetCurrentDirectory is limited to
// MAX_PATH on Windows even when long paths are otherwise enabled.
var testRoot = Path.Combine(AppContext.BaseDirectory, TestRootName, Guid.NewGuid().ToString("N")[..8]);
var projectDir = Path.Combine(testRoot, "p");
var spawnDir = Path.Combine(testRoot, "d", "s");
var projectOutputDir = Path.Combine(projectDir, "output");
var spawnOutputDir = Path.Combine(spawnDir, "output");
Directory.CreateDirectory(projectOutputDir);
Directory.CreateDirectory(spawnOutputDir);

var originalCurrentDirectory = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(spawnDir);

var errorMessages = new List<string>();
var messages = new List<string>();
var buildEngine = new Mock<IBuildEngine>();
buildEngine.Setup(e => e.LogErrorEvent(It.IsAny<BuildErrorEventArgs>()))
.Callback<BuildErrorEventArgs>(args => errorMessages.Add(args.Message));
buildEngine.Setup(e => e.LogMessageEvent(It.IsAny<BuildMessageEventArgs>()))
.Callback<BuildMessageEventArgs>(args => messages.Add(args.Message));

var task = new GenerateStaticWebAssetEndpointsManifest
{
BuildEngine = buildEngine.Object,
TaskEnvironment = TaskEnvironment.CreateWithProjectDirectoryAndEnvironment(projectDir),
Assets = Array.Empty<ITaskItem>(),
Endpoints = Array.Empty<ITaskItem>(),
Source = "MyProject",
ManifestType = "Build",
ExclusionPatterns = "**/excluded.txt",
ManifestPath = Path.Combine("output", "endpoints.json"),
CacheFilePath = Path.Combine("output", "endpoints.cache"),
ExclusionPatternsCacheFilePath = Path.Combine("output", "exclusions.cache"),
};

task.Execute().Should().BeTrue(string.Join("; ", errorMessages));

var expectedManifest = Path.Combine(projectOutputDir, "endpoints.json");
var expectedExclusionCache = Path.Combine(projectOutputDir, "exclusions.cache");
File.Exists(expectedManifest).Should().BeTrue("endpoints manifest must be written under TaskEnvironment.ProjectDirectory, not the process CWD");
File.Exists(expectedExclusionCache).Should().BeTrue("exclusion-patterns cache must be written under TaskEnvironment.ProjectDirectory, not the process CWD");

File.Exists(Path.Combine(spawnOutputDir, "endpoints.json")).Should().BeFalse();
File.Exists(Path.Combine(spawnOutputDir, "exclusions.cache")).Should().BeFalse();
messages.Should().Contain($"Creating artifact because artifact file '{expectedManifest}' does not exist.");
}
finally
{
Directory.SetCurrentDirectory(originalCurrentDirectory);
if (Directory.Exists(testRoot))
{
Directory.Delete(testRoot, recursive: true);
}
}
}

[TestMethod]
[OSCondition(OperatingSystems.Linux | OperatingSystems.OSX)]
public void WritesEndpointsManifestWhenPathIsWhitespace()
{
var projectDir = Path.Combine(AppContext.BaseDirectory, TestRootName, Guid.NewGuid().ToString("N")[..8], "ws");
Directory.CreateDirectory(projectDir);

try
{
var task = new GenerateStaticWebAssetEndpointsManifest
{
BuildEngine = new Mock<IBuildEngine>().Object,
TaskEnvironment = TaskEnvironment.CreateWithProjectDirectoryAndEnvironment(projectDir),
Assets = [],
Endpoints = [],
Source = "MyProject",
ManifestType = "Build",
ManifestPath = " ",
};

task.Execute().Should().BeTrue();
File.Exists(Path.Combine(projectDir, " ")).Should().BeTrue();
}
finally
{
Directory.Delete(projectDir, recursive: true);
}
}
}
Loading