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
56 changes: 55 additions & 1 deletion src/TaskAnalyzer.Tests/MultiThreadableTaskAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1613,7 +1613,61 @@ public override bool Execute()
}
""");

diags.ShouldContain(d => d.Id == DiagnosticIds.TaskEnvironmentRequired);
diags.Length.ShouldBe(1);
diags[0].Id.ShouldBe(DiagnosticIds.TaskEnvironmentRequired);
diags[0].GetMessage().ShouldBe(
"'Path.GetTempFileName()' should use TaskEnvironment alternative: create a unique file under TaskEnvironment.GetTempPath() with Path.GetRandomFileName() and FileMode.CreateNew");
}

[Fact]
public async Task TaskEnvironmentTempFilePattern_NoDiagnostics()
{
var diagnostics = await GetCompilerAndAnalyzerDiagnosticsAsync(
"""
using System.IO;
using Microsoft.Build.Framework;
[MSBuildMultiThreadableTask]
public class MyTask : Microsoft.Build.Utilities.Task, IMultiThreadableTask
{
public TaskEnvironment TaskEnvironment { get; set; } = new();

public override bool Execute()
{
AbsolutePath filePath = CreateTempFile(TaskEnvironment);
File.Delete(filePath);
return true;
}

private static AbsolutePath CreateTempFile(TaskEnvironment taskEnvironment)
{
const int maximumAttempts = 10;
AbsolutePath tempPath = taskEnvironment.GetTempPath();

for (int attempt = 1; ; attempt++)
{
AbsolutePath filePath = new(Path.GetRandomFileName(), tempPath);

try
{
using FileStream stream = new(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None);

return filePath;
}
catch (IOException) when (attempt < maximumAttempts && File.Exists(filePath))
{
}
}
}
}
""",
new MultiThreadableTaskAnalyzer());

diagnostics.Where(diagnostic => diagnostic.Id.StartsWith("CS", System.StringComparison.Ordinal)).ShouldBeEmpty();
diagnostics.Where(diagnostic => diagnostic.Id.StartsWith("MSBuildTask", System.StringComparison.Ordinal)).ShouldBeEmpty();
}

[Theory]
Expand Down
2 changes: 2 additions & 0 deletions src/TaskAnalyzer.Tests/TestHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,14 @@ public class TaskEnvironment
public void SetEnvironmentVariable(string name, string? value) { }
public System.Collections.Generic.IReadOnlyDictionary<string, string> GetEnvironmentVariables() => new System.Collections.Generic.Dictionary<string, string>();
public AbsolutePath GetAbsolutePath(string path) => default;
public AbsolutePath GetTempPath() => default;
public System.Diagnostics.ProcessStartInfo GetProcessStartInfo() => new();
}

public struct AbsolutePath : System.IEquatable<AbsolutePath>
{
public AbsolutePath(string path) { Value = path; OriginalValue = path; }
public AbsolutePath(string path, AbsolutePath basePath) { Value = System.String.Concat(basePath.Value, path); OriginalValue = path; }
public string Value { get; }
public string OriginalValue { get; }
public static implicit operator string(AbsolutePath p) => p.Value;
Expand Down
2 changes: 1 addition & 1 deletion src/TaskAnalyzer/BannedApiDefinitions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ private static ImmutableArray<BannedApi> CreateAll()

// Other temp helpers - depend on environment variables
new BannedApi("M:System.IO.Path.GetTempFileName",
ApiCategory.TaskEnvironment, "depends on TMP/TEMP environment variables; suppress with a justification until a TaskEnvironment alternative is available"),
ApiCategory.TaskEnvironment, "create a unique file under TaskEnvironment.GetTempPath() with Path.GetRandomFileName() and FileMode.CreateNew"),
new BannedApi("M:System.IO.Directory.CreateTempSubdirectory(System.String)",
ApiCategory.TaskEnvironment, "depends on TMP/TEMP environment variables; suppress with a justification until a TaskEnvironment alternative is available"),
new BannedApi("M:System.CodeDom.Compiler.TempFileCollection.#ctor",
Expand Down
45 changes: 42 additions & 3 deletions src/TaskAnalyzer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,54 @@ These APIs access process-global state that varies per task in multithreaded mod
| `Environment.GetFolderPath()` | Use `TaskEnvironment.GetEnvironmentVariable()` |
| `Path.GetFullPath()` | `TaskEnvironment.GetAbsolutePath()` |
| `Path.GetTempPath()` | `TaskEnvironment.GetTempPath()` |
| `Path.GetTempFileName()` | No good workaround until https://github.com/dotnet/msbuild/issues/14583 is resolved. |
| `Directory.CreateTempSubdirectory()` (with or without a prefix) | No good workaround until https://github.com/dotnet/msbuild/issues/14583 is resolved. |
| `Path.GetTempFileName()` | Create a unique file under `TaskEnvironment.GetTempPath()`. See the example below. |
| `Directory.CreateTempSubdirectory()` (with or without a prefix) | No supported equivalent. Suppress the diagnostic with a justification. |
| `new TempFileCollection()` | Pass an explicit task-resolved temporary directory, or suppress with a justification. |
| `Process.Start()` (all overloads) | `TaskEnvironment.GetProcessStartInfo()` |
| `new ProcessStartInfo()` (all overloads) | `TaskEnvironment.GetProcessStartInfo()` |

In multithreaded mode, `TaskEnvironment.GetTempPath()` resolves the temporary folder from the isolated task environment. In multi-process mode, it matches `Path.GetTempPath()`.

The other temp helpers above depend on process-wide temporary-directory environment variables. Until a `TaskEnvironment` alternative is available, suppress `MSBuildTask0002` (or `MSBuildTask0005` for a call through a helper) with a justification. `Path.GetRandomFileName()` only generates a name and does not resolve a temporary directory, so it is not banned.
`Path.GetTempFileName()` creates a unique empty file. `TaskEnvironment.GetTempPath()` only returns the task-local temporary directory. Add this helper to a task class when the task needs the file-creation behavior:

```csharp
using System.IO;
using Microsoft.Build.Framework;

private static AbsolutePath CreateTempFile(TaskEnvironment taskEnvironment)
{
const int maximumAttempts = 10;
AbsolutePath tempPath = taskEnvironment.GetTempPath();

for (int attempt = 1; ; attempt++)
{
AbsolutePath filePath = new(Path.GetRandomFileName(), tempPath);

try
{
using FileStream stream = new(
filePath,
FileMode.CreateNew,
FileAccess.Write,
FileShare.None);

return filePath;
}
catch (IOException) when (attempt < maximumAttempts && File.Exists(filePath))
{
// Try another name. The final attempt preserves the I/O exception.
}
}
}
```

`FileMode.CreateNew` prevents the helper from overwriting an existing file. The filter retries only when the generated file already exists. Other I/O errors stop the operation immediately.

The caller owns the returned file. Delete the file when the task no longer needs it. MSBuild does not provide a `TaskEnvironment.GetTempFileName()` convenience API.

`Directory.CreateTempSubdirectory()` still has no supported task-local equivalent. Suppress `MSBuildTask0002`, or `MSBuildTask0005` for a helper call, with a justification.

`Path.GetRandomFileName()` only generates a name. It does not resolve a temporary directory, so TaskAnalyzer does not ban it.

`TempFileCollection` constructors accepting `tempDir` are not banned because they can use an explicit task-resolved directory. Passing null or empty still falls back to the global temporary directory; this conditional usage is not currently detected.

Expand Down
Loading