From 7e4e244e0810857f39acb3ee1cbce940cd4e89b0 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Tue, 13 Jan 2026 11:25:24 -0600 Subject: [PATCH 01/27] support binding to AbsolutePath and AbsolutePath[] for task input/output parameters. --- .../BackEnd/TaskBuilderTestTask.cs | 60 ++++ .../BackEnd/TaskExecutionHost_Tests.cs | 93 +++++ .../TaskParameterTypeVerifier_Tests.cs | 326 ++++++++++++++++++ .../TaskExecutionHost/TaskExecutionHost.cs | 18 +- src/Shared/TaskParameterTypeVerifier.cs | 15 +- 5 files changed, 505 insertions(+), 7 deletions(-) create mode 100644 src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs diff --git a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs index c66854b0206..1ffd91acd4e 100644 --- a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs +++ b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs @@ -236,6 +236,16 @@ public CustomStruct(IConvertible value) /// private ITaskItem[] _itemArrayOutput; + /// + /// The value for the AbsolutePathOutput. + /// + private AbsolutePath _absolutePathOutput; + + /// + /// The value for the AbsolutePathArrayOutput. + /// + private AbsolutePath[] _absolutePathArrayOutput; + /// /// Property determining if Execute() should throw or not. /// @@ -629,6 +639,30 @@ public ITaskItem[] ItemArrayParam } } + /// + /// An AbsolutePath parameter. + /// + public AbsolutePath AbsolutePathParam + { + set + { + _absolutePathOutput = value; + _testTaskHost?.ParameterSet("AbsolutePathParam", value); + } + } + + /// + /// An AbsolutePath array parameter. + /// + public AbsolutePath[] AbsolutePathArrayParam + { + set + { + _absolutePathArrayOutput = value; + _testTaskHost?.ParameterSet("AbsolutePathArrayParam", value); + } + } + /// /// The Execute return value parameter. /// @@ -1175,6 +1209,32 @@ public ITaskItem[] ItemArrayNullOutput } } + /// + /// An AbsolutePath output. + /// + [Output] + public AbsolutePath AbsolutePathOutput + { + get + { + _testTaskHost?.OutputRead("AbsolutePathOutput", _absolutePathOutput); + return _absolutePathOutput; + } + } + + /// + /// An AbsolutePath array output. + /// + [Output] + public AbsolutePath[] AbsolutePathArrayOutput + { + get + { + _testTaskHost?.OutputRead("AbsolutePathArrayOutput", _absolutePathArrayOutput); + return _absolutePathArrayOutput; + } + } + [Output] public TargetBuiltReason EnumOutput => TargetBuiltReason.BeforeTargets; diff --git a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs index ee01e1ad11f..03392859de3 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -471,6 +471,99 @@ public void TestSetStringArrayParamEmptyItem() #endregion + #region AbsolutePath Params + + /// + /// Validate that setting an AbsolutePath parameter with a valid absolute path works. + /// + [Fact] + public void TestSetAbsolutePathParam() + { + string absolutePath = NativeMethodsShared.IsWindows ? @"C:\temp\file.txt" : "/tmp/file.txt"; + ValidateTaskParameter("AbsolutePathParam", absolutePath, new AbsolutePath(absolutePath)); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetAbsolutePathParamEmptyAttribute() + { + ValidateTaskParameterNotSet("AbsolutePathParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetAbsolutePathParamEmptyProperty() + { + ValidateTaskParameterNotSet("AbsolutePathParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetAbsolutePathParamEmptyItem() + { + ValidateTaskParameterNotSet("AbsolutePathParam", "@(NonExistentItem)"); + } + + #endregion + + #region AbsolutePath Array Params + + /// + /// Validate that setting an AbsolutePath array with a single value sets the correct value. + /// + [Fact] + public void TestSetAbsolutePathArrayParam() + { + string absolutePath = NativeMethodsShared.IsWindows ? @"C:\temp\file.txt" : "/tmp/file.txt"; + ValidateTaskParameterArray("AbsolutePathArrayParam", absolutePath, new AbsolutePath[] { new AbsolutePath(absolutePath) }); + } + + /// + /// Validate that setting an AbsolutePath array with multiple values sets the correct values. + /// + [Fact] + public void TestSetAbsolutePathArrayParamMultiple() + { + string path1 = NativeMethodsShared.IsWindows ? @"C:\temp\file1.txt" : "/tmp/file1.txt"; + string path2 = NativeMethodsShared.IsWindows ? @"C:\temp\file2.txt" : "/tmp/file2.txt"; + ValidateTaskParameterArray("AbsolutePathArrayParam", path1 + ";" + path2, new AbsolutePath[] { new AbsolutePath(path1), new AbsolutePath(path2) }); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetAbsolutePathArrayParamEmptyAttribute() + { + ValidateTaskParameterNotSet("AbsolutePathArrayParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetAbsolutePathArrayParamEmptyProperty() + { + ValidateTaskParameterNotSet("AbsolutePathArrayParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetAbsolutePathArrayParamEmptyItem() + { + ValidateTaskParameterNotSet("AbsolutePathArrayParam", "@(NonExistentItem)"); + } + + #endregion + #region ITaskItem Params /// diff --git a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs new file mode 100644 index 00000000000..1f1f00d6fad --- /dev/null +++ b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs @@ -0,0 +1,326 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using Microsoft.Build.BackEnd; +using Microsoft.Build.Framework; +using Xunit; + +#nullable disable + +namespace Microsoft.Build.UnitTests.BackEnd +{ + /// + /// Tests for TaskParameterTypeVerifier class + /// + public class TaskParameterTypeVerifier_Tests + { + #region IsValidScalarInputParameter Tests + + [Fact] + public void IsValidScalarInputParameter_String_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(string))); + } + + [Fact] + public void IsValidScalarInputParameter_ITaskItem_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(ITaskItem))); + } + + [Fact] + public void IsValidScalarInputParameter_Bool_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(bool))); + } + + [Fact] + public void IsValidScalarInputParameter_Int_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(int))); + } + + [Fact] + public void IsValidScalarInputParameter_Double_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(double))); + } + + [Fact] + public void IsValidScalarInputParameter_DateTime_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(DateTime))); + } + + [Fact] + public void IsValidScalarInputParameter_AbsolutePath_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(AbsolutePath))); + } + + [Fact] + public void IsValidScalarInputParameter_Object_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(object))); + } + + [Fact] + public void IsValidScalarInputParameter_StringArray_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(string[]))); + } + + #endregion + + #region IsValidVectorInputParameter Tests + + [Fact] + public void IsValidVectorInputParameter_StringArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(string[]))); + } + + [Fact] + public void IsValidVectorInputParameter_ITaskItemArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(ITaskItem[]))); + } + + [Fact] + public void IsValidVectorInputParameter_BoolArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(bool[]))); + } + + [Fact] + public void IsValidVectorInputParameter_IntArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(int[]))); + } + + [Fact] + public void IsValidVectorInputParameter_DoubleArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(double[]))); + } + + [Fact] + public void IsValidVectorInputParameter_DateTimeArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(DateTime[]))); + } + + [Fact] + public void IsValidVectorInputParameter_AbsolutePathArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(AbsolutePath[]))); + } + + [Fact] + public void IsValidVectorInputParameter_String_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(string))); + } + + [Fact] + public void IsValidVectorInputParameter_ObjectArray_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(object[]))); + } + + #endregion + + #region IsValueTypeOutputParameter Tests + + [Fact] + public void IsValueTypeOutputParameter_String_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(string))); + } + + [Fact] + public void IsValueTypeOutputParameter_Bool_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(bool))); + } + + [Fact] + public void IsValueTypeOutputParameter_Int_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(int))); + } + + [Fact] + public void IsValueTypeOutputParameter_AbsolutePath_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(AbsolutePath))); + } + + [Fact] + public void IsValueTypeOutputParameter_StringArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(string[]))); + } + + [Fact] + public void IsValueTypeOutputParameter_BoolArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(bool[]))); + } + + [Fact] + public void IsValueTypeOutputParameter_IntArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(int[]))); + } + + [Fact] + public void IsValueTypeOutputParameter_AbsolutePathArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(AbsolutePath[]))); + } + + [Fact] + public void IsValueTypeOutputParameter_ITaskItem_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(ITaskItem))); + } + + [Fact] + public void IsValueTypeOutputParameter_Object_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValueTypeOutputParameter(typeof(object))); + } + + #endregion + + #region IsValidInputParameter Tests + + [Fact] + public void IsValidInputParameter_String_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidInputParameter(typeof(string))); + } + + [Fact] + public void IsValidInputParameter_ITaskItem_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidInputParameter(typeof(ITaskItem))); + } + + [Fact] + public void IsValidInputParameter_Bool_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidInputParameter(typeof(bool))); + } + + [Fact] + public void IsValidInputParameter_AbsolutePath_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidInputParameter(typeof(AbsolutePath))); + } + + [Fact] + public void IsValidInputParameter_StringArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidInputParameter(typeof(string[]))); + } + + [Fact] + public void IsValidInputParameter_ITaskItemArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidInputParameter(typeof(ITaskItem[]))); + } + + [Fact] + public void IsValidInputParameter_BoolArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidInputParameter(typeof(bool[]))); + } + + [Fact] + public void IsValidInputParameter_AbsolutePathArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidInputParameter(typeof(AbsolutePath[]))); + } + + [Fact] + public void IsValidInputParameter_Object_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValidInputParameter(typeof(object))); + } + + [Fact] + public void IsValidInputParameter_ObjectArray_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValidInputParameter(typeof(object[]))); + } + + #endregion + + #region IsValidOutputParameter Tests + + [Fact] + public void IsValidOutputParameter_String_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(string))); + } + + [Fact] + public void IsValidOutputParameter_ITaskItem_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem))); + } + + [Fact] + public void IsValidOutputParameter_Bool_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(bool))); + } + + [Fact] + public void IsValidOutputParameter_AbsolutePath_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(AbsolutePath))); + } + + [Fact] + public void IsValidOutputParameter_StringArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(string[]))); + } + + [Fact] + public void IsValidOutputParameter_ITaskItemArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem[]))); + } + + [Fact] + public void IsValidOutputParameter_BoolArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(bool[]))); + } + + [Fact] + public void IsValidOutputParameter_AbsolutePathArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(AbsolutePath[]))); + } + + [Fact] + public void IsValidOutputParameter_Object_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(object))); + } + + [Fact] + public void IsValidOutputParameter_ObjectArray_ReturnsFalse() + { + Assert.False(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(object[]))); + } + + #endregion + } +} diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index 29287c606e6..907282c969c 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -775,6 +775,10 @@ private bool SetValueParameter(TaskPropertyInfo parameter, Type parameterType, s { return InternalSetTaskParameter(parameter, expandedParameterValue); } + else if (parameterType == typeof(AbsolutePath)) + { + return InternalSetTaskParameter(parameter, TaskEnvironment.GetAbsolutePath(expandedParameterValue)); + } else { return InternalSetTaskParameter(parameter, Convert.ChangeType(expandedParameterValue, parameterType, CultureInfo.InvariantCulture)); @@ -806,6 +810,10 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I { finalTaskInputs.Add(ConversionUtilities.ConvertStringToBool(item.ItemSpec)); } + else if (parameterType == typeof(AbsolutePath[])) + { + finalTaskInputs.Add(TaskEnvironment.GetAbsolutePath(item.ItemSpec)); + } else { finalTaskInputs.Add(Convert.ChangeType(item.ItemSpec, parameterType.GetElementType(), CultureInfo.InvariantCulture)); @@ -892,7 +900,15 @@ private string[] GetValueOutputs(TaskPropertyInfo parameter) object output = convertibleOutputs.GetValue(i); if (output != null) { - stringOutputs[i] = (string)Convert.ChangeType(output, typeof(string), CultureInfo.InvariantCulture); + // AbsolutePath needs special handling because Convert.ChangeType doesn't work with implicit operators + if (output is AbsolutePath absolutePath) + { + stringOutputs[i] = absolutePath.Value; + } + else + { + stringOutputs[i] = (string)Convert.ChangeType(output, typeof(string), CultureInfo.InvariantCulture); + } } } diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index f8da0901384..75472c145fb 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -17,7 +17,7 @@ internal static class TaskParameterTypeVerifier /// Is the parameter type a valid scalar input value /// internal static bool IsValidScalarInputParameter(Type parameterType) => - parameterType.IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem); + parameterType.IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem) || parameterType == typeof(AbsolutePath); /// /// Is the passed in parameterType a valid vector input parameter @@ -26,14 +26,15 @@ internal static bool IsValidVectorInputParameter(Type parameterType) { bool result = (parameterType.IsArray && parameterType.GetElementType().IsValueType) || parameterType == typeof(string[]) || - parameterType == typeof(ITaskItem[]); + parameterType == typeof(ITaskItem[]) || + parameterType == typeof(AbsolutePath[]); return result; } /// - /// Is the passed in value type assignable to an ITask or Itask[] object + /// Is the passed in value type assignable to an ITaskItem or ITaskItem[] object /// - internal static bool IsAssignableToITask(Type parameterType) + internal static bool IsAssignableToITaskItem(Type parameterType) { bool result = typeof(ITaskItem[]).IsAssignableFrom(parameterType) || /* ITaskItem array or derived type, or */ typeof(ITaskItem).IsAssignableFrom(parameterType); /* ITaskItem or derived type */ @@ -47,8 +48,10 @@ internal static bool IsValueTypeOutputParameter(Type parameterType) { bool result = (parameterType.IsArray && parameterType.GetElementType().IsValueType) || /* array of value types, or */ parameterType == typeof(string[]) || /* string array, or */ + parameterType == typeof(AbsolutePath[]) || /* AbsolutePath array, or */ parameterType.IsValueType || /* value type, or */ - parameterType == typeof(string); /* string */ + parameterType == typeof(string) || /* string, or */ + parameterType == typeof(AbsolutePath); /* AbsolutePath */ return result; } @@ -65,7 +68,7 @@ internal static bool IsValidInputParameter(Type parameterType) /// internal static bool IsValidOutputParameter(Type parameterType) { - return IsValueTypeOutputParameter(parameterType) || IsAssignableToITask(parameterType); + return IsValueTypeOutputParameter(parameterType) || IsAssignableToITaskItem(parameterType); } } } From 8a342ee0aad8a5e92933ba899d8a06e58f90cb6c Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Tue, 13 Jan 2026 16:57:31 -0600 Subject: [PATCH 02/27] Allow users to bind to primitive types while still having access to metadata --- documentation/wiki/Tasks.md | 12 +- .../BackEnd/TaskBuilderTestTask.cs | 60 ++++++ .../BackEnd/TaskExecutionHost_Tests.cs | 138 +++++++++++++ .../TaskExecutionHost/TaskExecutionHost.cs | 137 ++++++++++--- src/Build/Microsoft.Build.csproj | 1 + src/Framework/ITaskItem_T.cs | 25 +++ .../Microsoft.Build.Framework.csproj | 3 + src/Shared/TaskParameterTypeVerifier.cs | 74 ++++++- src/Shared/ValueTypeParser.cs | 139 +++++++++++++ src/Tasks/Microsoft.Build.Tasks.csproj | 2 - src/Utilities/TaskItem_T.cs | 191 ++++++++++++++++++ 11 files changed, 742 insertions(+), 40 deletions(-) create mode 100644 src/Framework/ITaskItem_T.cs create mode 100644 src/Shared/ValueTypeParser.cs create mode 100644 src/Utilities/TaskItem_T.cs diff --git a/documentation/wiki/Tasks.md b/documentation/wiki/Tasks.md index a8fd0ea67d8..2d78b48d617 100644 --- a/documentation/wiki/Tasks.md +++ b/documentation/wiki/Tasks.md @@ -8,8 +8,16 @@ A task is a class implementing [`ITask`](https://github.com/dotnet/msbuild/blob/ - The notable method of this interface is `bool Execute()`. Code in it will get executed when the task is run. - A Task can have public properties that can be set by the user in the project file. - - These properties can be `string`, `bool`, `ITaskItem` (representation of a file system object), `string[]`, `bool[]`, `ITaskItem[]` - - the properties can have attributes `[Required]` which causes the engine to check that it has a value when the task is run and `[Output]` which exposes the property to be used again in XML + - These properties can be: + - **String types**: `string`, `string[]` + - **Boolean types**: `bool`, `bool[]` + - **Numeric value types**: `int`, `long`, `short`, `byte`, `uint`, `ulong`, `ushort`, `sbyte`, `double`, `float`, `decimal`, and their array equivalents + - **Other value types**: `char`, `DateTime`, and their array equivalents + - **Item types**: `ITaskItem` (representation of a file system object with metadata), `ITaskItem[]` + - **Strongly-typed items**: `ITaskItem` where `T` is a value type (e.g., `ITaskItem`), and their array equivalents + - **Path types**: `AbsolutePath`, `AbsolutePath[]` + - **Custom value types**: Any struct implementing `IConvertible` (for output parameters only) + - The properties can have attributes `[Required]` which causes the engine to check that it has a value when the task is run and `[Output]` which exposes the property to be used again in XML - Tasks have the `Log` property set by the engine to log messages/errors/warnings. diff --git a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs index 1ffd91acd4e..7c2e5f56fcd 100644 --- a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs +++ b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs @@ -246,6 +246,16 @@ public CustomStruct(IConvertible value) /// private AbsolutePath[] _absolutePathArrayOutput; + /// + /// The value for the TaskItemIntOutput. + /// + private ITaskItem _taskItemIntOutput; + + /// + /// The value for the TaskItemIntArrayOutput. + /// + private ITaskItem[] _taskItemIntArrayOutput; + /// /// Property determining if Execute() should throw or not. /// @@ -663,6 +673,30 @@ public AbsolutePath[] AbsolutePathArrayParam } } + /// + /// A TaskItem<int> parameter. + /// + public ITaskItem TaskItemIntParam + { + set + { + _taskItemIntOutput = value; + _testTaskHost?.ParameterSet("TaskItemIntParam", value); + } + } + + /// + /// A TaskItem<int> array parameter. + /// + public ITaskItem[] TaskItemIntArrayParam + { + set + { + _taskItemIntArrayOutput = value; + _testTaskHost?.ParameterSet("TaskItemIntArrayParam", value); + } + } + /// /// The Execute return value parameter. /// @@ -1235,6 +1269,32 @@ public AbsolutePath[] AbsolutePathArrayOutput } } + /// + /// A TaskItem<int> output. + /// + [Output] + public ITaskItem TaskItemIntOutput + { + get + { + _testTaskHost?.OutputRead("TaskItemIntOutput", _taskItemIntOutput); + return _taskItemIntOutput; + } + } + + /// + /// A TaskItem<int> array output. + /// + [Output] + public ITaskItem[] TaskItemIntArrayOutput + { + get + { + _testTaskHost?.OutputRead("TaskItemIntArrayOutput", _taskItemIntArrayOutput); + return _taskItemIntArrayOutput; + } + } + [Output] public TargetBuiltReason EnumOutput => TargetBuiltReason.BeforeTargets; diff --git a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs index 03392859de3..a159b4021c3 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -20,6 +20,7 @@ using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Shared.Debugging; +using Microsoft.Build.Utilities; using Shouldly; using Xunit; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; @@ -564,6 +565,99 @@ public void TestSetAbsolutePathArrayParamEmptyItem() #endregion + #region TaskItem Params + + /// + /// Validate that setting a TaskItem<int> parameter with a valid integer works. + /// + [Fact] + public void TestSetTaskItemIntParam() + { + ValidateTaskParameter("TaskItemIntParam", "42", new Microsoft.Build.Utilities.TaskItem(42)); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemIntParamEmptyAttribute() + { + ValidateTaskParameterNotSet("TaskItemIntParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemIntParamEmptyProperty() + { + ValidateTaskParameterNotSet("TaskItemIntParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemIntParamEmptyItem() + { + ValidateTaskParameterNotSet("TaskItemIntParam", "@(NonExistentItem)"); + } + + #endregion + + #region TaskItem Array Params + + /// + /// Validate that setting a TaskItem<int> array with a single value sets the correct value. + /// + [Fact] + public void TestSetTaskItemIntArrayParam() + { + ValidateTaskParameterArray("TaskItemIntArrayParam", "42", new Microsoft.Build.Utilities.TaskItem[] { new Microsoft.Build.Utilities.TaskItem(42) }); + } + + /// + /// Validate that setting a TaskItem<int> array with multiple values sets the correct values. + /// + [Fact] + public void TestSetTaskItemIntArrayParamMultiple() + { + ValidateTaskParameterArray("TaskItemIntArrayParam", "10;20;30", new Microsoft.Build.Utilities.TaskItem[] { + new Microsoft.Build.Utilities.TaskItem(10), + new Microsoft.Build.Utilities.TaskItem(20), + new Microsoft.Build.Utilities.TaskItem(30) + }); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemIntArrayParamEmptyAttribute() + { + ValidateTaskParameterNotSet("TaskItemIntArrayParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemIntArrayParamEmptyProperty() + { + ValidateTaskParameterNotSet("TaskItemIntArrayParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemIntArrayParamEmptyItem() + { + ValidateTaskParameterNotSet("TaskItemIntArrayParam", "@(NonExistentItem)"); + } + + #endregion + #region ITaskItem Params /// @@ -981,6 +1075,50 @@ public void TestOutputItemArrayToProperty() #endregion + #region TaskItem Outputs + + /// + /// Validate that a TaskItem<int> output to an item produces the correct evaluated include. + /// + [Fact] + public void TestOutputTaskItemIntToItem() + { + SetTaskParameter("TaskItemIntParam", "42"); + ValidateOutputItem("TaskItemIntOutput", "42"); + } + + /// + /// Validate that a TaskItem<int> output to a property produces the correct evaluated value. + /// + [Fact] + public void TestOutputTaskItemIntToProperty() + { + SetTaskParameter("TaskItemIntParam", "42"); + ValidateOutputProperty("TaskItemIntOutput", "42"); + } + + /// + /// Validate that a TaskItem<int> array output to items produces the correct evaluated includes. + /// + [Fact] + public void TestOutputTaskItemIntArrayToItems() + { + SetTaskParameter("TaskItemIntArrayParam", "42;99"); + ValidateOutputItems("TaskItemIntArrayOutput", new string[] { "42", "99" }); + } + + /// + /// Validate that a TaskItem<int> array output to a property produces the correct semi-colon-delimited evaluated value. + /// + [Fact] + public void TestOutputTaskItemIntArrayToProperty() + { + SetTaskParameter("TaskItemIntArrayParam", "42;99"); + ValidateOutputProperty("TaskItemIntArrayOutput", "42;99"); + } + + #endregion + #region Other Output Tests /// diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index 907282c969c..e339dfc9cec 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -15,16 +15,17 @@ using System.Threading; using Microsoft.Build.BackEnd.Logging; +using Microsoft.Build.Collections; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; +using Microsoft.Build.Utilities; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using Task = System.Threading.Tasks.Task; -using Microsoft.Build.Collections; #nullable disable @@ -753,6 +754,43 @@ private void Cancel() } #region Local Methods + + /// + /// Checks if a type is TaskItem<T> where T is a value type. + /// + private static bool IsTaskItemOfT(Type parameterType) + { + if (!parameterType.GetTypeInfo().IsGenericType) + { + return false; + } + + Type genericTypeDefinition = parameterType.GetGenericTypeDefinition(); + if (genericTypeDefinition != typeof(ITaskItem<>) && genericTypeDefinition != typeof(TaskItem<>)) + { + return false; + } + + Type[] genericArguments = parameterType.GetGenericArguments(); + return genericArguments.Length == 1 && genericArguments[0].GetTypeInfo().IsValueType; + } + + /// + /// Creates an instance of TaskItem<T> from an ITaskItem. + /// + private static object CreateTaskItemOfT(Type taskItemType, ITaskItem item) + { + // Get the T from TaskItem + Type[] genericArguments = taskItemType.GetGenericArguments(); + Type valueType = genericArguments[0]; + + // Create TaskItem using the constructor that takes ITaskItem + Type constructedType = typeof(TaskItem<>).MakeGenericType(valueType); + ConstructorInfo constructor = constructedType.GetConstructor(new[] { typeof(ITaskItem) }); + + return constructor.Invoke(new object[] { item }); + } + /// /// Called on the local side. /// @@ -766,23 +804,15 @@ private bool SetTaskItemParameter(TaskPropertyInfo parameter, ITaskItem item) /// private bool SetValueParameter(TaskPropertyInfo parameter, Type parameterType, string expandedParameterValue) { - if (parameterType == typeof(bool)) - { - // Convert the string to the appropriate datatype, and set the task's parameter. - return InternalSetTaskParameter(parameter, ConversionUtilities.ConvertStringToBool(expandedParameterValue)); - } - else if (parameterType == typeof(string)) - { - return InternalSetTaskParameter(parameter, expandedParameterValue); - } - else if (parameterType == typeof(AbsolutePath)) + // Special handling for AbsolutePath to use TaskEnvironment for proper path resolution + if (parameterType == typeof(AbsolutePath)) { return InternalSetTaskParameter(parameter, TaskEnvironment.GetAbsolutePath(expandedParameterValue)); } - else - { - return InternalSetTaskParameter(parameter, Convert.ChangeType(expandedParameterValue, parameterType, CultureInfo.InvariantCulture)); - } + + // Use the unified ValueTypeParser for all other types + object parsedValue = ValueTypeParser.Parse(expandedParameterValue, parameterType); + return InternalSetTaskParameter(parameter, parsedValue); } /// @@ -797,7 +827,9 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I // Loop through all the TaskItems in our arraylist, and convert them. ArrayList finalTaskInputs = new ArrayList(taskItems.Count); - if (parameterType != typeof(ITaskItem[])) + Type elementType = parameterType.GetElementType(); + + if (parameterType != typeof(ITaskItem[]) && !IsTaskItemOfT(elementType)) { foreach (TaskItem item in taskItems) { @@ -816,12 +848,24 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I } else { - finalTaskInputs.Add(Convert.ChangeType(item.ItemSpec, parameterType.GetElementType(), CultureInfo.InvariantCulture)); + finalTaskInputs.Add(Convert.ChangeType(item.ItemSpec, elementType, CultureInfo.InvariantCulture)); } } } + else if (IsTaskItemOfT(elementType)) + { + // Handle TaskItem[] + foreach (TaskItem item in taskItems) + { + currentItem = item; + RecordItemForDisconnectIfNecessary(item); + object taskItemOfT = CreateTaskItemOfT(elementType, item); + finalTaskInputs.Add(taskItemOfT); + } + } else { + // Handle ITaskItem[] foreach (TaskItem item in taskItems) { // if we've been asked to remote these items then @@ -874,7 +918,38 @@ private ITaskItem[] GetItemOutputs(TaskPropertyInfo parameter) if (!(outputs is ITaskItem[] taskItemOutputs)) { - taskItemOutputs = [(ITaskItem)outputs]; + if (outputs == null) + { + taskItemOutputs = null; + } + else + { + // Check if it's a TaskItem or TaskItem[] + Type outputType = outputs.GetType(); + if (outputType.IsArray) + { + Type elementType = outputType.GetElementType(); + if (IsTaskItemOfT(elementType)) + { + // Convert TaskItem[] to ITaskItem[] + Array taskItemArray = (Array)outputs; + taskItemOutputs = new ITaskItem[taskItemArray.Length]; + for (int i = 0; i < taskItemArray.Length; i++) + { + taskItemOutputs[i] = (ITaskItem)taskItemArray.GetValue(i); + } + } + else + { + taskItemOutputs = [(ITaskItem)outputs]; + } + } + else + { + // Scalar value (including TaskItem) + taskItemOutputs = [(ITaskItem)outputs]; + } + } } return taskItemOutputs; @@ -900,15 +975,8 @@ private string[] GetValueOutputs(TaskPropertyInfo parameter) object output = convertibleOutputs.GetValue(i); if (output != null) { - // AbsolutePath needs special handling because Convert.ChangeType doesn't work with implicit operators - if (output is AbsolutePath absolutePath) - { - stringOutputs[i] = absolutePath.Value; - } - else - { - stringOutputs[i] = (string)Convert.ChangeType(output, typeof(string), CultureInfo.InvariantCulture); - } + // Use the unified ValueTypeParser for consistent formatting + stringOutputs[i] = ValueTypeParser.ToString(output); } } @@ -1255,7 +1323,7 @@ private bool InitializeTaskScalarParameter( try { - if (parameterType == typeof(ITaskItem)) + if (parameterType == typeof(ITaskItem) || IsTaskItemOfT(parameterType)) { // We don't know how many items we're going to end up with, but we'll // keep adding them to this arraylist as we find them. @@ -1269,7 +1337,7 @@ private bool InitializeTaskScalarParameter( { if (finalTaskItems.Count != 1) { - // We only allow a single item to be passed into a parameter of ITaskItem. + // We only allow a single item to be passed into a parameter of ITaskItem or TaskItem. // Some of the computation (expansion) here is expensive, so don't switch to VerifyThrowInvalidProject. ProjectErrorUtilities.ThrowInvalidProject( @@ -1283,7 +1351,16 @@ private bool InitializeTaskScalarParameter( RecordItemForDisconnectIfNecessary(finalTaskItems[0]); - success = SetTaskItemParameter(parameter, finalTaskItems[0]); + if (IsTaskItemOfT(parameterType)) + { + // Create TaskItem from ITaskItem + object taskItemOfT = CreateTaskItemOfT(parameterType, finalTaskItems[0]); + success = InternalSetTaskParameter(parameter, taskItemOfT); + } + else + { + success = SetTaskItemParameter(parameter, finalTaskItems[0]); + } taskParameterSet = true; } diff --git a/src/Build/Microsoft.Build.csproj b/src/Build/Microsoft.Build.csproj index eaa7400b4bd..4d4e9b54214 100644 --- a/src/Build/Microsoft.Build.csproj +++ b/src/Build/Microsoft.Build.csproj @@ -29,6 +29,7 @@ + diff --git a/src/Framework/ITaskItem_T.cs b/src/Framework/ITaskItem_T.cs new file mode 100644 index 00000000000..4d36e7b1765 --- /dev/null +++ b/src/Framework/ITaskItem_T.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable enable + +namespace Microsoft.Build.Framework +{ + /// + /// A strongly-typed task item interface that wraps a value of type + /// and provides access to it along with standard task item functionality. + /// + /// The type of the value. Must be a value type. + /// + /// This interface allows tasks to receive strongly-typed parameters while still working with MSBuild's item system. + /// The value is parsed from the item's identity (ItemSpec) using MSBuild's standard parsing conventions. + /// + public interface ITaskItem : ITaskItem2 + where T : struct + { + /// + /// Gets the strongly-typed value parsed from the item's identity. + /// + T Value { get; } + } +} diff --git a/src/Framework/Microsoft.Build.Framework.csproj b/src/Framework/Microsoft.Build.Framework.csproj index dcb2abebb5b..bd63e72efce 100644 --- a/src/Framework/Microsoft.Build.Framework.csproj +++ b/src/Framework/Microsoft.Build.Framework.csproj @@ -65,6 +65,9 @@ + + Shared\ValueTypeParser.cs + diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index 75472c145fb..499fc022bf3 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -13,21 +13,61 @@ namespace Microsoft.Build.BackEnd /// internal static class TaskParameterTypeVerifier { +#if !TASKHOST + /// + /// Checks if a type is ITaskItem<T> where T is a value type. + /// + private static bool IsTaskItemOfT(Type parameterType) + { + if (!parameterType.IsGenericType) + { + return false; + } + + Type genericTypeDefinition = parameterType.GetGenericTypeDefinition(); + if (genericTypeDefinition != typeof(ITaskItem<>)) + { + return false; + } + + Type[] genericArguments = parameterType.GetGenericArguments(); + return genericArguments.Length == 1 && genericArguments[0].IsValueType; + } +#endif + /// /// Is the parameter type a valid scalar input value /// internal static bool IsValidScalarInputParameter(Type parameterType) => - parameterType.IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem) || parameterType == typeof(AbsolutePath); + parameterType.IsValueType || + parameterType == typeof(string) || + parameterType == typeof(ITaskItem) +#if !TASKHOST + || parameterType == typeof(AbsolutePath) + || IsTaskItemOfT(parameterType) +#endif + ; /// /// Is the passed in parameterType a valid vector input parameter /// internal static bool IsValidVectorInputParameter(Type parameterType) { - bool result = (parameterType.IsArray && parameterType.GetElementType().IsValueType) || + if (!parameterType.IsArray) + { + return false; + } + + Type elementType = parameterType.GetElementType(); + + bool result = elementType.IsValueType || parameterType == typeof(string[]) || - parameterType == typeof(ITaskItem[]) || - parameterType == typeof(AbsolutePath[]); + parameterType == typeof(ITaskItem[]) +#if !TASKHOST + || parameterType == typeof(AbsolutePath[]) + || IsTaskItemOfT(elementType) +#endif + ; return result; } @@ -36,8 +76,25 @@ internal static bool IsValidVectorInputParameter(Type parameterType) /// internal static bool IsAssignableToITaskItem(Type parameterType) { + // Check if it's directly assignable bool result = typeof(ITaskItem[]).IsAssignableFrom(parameterType) || /* ITaskItem array or derived type, or */ typeof(ITaskItem).IsAssignableFrom(parameterType); /* ITaskItem or derived type */ + +#if !TASKHOST + // Also check for TaskItem or TaskItem[] + if (!result) + { + if (parameterType.IsArray) + { + result = IsTaskItemOfT(parameterType.GetElementType()); + } + else + { + result = IsTaskItemOfT(parameterType); + } + } +#endif + return result; } @@ -48,10 +105,15 @@ internal static bool IsValueTypeOutputParameter(Type parameterType) { bool result = (parameterType.IsArray && parameterType.GetElementType().IsValueType) || /* array of value types, or */ parameterType == typeof(string[]) || /* string array, or */ +#if !TASKHOST parameterType == typeof(AbsolutePath[]) || /* AbsolutePath array, or */ +#endif parameterType.IsValueType || /* value type, or */ - parameterType == typeof(string) || /* string, or */ - parameterType == typeof(AbsolutePath); /* AbsolutePath */ + parameterType == typeof(string) /* string, or */ +#if !TASKHOST + || parameterType == typeof(AbsolutePath) /* AbsolutePath */ +#endif + ; return result; } diff --git a/src/Shared/ValueTypeParser.cs b/src/Shared/ValueTypeParser.cs new file mode 100644 index 00000000000..5401e5a3601 --- /dev/null +++ b/src/Shared/ValueTypeParser.cs @@ -0,0 +1,139 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Globalization; +using Microsoft.Build.Framework; + +#nullable enable + +namespace Microsoft.Build.Shared +{ + /// + /// Provides unified parsing and formatting logic for value types used in MSBuild task parameters. + /// This ensures consistent behavior between TaskItem<T> parsing and TaskExecutionHost parameter binding. + /// + internal static class ValueTypeParser + { + /// + /// Parses a boolean value using MSBuild's boolean conventions. + /// Supports: true/on/yes/!false/!off/!no for true, false/off/no/!true/!on/!yes for false. + /// + private static bool ParseBool(string value) + { + // MSBuild boolean true values + if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "on", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "yes", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "!false", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "!off", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "!no", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + // MSBuild boolean false values + if (string.Equals(value, "false", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "off", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "no", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "!true", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "!on", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "!yes", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + throw new ArgumentException($"Cannot parse '{value}' as a boolean value."); + } + + /// + /// Parses a string value as the specified type. + /// + /// The string value to parse. + /// The type to parse the value as. + /// The parsed value as an object. + /// Thrown if the value cannot be parsed as the target type. + public static object Parse(string value, Type targetType) + { + try + { + // Special handling for AbsolutePath + if (targetType == typeof(AbsolutePath)) + { + return new AbsolutePath(value); + } + + // Special handling for bool - MSBuild supports various boolean representations + if (targetType == typeof(bool)) + { + return ParseBool(value); + } + + // Special handling for string (no parsing needed) + if (targetType == typeof(string)) + { + return value; + } + + // Use TypeCode-based parsing for built-in types + TypeCode typeCode = Type.GetTypeCode(targetType); + switch (typeCode) + { + case TypeCode.Int32: + return int.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.Int64: + return long.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.Double: + return double.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.Single: + return float.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.Decimal: + return decimal.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.Byte: + return byte.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.SByte: + return sbyte.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.Int16: + return short.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.UInt16: + return ushort.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.UInt32: + return uint.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.UInt64: + return ulong.Parse(value, CultureInfo.InvariantCulture); + case TypeCode.Char: + return char.Parse(value); + default: + // Fallback to Convert.ChangeType for other types + return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture); + } + } + catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException || ex is ArgumentException || ex is NotSupportedException) + { + throw new ArgumentException($"Cannot parse '{value}' as type {targetType.Name}.", nameof(value), ex); + } + } + + /// + /// Converts a value to its string representation for use in MSBuild. + /// + /// The value to convert. + /// The string representation of the value. + public static string ToString(object? value) + { + if (value == null) + { + return string.Empty; + } + + // AbsolutePath needs special handling because Convert.ChangeType doesn't work with implicit operators + if (value is AbsolutePath absolutePath) + { + return absolutePath.Value; + } + + // Use InvariantCulture for consistent formatting + return Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; + } + } +} diff --git a/src/Tasks/Microsoft.Build.Tasks.csproj b/src/Tasks/Microsoft.Build.Tasks.csproj index 8f9f6047689..efb9ec991d7 100644 --- a/src/Tasks/Microsoft.Build.Tasks.csproj +++ b/src/Tasks/Microsoft.Build.Tasks.csproj @@ -48,8 +48,6 @@ - - AssemblyDependency\AssemblyFoldersEx.cs diff --git a/src/Utilities/TaskItem_T.cs b/src/Utilities/TaskItem_T.cs new file mode 100644 index 00000000000..649f61972df --- /dev/null +++ b/src/Utilities/TaskItem_T.cs @@ -0,0 +1,191 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections; +using Microsoft.Build.Framework; +using Microsoft.Build.Shared; + +namespace Microsoft.Build.Utilities +{ + /// + /// A strongly-typed wrapper around that parses the item's identity + /// as a value of type . + /// + /// The type to parse the item identity as. Must be a value type. + /// + /// This allows tasks to receive strongly-typed parameters while still working with MSBuild's item system. + /// The identity (ItemSpec) is parsed using or special handling for + /// types like . + /// + public readonly struct TaskItem : ITaskItem, IEquatable> + where T : struct + { + private readonly ITaskItem _backingItem; + + /// + /// Gets the strongly-typed value parsed from the item's identity. + /// + public T Value { get; } + + /// + /// Initializes a new instance of from a strongly-typed value. + /// + /// The value to wrap. + public TaskItem(T value) + { + Value = value; + + // Create a backing item with the stringified value as ItemSpec + string itemSpec = ValueTypeParser.ToString(value); + _backingItem = new TaskItemData(itemSpec, null); + } + + /// + /// Initializes a new instance of from an . + /// + /// The task item to parse. + /// Thrown if is null. + /// Thrown if the item's identity cannot be parsed as type . + public TaskItem(ITaskItem item) + { + if (item == null) + { + throw new ArgumentNullException(nameof(item)); + } + + _backingItem = item; + + string itemSpec = item.ItemSpec; + if (string.IsNullOrEmpty(itemSpec)) + { + throw new ArgumentException($"Cannot create TaskItem<{typeof(T).Name}> from an item with empty identity.", nameof(item)); + } + + // Parse the value from ItemSpec + Value = ParseValue(itemSpec); + } + + /// + /// Parses a string value as type . + /// Uses the unified ValueTypeParser for consistent parsing behavior across MSBuild. + /// + private static T ParseValue(string value) => (T)ValueTypeParser.Parse(value, typeof(T)); + + /// + /// Converts the strongly-typed value to its string representation for use as ItemSpec. + /// Uses the unified ValueTypeParser for consistent formatting behavior across MSBuild. + /// + private string ValueToString() => ValueTypeParser.ToString(Value); + + #region ITaskItem Implementation + + /// + public string ItemSpec + { + get => _backingItem.ItemSpec; + set => throw new NotSupportedException("TaskItem ItemSpec is read-only. Create a new instance to change the value."); + } + + /// + public ICollection MetadataNames => _backingItem.MetadataNames; + + /// + public int MetadataCount => _backingItem.MetadataCount; + + /// + public string GetMetadata(string metadataName) => _backingItem.GetMetadata(metadataName); + + /// + public void SetMetadata(string metadataName, string metadataValue) => + _backingItem.SetMetadata(metadataName, metadataValue); + + /// + public void RemoveMetadata(string metadataName) => + _backingItem.RemoveMetadata(metadataName); + + /// + public void CopyMetadataTo(ITaskItem destinationItem) => + _backingItem.CopyMetadataTo(destinationItem); + + /// + public IDictionary CloneCustomMetadata() => _backingItem.CloneCustomMetadata(); + + #endregion + + #region ITaskItem2 Implementation + + /// + public string EvaluatedIncludeEscaped + { + get => (_backingItem as ITaskItem2)?.EvaluatedIncludeEscaped ?? ItemSpec; + set => throw new NotSupportedException("TaskItem EvaluatedIncludeEscaped is read-only. Create a new instance to change the value."); + } + + /// + public string GetMetadataValueEscaped(string metadataName) + { + return (_backingItem as ITaskItem2)?.GetMetadataValueEscaped(metadataName) ?? string.Empty; + } + + /// + public void SetMetadataValueLiteral(string metadataName, string metadataValue) + { + if (_backingItem is ITaskItem2 taskItem2) + { + taskItem2.SetMetadataValueLiteral(metadataName, metadataValue); + } + else + { + // For ITaskItem (non-ITaskItem2), we need to escape the value manually + // Since we don't have access to EscapingUtilities in Framework, we'll just set it directly + // This is acceptable because TaskItem is primarily used with ITaskItem2 implementations + _backingItem.SetMetadata(metadataName, metadataValue); + } + } + + /// + public IDictionary CloneCustomMetadataEscaped() + { + return (_backingItem as ITaskItem2)?.CloneCustomMetadataEscaped() ?? new Hashtable(); + } + + #endregion + + #region Equality and Conversion + + /// + public bool Equals(TaskItem other) => Value.Equals(other.Value); + + /// + public override bool Equals(object? obj) => obj is TaskItem other && Equals(other); + + /// + public override int GetHashCode() => Value.GetHashCode(); + + /// + /// Determines whether two instances are equal. + /// + public static bool operator ==(TaskItem left, TaskItem right) => left.Equals(right); + + /// + /// Determines whether two instances are not equal. + /// + public static bool operator !=(TaskItem left, TaskItem right) => !left.Equals(right); + + /// + /// Implicitly converts a to its strongly-typed value. + /// + public static implicit operator T(TaskItem taskItem) => taskItem.Value; + + /// + /// Implicitly converts a strongly-typed value to a . + /// + public static implicit operator TaskItem(T value) => new TaskItem(value); + + #endregion + + /// + public override string ToString() => ValueToString(); + } +} From bba8cd3b3bdecb4fe8f71693aad2cfe09101b943 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Tue, 13 Jan 2026 17:51:36 -0600 Subject: [PATCH 03/27] Support FileInfo/DirectoryInfo parameter binding as well --- documentation/wiki/Tasks.md | 4 +- .../BackEnd/TaskBuilderTestTask.cs | 240 ++++++++++ .../BackEnd/TaskExecutionHost_Tests.cs | 430 +++++++++++++++++- .../TaskExecutionHost/TaskExecutionHost.cs | 35 +- src/Framework/ITaskItem_T.cs | 4 +- src/Shared/TaskParameterTypeVerifier.cs | 19 +- src/Shared/ValueTypeParser.cs | 24 + src/Utilities/TaskItem_T.cs | 12 +- 8 files changed, 752 insertions(+), 16 deletions(-) diff --git a/documentation/wiki/Tasks.md b/documentation/wiki/Tasks.md index 2d78b48d617..66e5b15f556 100644 --- a/documentation/wiki/Tasks.md +++ b/documentation/wiki/Tasks.md @@ -14,8 +14,8 @@ A task is a class implementing [`ITask`](https://github.com/dotnet/msbuild/blob/ - **Numeric value types**: `int`, `long`, `short`, `byte`, `uint`, `ulong`, `ushort`, `sbyte`, `double`, `float`, `decimal`, and their array equivalents - **Other value types**: `char`, `DateTime`, and their array equivalents - **Item types**: `ITaskItem` (representation of a file system object with metadata), `ITaskItem[]` - - **Strongly-typed items**: `ITaskItem` where `T` is a value type (e.g., `ITaskItem`), and their array equivalents - - **Path types**: `AbsolutePath`, `AbsolutePath[]` + - **Strongly-typed items**: `ITaskItem` where `T` is a value type, `FileInfo`, or `DirectoryInfo` (e.g., `ITaskItem`, `ITaskItem`), and their array equivalents + - **Path types**: `AbsolutePath`, `AbsolutePath[]`, `FileInfo`, `FileInfo[]`, `DirectoryInfo`, `DirectoryInfo[]` - **Custom value types**: Any struct implementing `IConvertible` (for output parameters only) - The properties can have attributes `[Required]` which causes the engine to check that it has a value when the task is run and `[Output]` which exposes the property to be used again in XML diff --git a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs index 7c2e5f56fcd..0b855c9e9ff 100644 --- a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs +++ b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs @@ -256,6 +256,46 @@ public CustomStruct(IConvertible value) /// private ITaskItem[] _taskItemIntArrayOutput; + /// + /// The value for the FileInfoOutput. + /// + private System.IO.FileInfo _fileInfoOutput; + + /// + /// The value for the FileInfoArrayOutput. + /// + private System.IO.FileInfo[] _fileInfoArrayOutput; + + /// + /// The value for the DirectoryInfoOutput. + /// + private System.IO.DirectoryInfo _directoryInfoOutput; + + /// + /// The value for the DirectoryInfoArrayOutput. + /// + private System.IO.DirectoryInfo[] _directoryInfoArrayOutput; + + /// + /// The value for the TaskItemFileInfoOutput. + /// + private ITaskItem _taskItemFileInfoOutput; + + /// + /// The value for the TaskItemFileInfoArrayOutput. + /// + private ITaskItem[] _taskItemFileInfoArrayOutput; + + /// + /// The value for the TaskItemDirectoryInfoOutput. + /// + private ITaskItem _taskItemDirectoryInfoOutput; + + /// + /// The value for the TaskItemDirectoryInfoArrayOutput. + /// + private ITaskItem[] _taskItemDirectoryInfoArrayOutput; + /// /// Property determining if Execute() should throw or not. /// @@ -697,6 +737,102 @@ public ITaskItem[] TaskItemIntArrayParam } } + /// + /// A FileInfo parameter. + /// + public System.IO.FileInfo FileInfoParam + { + set + { + _fileInfoOutput = value; + _testTaskHost?.ParameterSet("FileInfoParam", value); + } + } + + /// + /// A FileInfo array parameter. + /// + public System.IO.FileInfo[] FileInfoArrayParam + { + set + { + _fileInfoArrayOutput = value; + _testTaskHost?.ParameterSet("FileInfoArrayParam", value); + } + } + + /// + /// A DirectoryInfo parameter. + /// + public System.IO.DirectoryInfo DirectoryInfoParam + { + set + { + _directoryInfoOutput = value; + _testTaskHost?.ParameterSet("DirectoryInfoParam", value); + } + } + + /// + /// A DirectoryInfo array parameter. + /// + public System.IO.DirectoryInfo[] DirectoryInfoArrayParam + { + set + { + _directoryInfoArrayOutput = value; + _testTaskHost?.ParameterSet("DirectoryInfoArrayParam", value); + } + } + + /// + /// An ITaskItem<FileInfo> parameter. + /// + public ITaskItem TaskItemFileInfoParam + { + set + { + _taskItemFileInfoOutput = value; + _testTaskHost?.ParameterSet("TaskItemFileInfoParam", value); + } + } + + /// + /// An ITaskItem<FileInfo> array parameter. + /// + public ITaskItem[] TaskItemFileInfoArrayParam + { + set + { + _taskItemFileInfoArrayOutput = value; + _testTaskHost?.ParameterSet("TaskItemFileInfoArrayParam", value); + } + } + + /// + /// An ITaskItem<DirectoryInfo> parameter. + /// + public ITaskItem TaskItemDirectoryInfoParam + { + set + { + _taskItemDirectoryInfoOutput = value; + _testTaskHost?.ParameterSet("TaskItemDirectoryInfoParam", value); + } + } + + /// + /// An ITaskItem<DirectoryInfo> array parameter. + /// + public ITaskItem[] TaskItemDirectoryInfoArrayParam + { + set + { + _taskItemDirectoryInfoArrayOutput = value; + _testTaskHost?.ParameterSet("TaskItemDirectoryInfoArrayParam", value); + } + } + /// /// The Execute return value parameter. /// @@ -1295,6 +1431,110 @@ public ITaskItem[] TaskItemIntArrayOutput } } + /// + /// A FileInfo output. + /// + [Output] + public System.IO.FileInfo FileInfoOutput + { + get + { + _testTaskHost?.OutputRead("FileInfoOutput", _fileInfoOutput); + return _fileInfoOutput; + } + } + + /// + /// A FileInfo array output. + /// + [Output] + public System.IO.FileInfo[] FileInfoArrayOutput + { + get + { + _testTaskHost?.OutputRead("FileInfoArrayOutput", _fileInfoArrayOutput); + return _fileInfoArrayOutput; + } + } + + /// + /// A DirectoryInfo output. + /// + [Output] + public System.IO.DirectoryInfo DirectoryInfoOutput + { + get + { + _testTaskHost?.OutputRead("DirectoryInfoOutput", _directoryInfoOutput); + return _directoryInfoOutput; + } + } + + /// + /// A DirectoryInfo array output. + /// + [Output] + public System.IO.DirectoryInfo[] DirectoryInfoArrayOutput + { + get + { + _testTaskHost?.OutputRead("DirectoryInfoArrayOutput", _directoryInfoArrayOutput); + return _directoryInfoArrayOutput; + } + } + + /// + /// An ITaskItem<FileInfo> output. + /// + [Output] + public ITaskItem TaskItemFileInfoOutput + { + get + { + _testTaskHost?.OutputRead("TaskItemFileInfoOutput", _taskItemFileInfoOutput); + return _taskItemFileInfoOutput; + } + } + + /// + /// An ITaskItem<FileInfo> array output. + /// + [Output] + public ITaskItem[] TaskItemFileInfoArrayOutput + { + get + { + _testTaskHost?.OutputRead("TaskItemFileInfoArrayOutput", _taskItemFileInfoArrayOutput); + return _taskItemFileInfoArrayOutput; + } + } + + /// + /// An ITaskItem<DirectoryInfo> output. + /// + [Output] + public ITaskItem TaskItemDirectoryInfoOutput + { + get + { + _testTaskHost?.OutputRead("TaskItemDirectoryInfoOutput", _taskItemDirectoryInfoOutput); + return _taskItemDirectoryInfoOutput; + } + } + + /// + /// An ITaskItem<DirectoryInfo> array output. + /// + [Output] + public ITaskItem[] TaskItemDirectoryInfoArrayOutput + { + get + { + _testTaskHost?.OutputRead("TaskItemDirectoryInfoArrayOutput", _taskItemDirectoryInfoArrayOutput); + return _taskItemDirectoryInfoArrayOutput; + } + } + [Output] public TargetBuiltReason EnumOutput => TargetBuiltReason.BeforeTargets; diff --git a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs index a159b4021c3..564a70a7723 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -658,6 +658,384 @@ public void TestSetTaskItemIntArrayParamEmptyItem() #endregion + #region FileInfo Params + + /// + /// Validate that setting a FileInfo parameter with a valid file path works. + /// + [Fact] + public void TestSetFileInfoParam() + { + string filePath = NativeMethodsShared.IsWindows ? @"C:\temp\file.txt" : "/tmp/file.txt"; + ValidateTaskParameter("FileInfoParam", filePath, new FileInfo(filePath)); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetFileInfoParamEmptyAttribute() + { + ValidateTaskParameterNotSet("FileInfoParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetFileInfoParamEmptyProperty() + { + ValidateTaskParameterNotSet("FileInfoParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetFileInfoParamEmptyItem() + { + ValidateTaskParameterNotSet("FileInfoParam", "@(NonExistentItem)"); + } + + #endregion + + #region FileInfo Array Params + + /// + /// Validate that setting a FileInfo array with a single value sets the correct value. + /// + [Fact] + public void TestSetFileInfoArrayParam() + { + string filePath = NativeMethodsShared.IsWindows ? @"C:\temp\file.txt" : "/tmp/file.txt"; + ValidateTaskParameterArray("FileInfoArrayParam", filePath, new FileInfo[] { new FileInfo(filePath) }); + } + + /// + /// Validate that setting a FileInfo array with multiple values sets the correct values. + /// + [Fact] + public void TestSetFileInfoArrayParamMultiple() + { + string path1 = NativeMethodsShared.IsWindows ? @"C:\temp\file1.txt" : "/tmp/file1.txt"; + string path2 = NativeMethodsShared.IsWindows ? @"C:\temp\file2.txt" : "/tmp/file2.txt"; + ValidateTaskParameterArray("FileInfoArrayParam", path1 + ";" + path2, new FileInfo[] { new FileInfo(path1), new FileInfo(path2) }); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetFileInfoArrayParamEmptyAttribute() + { + ValidateTaskParameterNotSet("FileInfoArrayParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetFileInfoArrayParamEmptyProperty() + { + ValidateTaskParameterNotSet("FileInfoArrayParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetFileInfoArrayParamEmptyItem() + { + ValidateTaskParameterNotSet("FileInfoArrayParam", "@(NonExistentItem)"); + } + + #endregion + + #region DirectoryInfo Params + + /// + /// Validate that setting a DirectoryInfo parameter with a valid directory path works. + /// + [Fact] + public void TestSetDirectoryInfoParam() + { + string dirPath = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; + ValidateTaskParameter("DirectoryInfoParam", dirPath, new DirectoryInfo(dirPath)); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetDirectoryInfoParamEmptyAttribute() + { + ValidateTaskParameterNotSet("DirectoryInfoParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetDirectoryInfoParamEmptyProperty() + { + ValidateTaskParameterNotSet("DirectoryInfoParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetDirectoryInfoParamEmptyItem() + { + ValidateTaskParameterNotSet("DirectoryInfoParam", "@(NonExistentItem)"); + } + + #endregion + + #region DirectoryInfo Array Params + + /// + /// Validate that setting a DirectoryInfo array with a single value sets the correct value. + /// + [Fact] + public void TestSetDirectoryInfoArrayParam() + { + string dirPath = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; + ValidateTaskParameterArray("DirectoryInfoArrayParam", dirPath, new DirectoryInfo[] { new DirectoryInfo(dirPath) }); + } + + /// + /// Validate that setting a DirectoryInfo array with multiple values sets the correct values. + /// + [Fact] + public void TestSetDirectoryInfoArrayParamMultiple() + { + string path1 = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; + string path2 = NativeMethodsShared.IsWindows ? @"C:\Windows" : "/usr"; + ValidateTaskParameterArray("DirectoryInfoArrayParam", path1 + ";" + path2, new DirectoryInfo[] { new DirectoryInfo(path1), new DirectoryInfo(path2) }); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetDirectoryInfoArrayParamEmptyAttribute() + { + ValidateTaskParameterNotSet("DirectoryInfoArrayParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetDirectoryInfoArrayParamEmptyProperty() + { + ValidateTaskParameterNotSet("DirectoryInfoArrayParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetDirectoryInfoArrayParamEmptyItem() + { + ValidateTaskParameterNotSet("DirectoryInfoArrayParam", "@(NonExistentItem)"); + } + + #endregion + + #region TaskItem Params + + /// + /// Validate that setting a TaskItem<FileInfo> parameter with a valid file path works. + /// + [Fact] + public void TestSetTaskItemFileInfoParam() + { + string filePath = NativeMethodsShared.IsWindows ? @"C:\temp\file.txt" : "/tmp/file.txt"; + ValidateTaskParameter("TaskItemFileInfoParam", filePath, new Microsoft.Build.Utilities.TaskItem(new FileInfo(filePath))); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemFileInfoParamEmptyAttribute() + { + ValidateTaskParameterNotSet("TaskItemFileInfoParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemFileInfoParamEmptyProperty() + { + ValidateTaskParameterNotSet("TaskItemFileInfoParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemFileInfoParamEmptyItem() + { + ValidateTaskParameterNotSet("TaskItemFileInfoParam", "@(NonExistentItem)"); + } + + #endregion + + #region TaskItem Array Params + + /// + /// Validate that setting a TaskItem<FileInfo> array with a single value sets the correct value. + /// + [Fact] + public void TestSetTaskItemFileInfoArrayParam() + { + string filePath = NativeMethodsShared.IsWindows ? @"C:\temp\file.txt" : "/tmp/file.txt"; + ValidateTaskParameterArray("TaskItemFileInfoArrayParam", filePath, new Microsoft.Build.Utilities.TaskItem[] { new Microsoft.Build.Utilities.TaskItem(new FileInfo(filePath)) }); + } + + /// + /// Validate that setting a TaskItem<FileInfo> array with multiple values sets the correct values. + /// + [Fact] + public void TestSetTaskItemFileInfoArrayParamMultiple() + { + string path1 = NativeMethodsShared.IsWindows ? @"C:\temp\file1.txt" : "/tmp/file1.txt"; + string path2 = NativeMethodsShared.IsWindows ? @"C:\temp\file2.txt" : "/tmp/file2.txt"; + ValidateTaskParameterArray("TaskItemFileInfoArrayParam", path1 + ";" + path2, new Microsoft.Build.Utilities.TaskItem[] { + new Microsoft.Build.Utilities.TaskItem(new FileInfo(path1)), + new Microsoft.Build.Utilities.TaskItem(new FileInfo(path2)) + }); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemFileInfoArrayParamEmptyAttribute() + { + ValidateTaskParameterNotSet("TaskItemFileInfoArrayParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemFileInfoArrayParamEmptyProperty() + { + ValidateTaskParameterNotSet("TaskItemFileInfoArrayParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemFileInfoArrayParamEmptyItem() + { + ValidateTaskParameterNotSet("TaskItemFileInfoArrayParam", "@(NonExistentItem)"); + } + + #endregion + + #region TaskItem Params + + /// + /// Validate that setting a TaskItem<DirectoryInfo> parameter with a valid directory path works. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoParam() + { + string dirPath = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; + ValidateTaskParameter("TaskItemDirectoryInfoParam", dirPath, new Microsoft.Build.Utilities.TaskItem(new DirectoryInfo(dirPath))); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoParamEmptyAttribute() + { + ValidateTaskParameterNotSet("TaskItemDirectoryInfoParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoParamEmptyProperty() + { + ValidateTaskParameterNotSet("TaskItemDirectoryInfoParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoParamEmptyItem() + { + ValidateTaskParameterNotSet("TaskItemDirectoryInfoParam", "@(NonExistentItem)"); + } + + #endregion + + #region TaskItem Array Params + + /// + /// Validate that setting a TaskItem<DirectoryInfo> array with a single value sets the correct value. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoArrayParam() + { + string dirPath = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; + ValidateTaskParameterArray("TaskItemDirectoryInfoArrayParam", dirPath, new Microsoft.Build.Utilities.TaskItem[] { new Microsoft.Build.Utilities.TaskItem(new DirectoryInfo(dirPath)) }); + } + + /// + /// Validate that setting a TaskItem<DirectoryInfo> array with multiple values sets the correct values. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoArrayParamMultiple() + { + string path1 = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; + string path2 = NativeMethodsShared.IsWindows ? @"C:\Windows" : "/usr"; + ValidateTaskParameterArray("TaskItemDirectoryInfoArrayParam", path1 + ";" + path2, new Microsoft.Build.Utilities.TaskItem[] { + new Microsoft.Build.Utilities.TaskItem(new DirectoryInfo(path1)), + new Microsoft.Build.Utilities.TaskItem(new DirectoryInfo(path2)) + }); + } + + /// + /// Validate that setting the parameter with an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoArrayParamEmptyAttribute() + { + ValidateTaskParameterNotSet("TaskItemDirectoryInfoArrayParam", ""); + } + + /// + /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoArrayParamEmptyProperty() + { + ValidateTaskParameterNotSet("TaskItemDirectoryInfoArrayParam", "$(NonExistentProperty)"); + } + + /// + /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. + /// + [Fact] + public void TestSetTaskItemDirectoryInfoArrayParamEmptyItem() + { + ValidateTaskParameterNotSet("TaskItemDirectoryInfoArrayParam", "@(NonExistentItem)"); + } + + #endregion + #region ITaskItem Params /// @@ -1592,7 +1970,31 @@ private void ValidateTaskParameter(string parameterName, string value, object ex SetTaskParameter(parameterName, value); Assert.True(_parametersSetOnTask.ContainsKey(parameterName)); - Assert.Equal(expectedValue, _parametersSetOnTask[parameterName]); + + object actualValue = _parametersSetOnTask[parameterName]; + + // Special handling for FileInfo and DirectoryInfo - compare FullName instead of object equality + if (expectedValue is FileInfo expectedFileInfo && actualValue is FileInfo actualFileInfo) + { + Assert.Equal(expectedFileInfo.FullName, actualFileInfo.FullName); + } + else if (expectedValue is DirectoryInfo expectedDirInfo && actualValue is DirectoryInfo actualDirInfo) + { + Assert.Equal(expectedDirInfo.FullName, actualDirInfo.FullName); + } + // Special handling for TaskItem and TaskItem - compare FullName through ItemSpec + else if (expectedValue is ITaskItem expectedTaskItemFileInfo && actualValue is ITaskItem actualTaskItemFileInfo) + { + Assert.Equal(expectedTaskItemFileInfo.Value.FullName, actualTaskItemFileInfo.Value.FullName); + } + else if (expectedValue is ITaskItem expectedTaskItemDirInfo && actualValue is ITaskItem actualTaskItemDirInfo) + { + Assert.Equal(expectedTaskItemDirInfo.Value.FullName, actualTaskItemDirInfo.Value.FullName); + } + else + { + Assert.Equal(expectedValue, actualValue); + } } /// @@ -1687,7 +2089,31 @@ private void ValidateTaskParameterArray(string parameterName, string value, obje Assert.Equal(expectedArray.Length, actualArray.Length); for (int i = 0; i < expectedArray.Length; i++) { - Assert.Equal(expectedArray.GetValue(i), actualArray.GetValue(i)); + object expected = expectedArray.GetValue(i); + object actual = actualArray.GetValue(i); + + // Special handling for FileInfo and DirectoryInfo - compare FullName instead of object equality + if (expected is FileInfo expectedFileInfo && actual is FileInfo actualFileInfo) + { + Assert.Equal(expectedFileInfo.FullName, actualFileInfo.FullName); + } + else if (expected is DirectoryInfo expectedDirInfo && actual is DirectoryInfo actualDirInfo) + { + Assert.Equal(expectedDirInfo.FullName, actualDirInfo.FullName); + } + // Special handling for TaskItem and TaskItem - compare FullName through ItemSpec + else if (expected is ITaskItem expectedTaskItemFileInfo && actual is ITaskItem actualTaskItemFileInfo) + { + Assert.Equal(expectedTaskItemFileInfo.Value.FullName, actualTaskItemFileInfo.Value.FullName); + } + else if (expected is ITaskItem expectedTaskItemDirInfo && actual is ITaskItem actualTaskItemDirInfo) + { + Assert.Equal(expectedTaskItemDirInfo.Value.FullName, actualTaskItemDirInfo.Value.FullName); + } + else + { + Assert.Equal(expected, actual); + } } } diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index e339dfc9cec..030559b1f91 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Globalization; +using System.IO; using System.Linq; using System.Reflection; #if FEATURE_APPDOMAIN @@ -756,7 +757,7 @@ private void Cancel() #region Local Methods /// - /// Checks if a type is TaskItem<T> where T is a value type. + /// Checks if a type is TaskItem<T> where T is a value type, FileInfo, or DirectoryInfo. /// private static bool IsTaskItemOfT(Type parameterType) { @@ -772,7 +773,13 @@ private static bool IsTaskItemOfT(Type parameterType) } Type[] genericArguments = parameterType.GetGenericArguments(); - return genericArguments.Length == 1 && genericArguments[0].GetTypeInfo().IsValueType; + if (genericArguments.Length != 1) + { + return false; + } + + Type typeArg = genericArguments[0]; + return typeArg.GetTypeInfo().IsValueType || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); } /// @@ -810,6 +817,20 @@ private bool SetValueParameter(TaskPropertyInfo parameter, Type parameterType, s return InternalSetTaskParameter(parameter, TaskEnvironment.GetAbsolutePath(expandedParameterValue)); } + // Special handling for FileInfo - validate path through AbsolutePath first + if (parameterType == typeof(FileInfo)) + { + AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(expandedParameterValue); + return InternalSetTaskParameter(parameter, new FileInfo(absolutePath.Value)); + } + + // Special handling for DirectoryInfo - validate path through AbsolutePath first + if (parameterType == typeof(DirectoryInfo)) + { + AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(expandedParameterValue); + return InternalSetTaskParameter(parameter, new DirectoryInfo(absolutePath.Value)); + } + // Use the unified ValueTypeParser for all other types object parsedValue = ValueTypeParser.Parse(expandedParameterValue, parameterType); return InternalSetTaskParameter(parameter, parsedValue); @@ -846,6 +867,16 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I { finalTaskInputs.Add(TaskEnvironment.GetAbsolutePath(item.ItemSpec)); } + else if (parameterType == typeof(FileInfo[])) + { + AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(item.ItemSpec); + finalTaskInputs.Add(new FileInfo(absolutePath.Value)); + } + else if (parameterType == typeof(DirectoryInfo[])) + { + AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(item.ItemSpec); + finalTaskInputs.Add(new DirectoryInfo(absolutePath.Value)); + } else { finalTaskInputs.Add(Convert.ChangeType(item.ItemSpec, elementType, CultureInfo.InvariantCulture)); diff --git a/src/Framework/ITaskItem_T.cs b/src/Framework/ITaskItem_T.cs index 4d36e7b1765..e36d34176e1 100644 --- a/src/Framework/ITaskItem_T.cs +++ b/src/Framework/ITaskItem_T.cs @@ -9,13 +9,13 @@ namespace Microsoft.Build.Framework /// A strongly-typed task item interface that wraps a value of type /// and provides access to it along with standard task item functionality. /// - /// The type of the value. Must be a value type. + /// The type of the value. Can be a value type, FileInfo, or DirectoryInfo. /// /// This interface allows tasks to receive strongly-typed parameters while still working with MSBuild's item system. /// The value is parsed from the item's identity (ItemSpec) using MSBuild's standard parsing conventions. + /// Supported types include primitive value types (int, bool, etc.), AbsolutePath, FileInfo, and DirectoryInfo. /// public interface ITaskItem : ITaskItem2 - where T : struct { /// /// Gets the strongly-typed value parsed from the item's identity. diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index 499fc022bf3..1a397ad98f8 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.IO; using Microsoft.Build.Framework; #nullable disable @@ -31,7 +32,13 @@ private static bool IsTaskItemOfT(Type parameterType) } Type[] genericArguments = parameterType.GetGenericArguments(); - return genericArguments.Length == 1 && genericArguments[0].IsValueType; + if (genericArguments.Length != 1) + { + return false; + } + + Type typeArg = genericArguments[0]; + return typeArg.IsValueType || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); } #endif @@ -44,6 +51,8 @@ internal static bool IsValidScalarInputParameter(Type parameterType) => parameterType == typeof(ITaskItem) #if !TASKHOST || parameterType == typeof(AbsolutePath) + || parameterType == typeof(FileInfo) + || parameterType == typeof(DirectoryInfo) || IsTaskItemOfT(parameterType) #endif ; @@ -65,6 +74,8 @@ internal static bool IsValidVectorInputParameter(Type parameterType) parameterType == typeof(ITaskItem[]) #if !TASKHOST || parameterType == typeof(AbsolutePath[]) + || parameterType == typeof(FileInfo[]) + || parameterType == typeof(DirectoryInfo[]) || IsTaskItemOfT(elementType) #endif ; @@ -107,11 +118,15 @@ internal static bool IsValueTypeOutputParameter(Type parameterType) parameterType == typeof(string[]) || /* string array, or */ #if !TASKHOST parameterType == typeof(AbsolutePath[]) || /* AbsolutePath array, or */ + parameterType == typeof(FileInfo[]) || /* FileInfo array, or */ + parameterType == typeof(DirectoryInfo[]) || /* DirectoryInfo array, or */ #endif parameterType.IsValueType || /* value type, or */ parameterType == typeof(string) /* string, or */ #if !TASKHOST - || parameterType == typeof(AbsolutePath) /* AbsolutePath */ + || parameterType == typeof(AbsolutePath) /* AbsolutePath, or */ + || parameterType == typeof(FileInfo) /* FileInfo, or */ + || parameterType == typeof(DirectoryInfo) /* DirectoryInfo */ #endif ; return result; diff --git a/src/Shared/ValueTypeParser.cs b/src/Shared/ValueTypeParser.cs index 5401e5a3601..331ac6ebd51 100644 --- a/src/Shared/ValueTypeParser.cs +++ b/src/Shared/ValueTypeParser.cs @@ -3,6 +3,7 @@ using System; using System.Globalization; +using System.IO; using Microsoft.Build.Framework; #nullable enable @@ -63,6 +64,18 @@ public static object Parse(string value, Type targetType) return new AbsolutePath(value); } + // Special handling for FileInfo + if (targetType == typeof(FileInfo)) + { + return new FileInfo(value); + } + + // Special handling for DirectoryInfo + if (targetType == typeof(DirectoryInfo)) + { + return new DirectoryInfo(value); + } + // Special handling for bool - MSBuild supports various boolean representations if (targetType == typeof(bool)) { @@ -132,6 +145,17 @@ public static string ToString(object? value) return absolutePath.Value; } + // FileInfo and DirectoryInfo need special handling to return their path + if (value is FileInfo fileInfo) + { + return fileInfo.FullName; + } + + if (value is DirectoryInfo directoryInfo) + { + return directoryInfo.FullName; + } + // Use InvariantCulture for consistent formatting return Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; } diff --git a/src/Utilities/TaskItem_T.cs b/src/Utilities/TaskItem_T.cs index 649f61972df..d23626ca7a2 100644 --- a/src/Utilities/TaskItem_T.cs +++ b/src/Utilities/TaskItem_T.cs @@ -12,14 +12,13 @@ namespace Microsoft.Build.Utilities /// A strongly-typed wrapper around that parses the item's identity /// as a value of type . /// - /// The type to parse the item identity as. Must be a value type. + /// The type to parse the item identity as. Can be a value type, FileInfo, or DirectoryInfo. /// /// This allows tasks to receive strongly-typed parameters while still working with MSBuild's item system. - /// The identity (ItemSpec) is parsed using or special handling for - /// types like . + /// The identity (ItemSpec) is parsed using which handles value types, + /// AbsolutePath, FileInfo, and DirectoryInfo. /// public readonly struct TaskItem : ITaskItem, IEquatable> - where T : struct { private readonly ITaskItem _backingItem; @@ -155,13 +154,14 @@ public IDictionary CloneCustomMetadataEscaped() #region Equality and Conversion /// - public bool Equals(TaskItem other) => Value.Equals(other.Value); + public bool Equals(TaskItem other) => + Value?.Equals(other.Value) ?? (other.Value == null); /// public override bool Equals(object? obj) => obj is TaskItem other && Equals(other); /// - public override int GetHashCode() => Value.GetHashCode(); + public override int GetHashCode() => Value?.GetHashCode() ?? 0; /// /// Determines whether two instances are equal. From 068689159c509dea12ebe4168dfae4200ad21826 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 4 Jun 2026 10:43:36 -0500 Subject: [PATCH 04/27] Remove dead #if !TASKHOST guards from TaskParameterTypeVerifier The TASKHOST define is no longer set by any project in the main codebase since the .NET 3.5 taskhost was separated into a frozen project. These guards were always evaluating to true. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Shared/TaskParameterTypeVerifier.cs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index 1a397ad98f8..ea81d18fd50 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -14,7 +14,6 @@ namespace Microsoft.Build.BackEnd /// internal static class TaskParameterTypeVerifier { -#if !TASKHOST /// /// Checks if a type is ITaskItem<T> where T is a value type. /// @@ -40,7 +39,6 @@ private static bool IsTaskItemOfT(Type parameterType) Type typeArg = genericArguments[0]; return typeArg.IsValueType || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); } -#endif /// /// Is the parameter type a valid scalar input value @@ -49,12 +47,10 @@ internal static bool IsValidScalarInputParameter(Type parameterType) => parameterType.IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem) -#if !TASKHOST || parameterType == typeof(AbsolutePath) || parameterType == typeof(FileInfo) || parameterType == typeof(DirectoryInfo) || IsTaskItemOfT(parameterType) -#endif ; /// @@ -72,12 +68,10 @@ internal static bool IsValidVectorInputParameter(Type parameterType) bool result = elementType.IsValueType || parameterType == typeof(string[]) || parameterType == typeof(ITaskItem[]) -#if !TASKHOST || parameterType == typeof(AbsolutePath[]) || parameterType == typeof(FileInfo[]) || parameterType == typeof(DirectoryInfo[]) || IsTaskItemOfT(elementType) -#endif ; return result; } @@ -91,7 +85,6 @@ internal static bool IsAssignableToITaskItem(Type parameterType) bool result = typeof(ITaskItem[]).IsAssignableFrom(parameterType) || /* ITaskItem array or derived type, or */ typeof(ITaskItem).IsAssignableFrom(parameterType); /* ITaskItem or derived type */ -#if !TASKHOST // Also check for TaskItem or TaskItem[] if (!result) { @@ -104,7 +97,6 @@ internal static bool IsAssignableToITaskItem(Type parameterType) result = IsTaskItemOfT(parameterType); } } -#endif return result; } @@ -116,18 +108,14 @@ internal static bool IsValueTypeOutputParameter(Type parameterType) { bool result = (parameterType.IsArray && parameterType.GetElementType().IsValueType) || /* array of value types, or */ parameterType == typeof(string[]) || /* string array, or */ -#if !TASKHOST parameterType == typeof(AbsolutePath[]) || /* AbsolutePath array, or */ parameterType == typeof(FileInfo[]) || /* FileInfo array, or */ parameterType == typeof(DirectoryInfo[]) || /* DirectoryInfo array, or */ -#endif parameterType.IsValueType || /* value type, or */ parameterType == typeof(string) /* string, or */ -#if !TASKHOST || parameterType == typeof(AbsolutePath) /* AbsolutePath, or */ || parameterType == typeof(FileInfo) /* FileInfo, or */ || parameterType == typeof(DirectoryInfo) /* DirectoryInfo */ -#endif ; return result; } From 4c1bdf2ae174bd73731e27f4c2eeeab097659bcb Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 4 Jun 2026 15:30:40 -0500 Subject: [PATCH 05/27] Fix task host crash serializing typed task outputs The out-of-proc task host gathers all [Output] properties and serializes them via TaskParameter. The PR's new AbsolutePath/FileInfo/DirectoryInfo outputs crashed the node: AbsolutePath (a struct) is never null so it always serialized, and Convert.ChangeType threw InvalidCastException because it is not IConvertible; FileInfo/DirectoryInfo additionally hit Assumed.Unreachable in the constructor. Route FileInfo/DirectoryInfo (scalar and array) to ValueType/ValueTypeArray, and convert values on the write side using ValueTypeParser.ToString - the same canonical conversion the in-process engine uses in TaskExecutionHost.GetValueOutputs - so in-proc and out-of-proc produce identical strings. Harden ValueTypeParser.ToString for a default AbsolutePath (null Value). The legacy net35 task host is intentionally untouched. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Shared/TaskParameter.cs | 41 ++++--- src/Shared/UnitTests/TaskParameter_Tests.cs | 129 ++++++++++++++++++++ src/Shared/ValueTypeParser.cs | 2 +- 3 files changed, 156 insertions(+), 16 deletions(-) diff --git a/src/Shared/TaskParameter.cs b/src/Shared/TaskParameter.cs index 76496e1c961..5db7716dac5 100644 --- a/src/Shared/TaskParameter.cs +++ b/src/Shared/TaskParameter.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.IO; using System.Linq; using Microsoft.Build.Collections; @@ -41,12 +42,14 @@ internal enum TaskParameterType PrimitiveTypeArray, /// - /// Parameter is a value type. Note: Must be . + /// Parameter is a non-primitive value serialized as a string (for example a value type + /// such as , or /). /// ValueType, /// - /// Parameter is an array of value types. Note: Must be . + /// Parameter is an array of non-primitive values serialized as strings (for example an array + /// of value types, or []/[]). /// ValueTypeArray, @@ -141,8 +144,11 @@ public TaskParameter(object wrappedParameter) _wrappedParameter = taskItemArrayParameter; } - else if (wrappedParameterType.GetElementType().IsValueType) + else if (wrappedParameterType.GetElementType().IsValueType + || wrappedParameterType.GetElementType() == typeof(FileInfo) + || wrappedParameterType.GetElementType() == typeof(DirectoryInfo)) { + // Value-type arrays as well as FileInfo[]/DirectoryInfo[] are serialized as strings. _parameterType = TaskParameterType.ValueTypeArray; _wrappedParameter = wrappedParameter; } @@ -176,8 +182,11 @@ public TaskParameter(object wrappedParameter) _parameterType = TaskParameterType.ITaskItem; _wrappedParameter = new TaskParameterTaskItem((ITaskItem)wrappedParameter); } - else if (wrappedParameterType.IsValueType) + else if (wrappedParameterType.IsValueType + || wrappedParameterType == typeof(FileInfo) + || wrappedParameterType == typeof(DirectoryInfo)) { + // Value types as well as FileInfo/DirectoryInfo are serialized as strings. _parameterType = TaskParameterType.ValueType; _wrappedParameter = wrappedParameter; } @@ -467,37 +476,39 @@ private void TranslatePrimitiveTypeArray(ITranslator translator) } /// - /// Serializes or deserializes the value type instance wrapped by this . + /// Serializes or deserializes the value instance wrapped by this . /// /// - /// The value type is converted to/from string using the class. Note that we require - /// task parameter types to be so this conversion is guaranteed to work for parameters - /// that have made it this far. + /// The value is converted to a string on the write side using , + /// the same canonical conversion the in-process engine uses when gathering task outputs + /// (see TaskExecutionHost.GetValueOutputs). This guarantees identical string output across the + /// in-process and out-of-process task host paths. The value is not converted back to its original + /// type on the read side: this is fine because output task parameters are anyway converted to strings + /// by the engine and input task parameters of custom value types are not supported. /// private void TranslateValueType(ITranslator translator) { string valueString = null; if (translator.Mode == TranslationDirection.WriteToStream) { - valueString = (string)Convert.ChangeType(_wrappedParameter, typeof(string), CultureInfo.InvariantCulture); + valueString = ValueTypeParser.ToString(_wrappedParameter); } translator.Translate(ref valueString); if (translator.Mode == TranslationDirection.ReadFromStream) { - // We don't know how to convert the string back to the original value type. This is fine because output - // task parameters are anyway converted to strings by the engine (see TaskExecutionHost.GetValueOutputs) - // and input task parameters of custom value types are not supported. _wrappedParameter = valueString; } } /// - /// Serializes or deserializes the value type array instance wrapped by this . + /// Serializes or deserializes the array instance wrapped by this . /// /// - /// The array is assumed to be non-null. + /// The array is assumed to be non-null. Each element is converted to a string on the write side + /// using , the same canonical conversion the in-process engine + /// uses when gathering task outputs. /// private void TranslateValueTypeArray(ITranslator translator) { @@ -510,7 +521,7 @@ private void TranslateValueTypeArray(ITranslator translator) for (int i = 0; i < length; i++) { - string valueString = Convert.ToString(array.GetValue(i), CultureInfo.InvariantCulture); + string valueString = ValueTypeParser.ToString(array.GetValue(i)); translator.Translate(ref valueString); } } diff --git a/src/Shared/UnitTests/TaskParameter_Tests.cs b/src/Shared/UnitTests/TaskParameter_Tests.cs index 28e9aba157f..b70b70169c9 100644 --- a/src/Shared/UnitTests/TaskParameter_Tests.cs +++ b/src/Shared/UnitTests/TaskParameter_Tests.cs @@ -165,6 +165,135 @@ public void ValueTypeArrayParameter() Assert.Equal(value[1].ToString(CultureInfo.InvariantCulture), stringArray[1]); } + /// + /// A default (null Value) must serialize cleanly. This is the + /// scenario that crashed the out-of-proc task host: a struct-typed output is never null, so + /// it always gets serialized, and the old code threw InvalidCastException because AbsolutePath + /// is not IConvertible. See https://github.com/dotnet/msbuild/pull/13016. + /// + [Fact] + public void DefaultAbsolutePathParameter() + { + TaskParameter t = new TaskParameter(default(AbsolutePath)); + + Assert.Equal(TaskParameterType.ValueType, t.ParameterType); + + ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); + TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); + + // A default AbsolutePath has a null Value and serializes to the empty string. + Assert.Equal(string.Empty, t2.WrappedParameter); + Assert.Equal(TaskParameterType.ValueType, t2.ParameterType); + } + + [Fact] + public void AbsolutePathParameter() + { + string path = Path.Combine(Path.GetTempPath(), "TaskParameterTests_file.txt"); + AbsolutePath value = new AbsolutePath(path); + TaskParameter t = new TaskParameter(value); + + Assert.Equal(TaskParameterType.ValueType, t.ParameterType); + + ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); + TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); + + // Path types are serialized using the same canonical conversion as the in-process engine. + Assert.Equal(value.Value, t2.WrappedParameter); + Assert.Equal(TaskParameterType.ValueType, t2.ParameterType); + } + + [Fact] + public void AbsolutePathArrayParameter() + { + AbsolutePath[] value = new AbsolutePath[] + { + new AbsolutePath(Path.Combine(Path.GetTempPath(), "a.txt")), + new AbsolutePath(Path.Combine(Path.GetTempPath(), "b.txt")), + }; + TaskParameter t = new TaskParameter(value); + + Assert.Equal(TaskParameterType.ValueTypeArray, t.ParameterType); + + ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); + TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); + + string[] stringArray = Assert.IsType(t2.WrappedParameter); + Assert.Equal(value[0].Value, stringArray[0]); + Assert.Equal(value[1].Value, stringArray[1]); + } + + [Fact] + public void FileInfoParameter() + { + FileInfo value = new FileInfo(Path.Combine(Path.GetTempPath(), "TaskParameterTests_file.txt")); + TaskParameter t = new TaskParameter(value); + + Assert.Equal(TaskParameterType.ValueType, t.ParameterType); + + ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); + TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); + + // FileInfo is serialized as its full path, matching ValueTypeParser/the in-process engine. + Assert.Equal(value.FullName, t2.WrappedParameter); + Assert.Equal(TaskParameterType.ValueType, t2.ParameterType); + } + + [Fact] + public void DirectoryInfoParameter() + { + DirectoryInfo value = new DirectoryInfo(Path.Combine(Path.GetTempPath(), "TaskParameterTests_dir")); + TaskParameter t = new TaskParameter(value); + + Assert.Equal(TaskParameterType.ValueType, t.ParameterType); + + ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); + TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); + + Assert.Equal(value.FullName, t2.WrappedParameter); + Assert.Equal(TaskParameterType.ValueType, t2.ParameterType); + } + + [Fact] + public void FileInfoArrayParameter() + { + FileInfo[] value = new FileInfo[] + { + new FileInfo(Path.Combine(Path.GetTempPath(), "a.txt")), + new FileInfo(Path.Combine(Path.GetTempPath(), "b.txt")), + }; + TaskParameter t = new TaskParameter(value); + + Assert.Equal(TaskParameterType.ValueTypeArray, t.ParameterType); + + ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); + TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); + + string[] stringArray = Assert.IsType(t2.WrappedParameter); + Assert.Equal(value[0].FullName, stringArray[0]); + Assert.Equal(value[1].FullName, stringArray[1]); + } + + [Fact] + public void DirectoryInfoArrayParameter() + { + DirectoryInfo[] value = new DirectoryInfo[] + { + new DirectoryInfo(Path.Combine(Path.GetTempPath(), "dirA")), + new DirectoryInfo(Path.Combine(Path.GetTempPath(), "dirB")), + }; + TaskParameter t = new TaskParameter(value); + + Assert.Equal(TaskParameterType.ValueTypeArray, t.ParameterType); + + ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); + TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); + + string[] stringArray = Assert.IsType(t2.WrappedParameter); + Assert.Equal(value[0].FullName, stringArray[0]); + Assert.Equal(value[1].FullName, stringArray[1]); + } + private enum TestEnumForParameter { Something, diff --git a/src/Shared/ValueTypeParser.cs b/src/Shared/ValueTypeParser.cs index 331ac6ebd51..18e86394642 100644 --- a/src/Shared/ValueTypeParser.cs +++ b/src/Shared/ValueTypeParser.cs @@ -142,7 +142,7 @@ public static string ToString(object? value) // AbsolutePath needs special handling because Convert.ChangeType doesn't work with implicit operators if (value is AbsolutePath absolutePath) { - return absolutePath.Value; + return absolutePath.Value ?? string.Empty; } // FileInfo and DirectoryInfo need special handling to return their path From bdf2ef3c7fccc527ab3a760dd8b3c5671d90ecf9 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 4 Jun 2026 17:43:04 -0500 Subject: [PATCH 06/27] Fix TaskItem parse errors surface as InvalidProjectFileException Unwrap TargetInvocationException in CreateTaskItemOfT so that parse errors from value-type constructors surface as the original exception (typically InvalidProjectFileException) rather than being wrapped in TargetInvocationException, which was swallowed by the outer catch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../BackEnd/TaskExecutionHost_Tests.cs | 24 +++++++++++++++++++ .../TaskExecutionHost/TaskExecutionHost.cs | 10 +++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs index 564a70a7723..b725969d045 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -576,6 +576,18 @@ public void TestSetTaskItemIntParam() ValidateTaskParameter("TaskItemIntParam", "42", new Microsoft.Build.Utilities.TaskItem(42)); } + /// + /// Validate that parse failures from TaskItem<T> scalar binding are reported as invalid task parameter values. + /// + [Fact] + public void TestSetTaskItemIntParamInvalidValue() + { + var parameters = GetStandardParametersDictionary(true); + parameters["TaskItemIntParam"] = ("not-an-int", ElementLocation.Create("foo.proj")); + + Should.Throw(() => _host.SetTaskParameters(parameters)); + } + /// /// Validate that setting the parameter with an empty value does not cause it to be set. /// @@ -629,6 +641,18 @@ public void TestSetTaskItemIntArrayParamMultiple() }); } + /// + /// Validate that parse failures from TaskItem<T> array binding are reported as invalid task parameter values. + /// + [Fact] + public void TestSetTaskItemIntArrayParamInvalidValue() + { + var parameters = GetStandardParametersDictionary(true); + parameters["TaskItemIntArrayParam"] = ("10;not-an-int", ElementLocation.Create("foo.proj")); + + Should.Throw(() => _host.SetTaskParameters(parameters)); + } + /// /// Validate that setting the parameter with an empty value does not cause it to be set. /// diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index 030559b1f91..37a0716f0b7 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -795,7 +795,15 @@ private static object CreateTaskItemOfT(Type taskItemType, ITaskItem item) Type constructedType = typeof(TaskItem<>).MakeGenericType(valueType); ConstructorInfo constructor = constructedType.GetConstructor(new[] { typeof(ITaskItem) }); - return constructor.Invoke(new object[] { item }); + try + { + return constructor.Invoke(new object[] { item }); + } + catch (TargetInvocationException e) when (e.InnerException is not null) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw(); + throw; + } } /// From 2c481c881517742d92f1b151408a961736ebd48e Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 4 Jun 2026 18:31:33 -0500 Subject: [PATCH 07/27] Use mutable TaskItem backing for TaskItem TaskItemData throws InvalidOperationException on all write operations (SetMetadata, RemoveMetadata, CopyMetadataTo). Switch the TaskItem(T) constructor to use Utilities.TaskItem as the backing item, which supports full metadata mutation as expected by ITaskItem consumers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Utilities.UnitTests/TaskItem_Tests.cs | 34 +++++++++++++++++++++++ src/Utilities/TaskItem_T.cs | 8 ++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/Utilities.UnitTests/TaskItem_Tests.cs b/src/Utilities.UnitTests/TaskItem_Tests.cs index 6e0cc3a9afa..30d0124f801 100644 --- a/src/Utilities.UnitTests/TaskItem_Tests.cs +++ b/src/Utilities.UnitTests/TaskItem_Tests.cs @@ -439,4 +439,38 @@ public void Run(string[] includes, IDictionary metadataToAdd) } #endif } + + /// + /// Tests for the generic struct. + /// + public class TaskItemOfTTests + { + [Fact] + public void SetMetadata_DoesNotThrow() + { + var item = new TaskItem(42); + // Should not throw - backing is a mutable TaskItem, not TaskItemData + item.SetMetadata("key", "value"); + item.GetMetadata("key").ShouldBe("value"); + } + + [Fact] + public void RemoveMetadata_DoesNotThrow() + { + var item = new TaskItem(42); + item.SetMetadata("key", "value"); + item.RemoveMetadata("key"); + item.GetMetadata("key").ShouldBeNullOrEmpty(); + } + + [Fact] + public void CopyMetadataTo_DoesNotThrow() + { + var source = new TaskItem(42); + source.SetMetadata("key", "value"); + var dest = new TaskItem("dest"); + source.CopyMetadataTo(dest); + dest.GetMetadata("key").ShouldBe("value"); + } + } } diff --git a/src/Utilities/TaskItem_T.cs b/src/Utilities/TaskItem_T.cs index d23626ca7a2..9e901f843ff 100644 --- a/src/Utilities/TaskItem_T.cs +++ b/src/Utilities/TaskItem_T.cs @@ -6,6 +6,10 @@ using Microsoft.Build.Framework; using Microsoft.Build.Shared; +// Alias to avoid ambiguity: within TaskItem, "TaskItem" refers to this generic struct; +// use TaskItemImpl to refer to the non-generic Utilities.TaskItem class. +using TaskItemImpl = Microsoft.Build.Utilities.TaskItem; + namespace Microsoft.Build.Utilities { /// @@ -35,9 +39,9 @@ public TaskItem(T value) { Value = value; - // Create a backing item with the stringified value as ItemSpec + // Use a mutable TaskItem as backing so metadata mutations are supported string itemSpec = ValueTypeParser.ToString(value); - _backingItem = new TaskItemData(itemSpec, null); + _backingItem = new TaskItemImpl(itemSpec); } /// From 5a4db7ea049dc1627d0a7e45d37783c89e2e9d48 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 4 Jun 2026 18:33:38 -0500 Subject: [PATCH 08/27] Use FullPath metadata for path-like T in TaskItem When constructing TaskItem from an ITaskItem where T is FileInfo, DirectoryInfo, or AbsolutePath, prefer the FullPath metadata (which the MSBuild item system computes as an absolute rooted path) over ItemSpec, which may be a relative path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Utilities.UnitTests/TaskItem_Tests.cs | 21 +++++++++++++++++++++ src/Utilities/TaskItem_T.cs | 22 ++++++++++++++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/Utilities.UnitTests/TaskItem_Tests.cs b/src/Utilities.UnitTests/TaskItem_Tests.cs index 30d0124f801..77743a541b3 100644 --- a/src/Utilities.UnitTests/TaskItem_Tests.cs +++ b/src/Utilities.UnitTests/TaskItem_Tests.cs @@ -472,5 +472,26 @@ public void CopyMetadataTo_DoesNotThrow() source.CopyMetadataTo(dest); dest.GetMetadata("key").ShouldBe("value"); } + + [Fact] + public void FromITaskItem_PathLikeType_UsesFullPathMetadata() + { + // FullPath is a reserved metadata computed by the MSBuild item system as the absolute path. + // TaskItem should use FullPath so relative ItemSpecs resolve to absolute paths. + var backingItem = new TaskItem("relative\\path.txt"); + string expectedAbsolutePath = backingItem.GetMetadata("FullPath"); + expectedAbsolutePath.ShouldNotBeNullOrEmpty(); + + var item = new TaskItem(backingItem); + item.Value.FullName.ShouldBe(expectedAbsolutePath); + } + + [Fact] + public void FromITaskItem_NonPathType_UsesItemSpec() + { + var backingItem = new TaskItem("42"); + var item = new TaskItem(backingItem); + item.Value.ShouldBe(42); + } } } diff --git a/src/Utilities/TaskItem_T.cs b/src/Utilities/TaskItem_T.cs index 9e901f843ff..8685514b5bb 100644 --- a/src/Utilities/TaskItem_T.cs +++ b/src/Utilities/TaskItem_T.cs @@ -65,8 +65,26 @@ public TaskItem(ITaskItem item) throw new ArgumentException($"Cannot create TaskItem<{typeof(T).Name}> from an item with empty identity.", nameof(item)); } - // Parse the value from ItemSpec - Value = ParseValue(itemSpec); + // For path-like types, prefer the FullPath metadata (which is always absolute) + // over ItemSpec which may be relative. + string parseFrom = IsPathLikeType() ? GetFullPathOrItemSpec(item, itemSpec) : itemSpec; + Value = ParseValue(parseFrom); + } + + /// Returns true if T is a path-like type that benefits from absolute path resolution. + private static bool IsPathLikeType() + { + Type t = typeof(T); + return t == typeof(System.IO.FileInfo) || + t == typeof(System.IO.DirectoryInfo) || + t == typeof(AbsolutePath); + } + + /// Returns the FullPath metadata value if non-empty, otherwise falls back to itemSpec. + private static string GetFullPathOrItemSpec(ITaskItem item, string itemSpec) + { + string fullPath = item.GetMetadata("FullPath"); + return !string.IsNullOrEmpty(fullPath) ? fullPath : itemSpec; } /// From ef3b4ee06f9cc8d3a1bd267a21156d2afb1a0347 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 4 Jun 2026 18:35:16 -0500 Subject: [PATCH 09/27] Use EqualityComparer.Default in TaskItem equality Replace Value?.Equals(other.Value) with EqualityComparer.Default.Equals to avoid boxing for value types, correctly handle null reference types, and use the appropriate comparer for each type T. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Utilities.UnitTests/TaskItem_Tests.cs | 42 +++++++++++++++++++++++ src/Utilities/TaskItem_T.cs | 5 +-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/Utilities.UnitTests/TaskItem_Tests.cs b/src/Utilities.UnitTests/TaskItem_Tests.cs index 77743a541b3..1b42c8d3169 100644 --- a/src/Utilities.UnitTests/TaskItem_Tests.cs +++ b/src/Utilities.UnitTests/TaskItem_Tests.cs @@ -493,5 +493,47 @@ public void FromITaskItem_NonPathType_UsesItemSpec() var item = new TaskItem(backingItem); item.Value.ShouldBe(42); } + + [Fact] + public void Equals_SameValue_ReturnsTrue() + { + var a = new TaskItem(42); + var b = new TaskItem(42); + a.Equals(b).ShouldBeTrue(); + (a == b).ShouldBeTrue(); + } + + [Fact] + public void Equals_DifferentValue_ReturnsFalse() + { + var a = new TaskItem(1); + var b = new TaskItem(2); + a.Equals(b).ShouldBeFalse(); + (a != b).ShouldBeTrue(); + } + + [Fact] + public void Equals_NullStringValue_HandledCorrectly() + { + // EqualityComparer.Default handles null without boxing or NullReferenceException + var a = new TaskItem((string)null!); + var b = new TaskItem((string)null!); + a.Equals(b).ShouldBeTrue(); + } + + [Fact] + public void GetHashCode_NullValue_ReturnsZero() + { + var item = new TaskItem((string)null!); + item.GetHashCode().ShouldBe(0); + } + + [Fact] + public void GetHashCode_ConsistentWithEquality() + { + var a = new TaskItem(42); + var b = new TaskItem(42); + a.GetHashCode().ShouldBe(b.GetHashCode()); + } } } diff --git a/src/Utilities/TaskItem_T.cs b/src/Utilities/TaskItem_T.cs index 8685514b5bb..6cd469000f5 100644 --- a/src/Utilities/TaskItem_T.cs +++ b/src/Utilities/TaskItem_T.cs @@ -3,6 +3,7 @@ using System; using System.Collections; +using System.Collections.Generic; using Microsoft.Build.Framework; using Microsoft.Build.Shared; @@ -177,13 +178,13 @@ public IDictionary CloneCustomMetadataEscaped() /// public bool Equals(TaskItem other) => - Value?.Equals(other.Value) ?? (other.Value == null); + EqualityComparer.Default.Equals(Value, other.Value); /// public override bool Equals(object? obj) => obj is TaskItem other && Equals(other); /// - public override int GetHashCode() => Value?.GetHashCode() ?? 0; + public override int GetHashCode() => Value is null ? 0 : EqualityComparer.Default.GetHashCode(Value); /// /// Determines whether two instances are equal. From ce1ff3286b3f2837682c347ef74cbd22e161318b Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 4 Jun 2026 23:08:33 -0500 Subject: [PATCH 10/27] Ensure ITaskItem[] arrays are recognized in TaskParameterTypeVerifier The code already correctly handles ITaskItem[] for both input (IsValidVectorInputParameter) and output (IsAssignableToITaskItem), but had no explicit test coverage. Add tests for all four methods covering scalar and array ITaskItem to prevent future regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../TaskParameterTypeVerifier_Tests.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs index 1f1f00d6fad..9bc597fcb69 100644 --- a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs @@ -321,6 +321,44 @@ public void IsValidOutputParameter_ObjectArray_ReturnsFalse() Assert.False(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(object[]))); } + // ─── ITaskItem and ITaskItem[] coverage ─────────────────────────── + + [Fact] + public void IsValidScalarInputParameter_ITaskItemOfT_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(ITaskItem))); + } + + [Fact] + public void IsValidVectorInputParameter_ITaskItemOfTArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(ITaskItem[]))); + } + + [Fact] + public void IsAssignableToITaskItem_ITaskItemOfT_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(ITaskItem))); + } + + [Fact] + public void IsAssignableToITaskItem_ITaskItemOfTArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(ITaskItem[]))); + } + + [Fact] + public void IsValidOutputParameter_ITaskItemOfT_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem))); + } + + [Fact] + public void IsValidOutputParameter_ITaskItemOfTArray_ReturnsTrue() + { + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem[]))); + } + #endregion } } From 90ef8e238a80969b4050cf9de0fc3268a529c1a8 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 11:02:03 -0500 Subject: [PATCH 11/27] Fix TaskItem[] output type verification Treat arrays with ITaskItem-implementing element types as assignable outputs so TaskItem[] follows the item-output path consistently with TaskExecutionHost behavior. Add unit tests covering TaskItem[] assignability and output validity. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../BackEnd/TaskParameterTypeVerifier_Tests.cs | 15 +++++++++++++++ src/Shared/TaskParameterTypeVerifier.cs | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs index 9bc597fcb69..b99aeba8821 100644 --- a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs @@ -4,6 +4,8 @@ using System; using Microsoft.Build.BackEnd; using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; +using Shouldly; using Xunit; #nullable disable @@ -359,6 +361,19 @@ public void IsValidOutputParameter_ITaskItemOfTArray_ReturnsTrue() Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem[]))); } + [Fact] + public void IsAssignableToITaskItem_TaskItemOfTArray_ReturnsTrue() + { + typeof(ITaskItem[]).IsAssignableFrom(typeof(TaskItem[])).ShouldBeFalse(); + TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(TaskItem[])).ShouldBeTrue(); + } + + [Fact] + public void IsValidOutputParameter_TaskItemOfTArray_ReturnsTrue() + { + TaskParameterTypeVerifier.IsValidOutputParameter(typeof(TaskItem[])).ShouldBeTrue(); + } + #endregion } } diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index ea81d18fd50..aa474f1e8f6 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -81,6 +81,11 @@ internal static bool IsValidVectorInputParameter(Type parameterType) /// internal static bool IsAssignableToITaskItem(Type parameterType) { + if (parameterType.IsArray && typeof(ITaskItem).IsAssignableFrom(parameterType.GetElementType())) + { + return true; + } + // Check if it's directly assignable bool result = typeof(ITaskItem[]).IsAssignableFrom(parameterType) || /* ITaskItem array or derived type, or */ typeof(ITaskItem).IsAssignableFrom(parameterType); /* ITaskItem or derived type */ From 54e6df428d6955ab8eccf61a9edcb6bd64074657 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 14:34:55 -0500 Subject: [PATCH 12/27] Restrict ITaskItem binding to path-like types (AbsolutePath, FileInfo, DirectoryInfo) in PR1 Value-type T (int, bool, etc.) support for ITaskItem will be added in a subsequent PR. Also remove ITaskItem tests from PR1 test files. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../BackEnd/TaskBuilderTestTask.cs | 60 ------- .../BackEnd/TaskExecutionHost_Tests.cs | 161 ------------------ .../TaskParameterTypeVerifier_Tests.cs | 49 ++++-- .../TaskExecutionHost/TaskExecutionHost.cs | 4 +- src/Shared/TaskParameterTypeVerifier.cs | 4 +- 5 files changed, 35 insertions(+), 243 deletions(-) diff --git a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs index 0b855c9e9ff..001edd7fe9d 100644 --- a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs +++ b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs @@ -246,16 +246,6 @@ public CustomStruct(IConvertible value) /// private AbsolutePath[] _absolutePathArrayOutput; - /// - /// The value for the TaskItemIntOutput. - /// - private ITaskItem _taskItemIntOutput; - - /// - /// The value for the TaskItemIntArrayOutput. - /// - private ITaskItem[] _taskItemIntArrayOutput; - /// /// The value for the FileInfoOutput. /// @@ -713,30 +703,6 @@ public AbsolutePath[] AbsolutePathArrayParam } } - /// - /// A TaskItem<int> parameter. - /// - public ITaskItem TaskItemIntParam - { - set - { - _taskItemIntOutput = value; - _testTaskHost?.ParameterSet("TaskItemIntParam", value); - } - } - - /// - /// A TaskItem<int> array parameter. - /// - public ITaskItem[] TaskItemIntArrayParam - { - set - { - _taskItemIntArrayOutput = value; - _testTaskHost?.ParameterSet("TaskItemIntArrayParam", value); - } - } - /// /// A FileInfo parameter. /// @@ -1405,32 +1371,6 @@ public AbsolutePath[] AbsolutePathArrayOutput } } - /// - /// A TaskItem<int> output. - /// - [Output] - public ITaskItem TaskItemIntOutput - { - get - { - _testTaskHost?.OutputRead("TaskItemIntOutput", _taskItemIntOutput); - return _taskItemIntOutput; - } - } - - /// - /// A TaskItem<int> array output. - /// - [Output] - public ITaskItem[] TaskItemIntArrayOutput - { - get - { - _testTaskHost?.OutputRead("TaskItemIntArrayOutput", _taskItemIntArrayOutput); - return _taskItemIntArrayOutput; - } - } - /// /// A FileInfo output. /// diff --git a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs index b725969d045..5462db854a5 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -565,123 +565,6 @@ public void TestSetAbsolutePathArrayParamEmptyItem() #endregion - #region TaskItem Params - - /// - /// Validate that setting a TaskItem<int> parameter with a valid integer works. - /// - [Fact] - public void TestSetTaskItemIntParam() - { - ValidateTaskParameter("TaskItemIntParam", "42", new Microsoft.Build.Utilities.TaskItem(42)); - } - - /// - /// Validate that parse failures from TaskItem<T> scalar binding are reported as invalid task parameter values. - /// - [Fact] - public void TestSetTaskItemIntParamInvalidValue() - { - var parameters = GetStandardParametersDictionary(true); - parameters["TaskItemIntParam"] = ("not-an-int", ElementLocation.Create("foo.proj")); - - Should.Throw(() => _host.SetTaskParameters(parameters)); - } - - /// - /// Validate that setting the parameter with an empty value does not cause it to be set. - /// - [Fact] - public void TestSetTaskItemIntParamEmptyAttribute() - { - ValidateTaskParameterNotSet("TaskItemIntParam", ""); - } - - /// - /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. - /// - [Fact] - public void TestSetTaskItemIntParamEmptyProperty() - { - ValidateTaskParameterNotSet("TaskItemIntParam", "$(NonExistentProperty)"); - } - - /// - /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. - /// - [Fact] - public void TestSetTaskItemIntParamEmptyItem() - { - ValidateTaskParameterNotSet("TaskItemIntParam", "@(NonExistentItem)"); - } - - #endregion - - #region TaskItem Array Params - - /// - /// Validate that setting a TaskItem<int> array with a single value sets the correct value. - /// - [Fact] - public void TestSetTaskItemIntArrayParam() - { - ValidateTaskParameterArray("TaskItemIntArrayParam", "42", new Microsoft.Build.Utilities.TaskItem[] { new Microsoft.Build.Utilities.TaskItem(42) }); - } - - /// - /// Validate that setting a TaskItem<int> array with multiple values sets the correct values. - /// - [Fact] - public void TestSetTaskItemIntArrayParamMultiple() - { - ValidateTaskParameterArray("TaskItemIntArrayParam", "10;20;30", new Microsoft.Build.Utilities.TaskItem[] { - new Microsoft.Build.Utilities.TaskItem(10), - new Microsoft.Build.Utilities.TaskItem(20), - new Microsoft.Build.Utilities.TaskItem(30) - }); - } - - /// - /// Validate that parse failures from TaskItem<T> array binding are reported as invalid task parameter values. - /// - [Fact] - public void TestSetTaskItemIntArrayParamInvalidValue() - { - var parameters = GetStandardParametersDictionary(true); - parameters["TaskItemIntArrayParam"] = ("10;not-an-int", ElementLocation.Create("foo.proj")); - - Should.Throw(() => _host.SetTaskParameters(parameters)); - } - - /// - /// Validate that setting the parameter with an empty value does not cause it to be set. - /// - [Fact] - public void TestSetTaskItemIntArrayParamEmptyAttribute() - { - ValidateTaskParameterNotSet("TaskItemIntArrayParam", ""); - } - - /// - /// Validate that setting the parameter with a property which evaluates to an empty value does not cause it to be set. - /// - [Fact] - public void TestSetTaskItemIntArrayParamEmptyProperty() - { - ValidateTaskParameterNotSet("TaskItemIntArrayParam", "$(NonExistentProperty)"); - } - - /// - /// Validate that setting the parameter with an item which evaluates to an empty value does not cause it to be set. - /// - [Fact] - public void TestSetTaskItemIntArrayParamEmptyItem() - { - ValidateTaskParameterNotSet("TaskItemIntArrayParam", "@(NonExistentItem)"); - } - - #endregion - #region FileInfo Params /// @@ -1477,50 +1360,6 @@ public void TestOutputItemArrayToProperty() #endregion - #region TaskItem Outputs - - /// - /// Validate that a TaskItem<int> output to an item produces the correct evaluated include. - /// - [Fact] - public void TestOutputTaskItemIntToItem() - { - SetTaskParameter("TaskItemIntParam", "42"); - ValidateOutputItem("TaskItemIntOutput", "42"); - } - - /// - /// Validate that a TaskItem<int> output to a property produces the correct evaluated value. - /// - [Fact] - public void TestOutputTaskItemIntToProperty() - { - SetTaskParameter("TaskItemIntParam", "42"); - ValidateOutputProperty("TaskItemIntOutput", "42"); - } - - /// - /// Validate that a TaskItem<int> array output to items produces the correct evaluated includes. - /// - [Fact] - public void TestOutputTaskItemIntArrayToItems() - { - SetTaskParameter("TaskItemIntArrayParam", "42;99"); - ValidateOutputItems("TaskItemIntArrayOutput", new string[] { "42", "99" }); - } - - /// - /// Validate that a TaskItem<int> array output to a property produces the correct semi-colon-delimited evaluated value. - /// - [Fact] - public void TestOutputTaskItemIntArrayToProperty() - { - SetTaskParameter("TaskItemIntArrayParam", "42;99"); - ValidateOutputProperty("TaskItemIntArrayOutput", "42;99"); - } - - #endregion - #region Other Output Tests /// diff --git a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs index b99aeba8821..6244dd8599d 100644 --- a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.IO; using Microsoft.Build.BackEnd; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; @@ -323,55 +324,67 @@ public void IsValidOutputParameter_ObjectArray_ReturnsFalse() Assert.False(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(object[]))); } - // ─── ITaskItem and ITaskItem[] coverage ─────────────────────────── + // ─── ITaskItem and ITaskItem[] coverage (path-like types) ──────── [Fact] - public void IsValidScalarInputParameter_ITaskItemOfT_ReturnsTrue() + public void IsValidScalarInputParameter_ITaskItemOfAbsolutePath_ReturnsTrue() { - Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(ITaskItem))); + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(ITaskItem))); } [Fact] - public void IsValidVectorInputParameter_ITaskItemOfTArray_ReturnsTrue() + public void IsValidScalarInputParameter_ITaskItemOfFileInfo_ReturnsTrue() { - Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(ITaskItem[]))); + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(ITaskItem))); } [Fact] - public void IsAssignableToITaskItem_ITaskItemOfT_ReturnsTrue() + public void IsValidScalarInputParameter_ITaskItemOfDirectoryInfo_ReturnsTrue() { - Assert.True(TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(ITaskItem))); + Assert.True(TaskParameterTypeVerifier.IsValidScalarInputParameter(typeof(ITaskItem))); } [Fact] - public void IsAssignableToITaskItem_ITaskItemOfTArray_ReturnsTrue() + public void IsValidVectorInputParameter_ITaskItemOfAbsolutePathArray_ReturnsTrue() { - Assert.True(TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(ITaskItem[]))); + Assert.True(TaskParameterTypeVerifier.IsValidVectorInputParameter(typeof(ITaskItem[]))); } [Fact] - public void IsValidOutputParameter_ITaskItemOfT_ReturnsTrue() + public void IsAssignableToITaskItem_ITaskItemOfAbsolutePath_ReturnsTrue() { - Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem))); + Assert.True(TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(ITaskItem))); } [Fact] - public void IsValidOutputParameter_ITaskItemOfTArray_ReturnsTrue() + public void IsAssignableToITaskItem_ITaskItemOfAbsolutePathArray_ReturnsTrue() { - Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem[]))); + Assert.True(TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(ITaskItem[]))); } [Fact] - public void IsAssignableToITaskItem_TaskItemOfTArray_ReturnsTrue() + public void IsValidOutputParameter_ITaskItemOfAbsolutePath_ReturnsTrue() { - typeof(ITaskItem[]).IsAssignableFrom(typeof(TaskItem[])).ShouldBeFalse(); - TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(TaskItem[])).ShouldBeTrue(); + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem))); } [Fact] - public void IsValidOutputParameter_TaskItemOfTArray_ReturnsTrue() + public void IsValidOutputParameter_ITaskItemOfAbsolutePathArray_ReturnsTrue() { - TaskParameterTypeVerifier.IsValidOutputParameter(typeof(TaskItem[])).ShouldBeTrue(); + Assert.True(TaskParameterTypeVerifier.IsValidOutputParameter(typeof(ITaskItem[]))); + } + + [Fact] + public void IsAssignableToITaskItem_TaskItemOfAbsolutePathArray_ReturnsTrue() + { + typeof(ITaskItem[]).IsAssignableFrom(typeof(TaskItem[])).ShouldBeFalse(); + TaskParameterTypeVerifier.IsAssignableToITaskItem(typeof(TaskItem[])).ShouldBeTrue(); + } + + [Fact] + public void IsValidOutputParameter_TaskItemOfAbsolutePathArray_ReturnsTrue() + { + TaskParameterTypeVerifier.IsValidOutputParameter(typeof(TaskItem[])).ShouldBeTrue(); } #endregion diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index 37a0716f0b7..c12f7daf671 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -757,7 +757,7 @@ private void Cancel() #region Local Methods /// - /// Checks if a type is TaskItem<T> where T is a value type, FileInfo, or DirectoryInfo. + /// Checks if a type is TaskItem<T> or ITaskItem<T> where T is a path-like type (AbsolutePath, FileInfo, or DirectoryInfo). /// private static bool IsTaskItemOfT(Type parameterType) { @@ -779,7 +779,7 @@ private static bool IsTaskItemOfT(Type parameterType) } Type typeArg = genericArguments[0]; - return typeArg.GetTypeInfo().IsValueType || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); + return typeArg == typeof(AbsolutePath) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); } /// diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index aa474f1e8f6..a43980a8d80 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -15,7 +15,7 @@ namespace Microsoft.Build.BackEnd internal static class TaskParameterTypeVerifier { /// - /// Checks if a type is ITaskItem<T> where T is a value type. + /// Checks if a type is ITaskItem<T> where T is a path-like type (AbsolutePath, FileInfo, or DirectoryInfo). /// private static bool IsTaskItemOfT(Type parameterType) { @@ -37,7 +37,7 @@ private static bool IsTaskItemOfT(Type parameterType) } Type typeArg = genericArguments[0]; - return typeArg.IsValueType || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); + return typeArg == typeof(AbsolutePath) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); } /// From 11b2648b1165c5dd5cfc3b3f9aa228ad6cd5af95 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 15:12:54 -0500 Subject: [PATCH 13/27] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- documentation/wiki/Tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation/wiki/Tasks.md b/documentation/wiki/Tasks.md index 66e5b15f556..178e7100662 100644 --- a/documentation/wiki/Tasks.md +++ b/documentation/wiki/Tasks.md @@ -14,7 +14,7 @@ A task is a class implementing [`ITask`](https://github.com/dotnet/msbuild/blob/ - **Numeric value types**: `int`, `long`, `short`, `byte`, `uint`, `ulong`, `ushort`, `sbyte`, `double`, `float`, `decimal`, and their array equivalents - **Other value types**: `char`, `DateTime`, and their array equivalents - **Item types**: `ITaskItem` (representation of a file system object with metadata), `ITaskItem[]` - - **Strongly-typed items**: `ITaskItem` where `T` is a value type, `FileInfo`, or `DirectoryInfo` (e.g., `ITaskItem`, `ITaskItem`), and their array equivalents + - **Strongly-typed items**: `ITaskItem` where `T` is `AbsolutePath`, `FileInfo`, or `DirectoryInfo` (e.g., `ITaskItem`, `ITaskItem`), and their array equivalents - **Path types**: `AbsolutePath`, `AbsolutePath[]`, `FileInfo`, `FileInfo[]`, `DirectoryInfo`, `DirectoryInfo[]` - **Custom value types**: Any struct implementing `IConvertible` (for output parameters only) - The properties can have attributes `[Required]` which causes the engine to check that it has a value when the task is run and `[Output]` which exposes the property to be used again in XML From 7a77c339edab121a6512c57899832f2d7e6cd07f Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 15:13:15 -0500 Subject: [PATCH 14/27] Use existing boolean conversion helpers instead of reimplementing Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/Shared/ValueTypeParser.cs | 25 ++----------------------- 1 file changed, 2 insertions(+), 23 deletions(-) diff --git a/src/Shared/ValueTypeParser.cs b/src/Shared/ValueTypeParser.cs index 18e86394642..6cac1a1dd60 100644 --- a/src/Shared/ValueTypeParser.cs +++ b/src/Shared/ValueTypeParser.cs @@ -22,29 +22,8 @@ internal static class ValueTypeParser /// private static bool ParseBool(string value) { - // MSBuild boolean true values - if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "on", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "yes", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "!false", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "!off", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "!no", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - // MSBuild boolean false values - if (string.Equals(value, "false", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "off", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "no", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "!true", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "!on", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "!yes", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - throw new ArgumentException($"Cannot parse '{value}' as a boolean value."); + // Reuse MSBuild's canonical boolean parsing (true/false, on/off, yes/no, and '!' negation) + return ConversionUtilities.ConvertStringToBool(value); } /// From e150dd5f3d8641e4d1f8f583c829987742a11c62 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 15:13:42 -0500 Subject: [PATCH 15/27] Update docs to align with parsed value types Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- src/Framework/ITaskItem_T.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Framework/ITaskItem_T.cs b/src/Framework/ITaskItem_T.cs index e36d34176e1..ed27dec1b84 100644 --- a/src/Framework/ITaskItem_T.cs +++ b/src/Framework/ITaskItem_T.cs @@ -9,11 +9,11 @@ namespace Microsoft.Build.Framework /// A strongly-typed task item interface that wraps a value of type /// and provides access to it along with standard task item functionality. /// - /// The type of the value. Can be a value type, FileInfo, or DirectoryInfo. + /// The type of the value. Supported types are , , and . /// - /// This interface allows tasks to receive strongly-typed parameters while still working with MSBuild's item system. + /// This interface allows tasks to receive strongly-typed item parameters while still working with MSBuild's item system. /// The value is parsed from the item's identity (ItemSpec) using MSBuild's standard parsing conventions. - /// Supported types include primitive value types (int, bool, etc.), AbsolutePath, FileInfo, and DirectoryInfo. + /// /// public interface ITaskItem : ITaskItem2 { From 1ce47a997fc135d2366bb9bcf05a108f037769ec Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 15:19:48 -0500 Subject: [PATCH 16/27] Consolidate TaskItem helper logic in shared verifier Move TaskExecutionHost's duplicated path-like TaskItem/ITaskItem helper logic into TaskParameterTypeVerifier so type checks and typed item construction are centralized and reusable. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../TaskExecutionHost/TaskExecutionHost.cs | 65 ++++--------------- src/Shared/TaskParameterTypeVerifier.cs | 52 +++++++++++++-- 2 files changed, 56 insertions(+), 61 deletions(-) diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index c12f7daf671..06a583f5589 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -757,54 +757,11 @@ private void Cancel() #region Local Methods /// - /// Checks if a type is TaskItem<T> or ITaskItem<T> where T is a path-like type (AbsolutePath, FileInfo, or DirectoryInfo). + /// Checks if a type is TaskItem<T> or ITaskItem<T> where T is path-like. /// - private static bool IsTaskItemOfT(Type parameterType) - { - if (!parameterType.GetTypeInfo().IsGenericType) - { - return false; - } - - Type genericTypeDefinition = parameterType.GetGenericTypeDefinition(); - if (genericTypeDefinition != typeof(ITaskItem<>) && genericTypeDefinition != typeof(TaskItem<>)) - { - return false; - } - - Type[] genericArguments = parameterType.GetGenericArguments(); - if (genericArguments.Length != 1) - { - return false; - } - - Type typeArg = genericArguments[0]; - return typeArg == typeof(AbsolutePath) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); - } - - /// - /// Creates an instance of TaskItem<T> from an ITaskItem. - /// - private static object CreateTaskItemOfT(Type taskItemType, ITaskItem item) - { - // Get the T from TaskItem - Type[] genericArguments = taskItemType.GetGenericArguments(); - Type valueType = genericArguments[0]; - - // Create TaskItem using the constructor that takes ITaskItem - Type constructedType = typeof(TaskItem<>).MakeGenericType(valueType); - ConstructorInfo constructor = constructedType.GetConstructor(new[] { typeof(ITaskItem) }); - - try - { - return constructor.Invoke(new object[] { item }); - } - catch (TargetInvocationException e) when (e.InnerException is not null) - { - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw(); - throw; - } - } + private static bool IsPathLikeTaskItemOrITaskItemOfT(Type parameterType) + => TaskParameterTypeVerifier.IsPathLikeITaskItemOfT(parameterType) + || TaskParameterTypeVerifier.IsPathLikeTaskItemOfT(parameterType, typeof(TaskItem<>).FullName); /// /// Called on the local side. @@ -858,7 +815,7 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I Type elementType = parameterType.GetElementType(); - if (parameterType != typeof(ITaskItem[]) && !IsTaskItemOfT(elementType)) + if (parameterType != typeof(ITaskItem[]) && !IsPathLikeTaskItemOrITaskItemOfT(elementType)) { foreach (TaskItem item in taskItems) { @@ -891,14 +848,14 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I } } } - else if (IsTaskItemOfT(elementType)) + else if (IsPathLikeTaskItemOrITaskItemOfT(elementType)) { // Handle TaskItem[] foreach (TaskItem item in taskItems) { currentItem = item; RecordItemForDisconnectIfNecessary(item); - object taskItemOfT = CreateTaskItemOfT(elementType, item); + object taskItemOfT = TaskParameterTypeVerifier.CreateTaskItemOfT(elementType, item, typeof(TaskItem<>)); finalTaskInputs.Add(taskItemOfT); } } @@ -968,7 +925,7 @@ private ITaskItem[] GetItemOutputs(TaskPropertyInfo parameter) if (outputType.IsArray) { Type elementType = outputType.GetElementType(); - if (IsTaskItemOfT(elementType)) + if (IsPathLikeTaskItemOrITaskItemOfT(elementType)) { // Convert TaskItem[] to ITaskItem[] Array taskItemArray = (Array)outputs; @@ -1362,7 +1319,7 @@ private bool InitializeTaskScalarParameter( try { - if (parameterType == typeof(ITaskItem) || IsTaskItemOfT(parameterType)) + if (parameterType == typeof(ITaskItem) || IsPathLikeTaskItemOrITaskItemOfT(parameterType)) { // We don't know how many items we're going to end up with, but we'll // keep adding them to this arraylist as we find them. @@ -1390,10 +1347,10 @@ private bool InitializeTaskScalarParameter( RecordItemForDisconnectIfNecessary(finalTaskItems[0]); - if (IsTaskItemOfT(parameterType)) + if (IsPathLikeTaskItemOrITaskItemOfT(parameterType)) { // Create TaskItem from ITaskItem - object taskItemOfT = CreateTaskItemOfT(parameterType, finalTaskItems[0]); + object taskItemOfT = TaskParameterTypeVerifier.CreateTaskItemOfT(parameterType, finalTaskItems[0], typeof(TaskItem<>)); success = InternalSetTaskParameter(parameter, taskItemOfT); } else diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index a43980a8d80..7c1ae9f6873 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -15,9 +15,10 @@ namespace Microsoft.Build.BackEnd internal static class TaskParameterTypeVerifier { /// - /// Checks if a type is ITaskItem<T> where T is a path-like type (AbsolutePath, FileInfo, or DirectoryInfo). + /// Checks if a type is the provided generic TaskItem type where T is a path-like type + /// (AbsolutePath, FileInfo, or DirectoryInfo). /// - private static bool IsTaskItemOfT(Type parameterType) + internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTaskItemTypeDefinitionFullName) { if (!parameterType.IsGenericType) { @@ -25,7 +26,7 @@ private static bool IsTaskItemOfT(Type parameterType) } Type genericTypeDefinition = parameterType.GetGenericTypeDefinition(); - if (genericTypeDefinition != typeof(ITaskItem<>)) + if (!string.Equals(genericTypeDefinition.FullName, genericTaskItemTypeDefinitionFullName, StringComparison.Ordinal)) { return false; } @@ -40,6 +41,43 @@ private static bool IsTaskItemOfT(Type parameterType) return typeArg == typeof(AbsolutePath) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); } + /// + /// Checks if a type is ITaskItem<T> where T is path-like. + /// + internal static bool IsPathLikeITaskItemOfT(Type parameterType) + => IsPathLikeTaskItemOfT(parameterType, typeof(ITaskItem<>).FullName); + + /// + /// Creates an instance of TaskItem<T> (or a provided TaskItem implementation for ITaskItem<T>) + /// from an . + /// + internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type taskItemImplementationGenericType) + { + // Get the T from TaskItem / ITaskItem. + Type[] genericArguments = taskItemType.GetGenericArguments(); + Type valueType = genericArguments[0]; + + Type genericTypeDefinition = taskItemType.GetGenericTypeDefinition(); + Type constructedType = genericTypeDefinition == typeof(ITaskItem<>) + ? taskItemImplementationGenericType.MakeGenericType(valueType) + : genericTypeDefinition.MakeGenericType(valueType); + ConstructorInfo constructor = constructedType.GetConstructor(new[] { typeof(ITaskItem) }); + if (constructor is null) + { + throw new InvalidOperationException($"Type '{constructedType.FullName}' does not have a constructor that takes ITaskItem."); + } + + try + { + return constructor.Invoke(new object[] { item }); + } + catch (TargetInvocationException e) when (e.InnerException is not null) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw(); + throw; + } + } + /// /// Is the parameter type a valid scalar input value /// @@ -50,7 +88,7 @@ internal static bool IsValidScalarInputParameter(Type parameterType) => || parameterType == typeof(AbsolutePath) || parameterType == typeof(FileInfo) || parameterType == typeof(DirectoryInfo) - || IsTaskItemOfT(parameterType) + || IsPathLikeITaskItemOfT(parameterType) ; /// @@ -71,7 +109,7 @@ internal static bool IsValidVectorInputParameter(Type parameterType) || parameterType == typeof(AbsolutePath[]) || parameterType == typeof(FileInfo[]) || parameterType == typeof(DirectoryInfo[]) - || IsTaskItemOfT(elementType) + || IsPathLikeITaskItemOfT(elementType) ; return result; } @@ -95,11 +133,11 @@ internal static bool IsAssignableToITaskItem(Type parameterType) { if (parameterType.IsArray) { - result = IsTaskItemOfT(parameterType.GetElementType()); + result = IsPathLikeITaskItemOfT(parameterType.GetElementType()); } else { - result = IsTaskItemOfT(parameterType); + result = IsPathLikeITaskItemOfT(parameterType); } } From 3548eb0b49af2eabeaa8066faf60ea5aa34ce373 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 15:26:36 -0500 Subject: [PATCH 17/27] actually escape set value in wrapped ITaskItem --- src/Utilities/TaskItem_T.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Utilities/TaskItem_T.cs b/src/Utilities/TaskItem_T.cs index 6cd469000f5..046d7ed8afa 100644 --- a/src/Utilities/TaskItem_T.cs +++ b/src/Utilities/TaskItem_T.cs @@ -159,10 +159,8 @@ public void SetMetadataValueLiteral(string metadataName, string metadataValue) } else { - // For ITaskItem (non-ITaskItem2), we need to escape the value manually - // Since we don't have access to EscapingUtilities in Framework, we'll just set it directly - // This is acceptable because TaskItem is primarily used with ITaskItem2 implementations - _backingItem.SetMetadata(metadataName, metadataValue); + var escapedValue = EscapingUtilities.Escape(metadataValue); + _backingItem.SetMetadata(metadataName, escapedValue); } } From 316ee7056557b32552532890c2cd2ce42b73f1ec Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 15:33:11 -0500 Subject: [PATCH 18/27] fix potential nullrefs on uninitialized TaskItem structs. --- src/Framework/ITaskItem_T.cs | 1 - src/Utilities/TaskItem_T.cs | 26 +++++++++++++------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/Framework/ITaskItem_T.cs b/src/Framework/ITaskItem_T.cs index ed27dec1b84..8dbdb88282c 100644 --- a/src/Framework/ITaskItem_T.cs +++ b/src/Framework/ITaskItem_T.cs @@ -14,7 +14,6 @@ namespace Microsoft.Build.Framework /// This interface allows tasks to receive strongly-typed item parameters while still working with MSBuild's item system. /// The value is parsed from the item's identity (ItemSpec) using MSBuild's standard parsing conventions. /// - /// public interface ITaskItem : ITaskItem2 { /// diff --git a/src/Utilities/TaskItem_T.cs b/src/Utilities/TaskItem_T.cs index 046d7ed8afa..fbc4f0d6f10 100644 --- a/src/Utilities/TaskItem_T.cs +++ b/src/Utilities/TaskItem_T.cs @@ -25,7 +25,7 @@ namespace Microsoft.Build.Utilities /// public readonly struct TaskItem : ITaskItem, IEquatable> { - private readonly ITaskItem _backingItem; + private readonly ITaskItem? _backingItem; /// /// Gets the strongly-typed value parsed from the item's identity. @@ -103,42 +103,42 @@ private static string GetFullPathOrItemSpec(ITaskItem item, string itemSpec) #region ITaskItem Implementation /// - public string ItemSpec + public string? ItemSpec { - get => _backingItem.ItemSpec; + get => _backingItem?.ItemSpec; set => throw new NotSupportedException("TaskItem ItemSpec is read-only. Create a new instance to change the value."); } /// - public ICollection MetadataNames => _backingItem.MetadataNames; + public ICollection? MetadataNames => _backingItem?.MetadataNames; /// - public int MetadataCount => _backingItem.MetadataCount; + public int MetadataCount => _backingItem?.MetadataCount ?? 0; /// - public string GetMetadata(string metadataName) => _backingItem.GetMetadata(metadataName); + public string? GetMetadata(string metadataName) => _backingItem?.GetMetadata(metadataName); /// public void SetMetadata(string metadataName, string metadataValue) => - _backingItem.SetMetadata(metadataName, metadataValue); + _backingItem?.SetMetadata(metadataName, metadataValue); /// public void RemoveMetadata(string metadataName) => - _backingItem.RemoveMetadata(metadataName); + _backingItem?.RemoveMetadata(metadataName); /// public void CopyMetadataTo(ITaskItem destinationItem) => - _backingItem.CopyMetadataTo(destinationItem); + _backingItem?.CopyMetadataTo(destinationItem); /// - public IDictionary CloneCustomMetadata() => _backingItem.CloneCustomMetadata(); + public IDictionary? CloneCustomMetadata() => _backingItem?.CloneCustomMetadata(); #endregion #region ITaskItem2 Implementation /// - public string EvaluatedIncludeEscaped + public string? EvaluatedIncludeEscaped { get => (_backingItem as ITaskItem2)?.EvaluatedIncludeEscaped ?? ItemSpec; set => throw new NotSupportedException("TaskItem EvaluatedIncludeEscaped is read-only. Create a new instance to change the value."); @@ -157,10 +157,10 @@ public void SetMetadataValueLiteral(string metadataName, string metadataValue) { taskItem2.SetMetadataValueLiteral(metadataName, metadataValue); } - else + else if (_backingItem is ITaskItem taskItem) { var escapedValue = EscapingUtilities.Escape(metadataValue); - _backingItem.SetMetadata(metadataName, escapedValue); + taskItem.SetMetadata(metadataName, escapedValue); } } From aa28234bc2bde21de31341f8330df0263bfccaa7 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 15:43:56 -0500 Subject: [PATCH 19/27] Unify task parameter helper logic across hosts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Build/Microsoft.Build.csproj | 2 + src/MSBuild/MSBuild.csproj | 2 + src/MSBuildTaskHost/BackEnd/TaskParameter.cs | 25 +++--- .../BackEnd/TaskParameterTypeVerifier.cs | 76 ++++++++++++++++--- src/MSBuildTaskHost/MSBuildTaskHost.csproj | 9 +++ src/Shared/TaskItemTypeHelper.cs | 65 ++++++++++++++++ src/Shared/TaskParameter.cs | 8 +- src/Shared/TaskParameterTypeVerifier.cs | 51 +------------ .../TaskParameterValueStringConverter.cs | 38 ++++++++++ src/Tasks/Microsoft.Build.Tasks.csproj | 2 + 10 files changed, 207 insertions(+), 71 deletions(-) create mode 100644 src/Shared/TaskItemTypeHelper.cs create mode 100644 src/Shared/TaskParameterValueStringConverter.cs diff --git a/src/Build/Microsoft.Build.csproj b/src/Build/Microsoft.Build.csproj index 4d4e9b54214..18a471e2080 100644 --- a/src/Build/Microsoft.Build.csproj +++ b/src/Build/Microsoft.Build.csproj @@ -139,6 +139,8 @@ BackEnd\Components\RequestBuilder\IntrinsicTasks\TaskLoggingHelperExtension.cs + + diff --git a/src/MSBuild/MSBuild.csproj b/src/MSBuild/MSBuild.csproj index ffdf75bf407..afa81ad3b10 100644 --- a/src/MSBuild/MSBuild.csproj +++ b/src/MSBuild/MSBuild.csproj @@ -84,6 +84,8 @@ + + diff --git a/src/MSBuildTaskHost/BackEnd/TaskParameter.cs b/src/MSBuildTaskHost/BackEnd/TaskParameter.cs index cae9c289530..4e03e9d4126 100644 --- a/src/MSBuildTaskHost/BackEnd/TaskParameter.cs +++ b/src/MSBuildTaskHost/BackEnd/TaskParameter.cs @@ -5,8 +5,10 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; +using System.IO; using System.Security; using Microsoft.Build.Framework; +using Microsoft.Build.Shared; using Microsoft.Build.TaskHost.Resources; using Microsoft.Build.TaskHost.Utilities; @@ -33,12 +35,14 @@ internal enum TaskParameterType PrimitiveTypeArray, /// - /// Parameter is a value type. Note: Must be . + /// Parameter is a non-primitive value serialized as a string (for example a value type + /// such as , or /). /// ValueType, /// - /// Parameter is an array of value types. Note: Must be . + /// Parameter is an array of non-primitive values serialized as strings (for example an array + /// of value types, or []/[]). /// ValueTypeArray, @@ -129,7 +133,9 @@ public TaskParameter(object? wrappedParameter) _wrappedParameter = taskItemArrayParameter; } - else if (wrappedParameterType.GetElementType().IsValueType) + else if (wrappedParameterType.GetElementType().IsValueType + || wrappedParameterType.GetElementType() == typeof(FileInfo) + || wrappedParameterType.GetElementType() == typeof(DirectoryInfo)) { _parameterType = TaskParameterType.ValueTypeArray; _wrappedParameter = wrappedParameter; @@ -164,7 +170,9 @@ public TaskParameter(object? wrappedParameter) _parameterType = TaskParameterType.ITaskItem; _wrappedParameter = new TaskParameterTaskItem((ITaskItem)wrappedParameter); } - else if (wrappedParameterType.IsValueType) + else if (wrappedParameterType.IsValueType + || wrappedParameterType == typeof(FileInfo) + || wrappedParameterType == typeof(DirectoryInfo)) { _parameterType = TaskParameterType.ValueType; _wrappedParameter = wrappedParameter; @@ -452,9 +460,8 @@ private void TranslatePrimitiveTypeArray(ITranslator translator) /// Serializes or deserializes the value type instance wrapped by this . /// /// - /// The value type is converted to/from string using the class. Note that we require - /// task parameter types to be so this conversion is guaranteed to work for parameters - /// that have made it this far. + /// The value is converted to a string on the write side using , + /// the same canonical conversion used by the in-process engine for out-of-proc parity. /// private void TranslateValueType(ITranslator translator) { @@ -462,7 +469,7 @@ private void TranslateValueType(ITranslator translator) if (translator.Mode == TranslationDirection.WriteToStream) { - valueString = (string)Convert.ChangeType(_wrappedParameter, typeof(string), CultureInfo.InvariantCulture); + valueString = TaskParameterValueStringConverter.ToString(_wrappedParameter); } translator.Translate(ref valueString); @@ -493,7 +500,7 @@ private void TranslateValueTypeArray(ITranslator translator) for (int i = 0; i < length; i++) { - string? valueString = Convert.ToString(array.GetValue(i), CultureInfo.InvariantCulture); + string? valueString = TaskParameterValueStringConverter.ToString(array.GetValue(i)); translator.Translate(ref valueString); } } diff --git a/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs b/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs index 2c5c9989f09..8e96b9e92d3 100644 --- a/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs +++ b/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.IO; using Microsoft.Build.Framework; +using Microsoft.Build.Shared; namespace Microsoft.Build.TaskHost.BackEnd; @@ -11,35 +13,87 @@ namespace Microsoft.Build.TaskHost.BackEnd; /// internal static class TaskParameterTypeVerifier { + /// + /// Checks if a type is the provided generic TaskItem type where T is a path-like type. + /// + internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTaskItemTypeDefinitionFullName) + => TaskItemTypeHelper.IsPathLikeTaskItemOfT(parameterType, genericTaskItemTypeDefinitionFullName); + + /// + /// Checks if a type is ITaskItem<T> where T is path-like. + /// + internal static bool IsPathLikeITaskItemOfT(Type parameterType) + => TaskItemTypeHelper.IsPathLikeITaskItemOfT(parameterType); + /// /// Is the parameter type a valid scalar input value. /// internal static bool IsValidScalarInputParameter(Type parameterType) - => parameterType.IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem); + => parameterType.IsValueType || + parameterType == typeof(string) || + parameterType == typeof(ITaskItem) || + parameterType == typeof(AbsolutePath) || + parameterType == typeof(FileInfo) || + parameterType == typeof(DirectoryInfo) || + IsPathLikeITaskItemOfT(parameterType); /// /// Is the passed in parameterType a valid vector input parameter. /// internal static bool IsValidVectorInputParameter(Type parameterType) - => (parameterType.IsArray && parameterType.GetElementType().IsValueType) || - parameterType == typeof(string[]) || - parameterType == typeof(ITaskItem[]); + { + if (!parameterType.IsArray) + { + return false; + } + + Type elementType = parameterType.GetElementType(); + + return elementType.IsValueType || + parameterType == typeof(string[]) || + parameterType == typeof(ITaskItem[]) || + parameterType == typeof(AbsolutePath[]) || + parameterType == typeof(FileInfo[]) || + parameterType == typeof(DirectoryInfo[]) || + IsPathLikeITaskItemOfT(elementType); + } /// - /// Is the passed in value type assignable to an ITask or ITask[] object. + /// Is the passed in value type assignable to an ITaskItem or ITaskItem[] object. /// internal static bool IsAssignableToITask(Type parameterType) - => typeof(ITaskItem[]).IsAssignableFrom(parameterType) || // ITaskItem array or derived type, or - typeof(ITaskItem).IsAssignableFrom(parameterType); // ITaskItem or derived type + { + if (parameterType.IsArray && typeof(ITaskItem).IsAssignableFrom(parameterType.GetElementType())) + { + return true; + } + + bool result = typeof(ITaskItem[]).IsAssignableFrom(parameterType) || typeof(ITaskItem).IsAssignableFrom(parameterType); + + if (!result) + { + result = parameterType.IsArray + ? IsPathLikeITaskItemOfT(parameterType.GetElementType()) + : IsPathLikeITaskItemOfT(parameterType); + } + + return result; + } /// /// Is the passed parameter a valid value type output parameter. /// internal static bool IsValueTypeOutputParameter(Type parameterType) - => (parameterType.IsArray && parameterType.GetElementType().IsValueType) || // array of value types, or - parameterType == typeof(string[]) || // string array, or - parameterType.IsValueType || // value type, or - parameterType == typeof(string); // string + => (parameterType.IsArray && parameterType.GetElementType().IsValueType) || + parameterType == typeof(string[]) || + parameterType == typeof(AbsolutePath[]) || + parameterType == typeof(FileInfo[]) || + parameterType == typeof(DirectoryInfo[]) || + parameterType.IsValueType || + parameterType == typeof(string) || + parameterType == typeof(AbsolutePath) || + parameterType == typeof(FileInfo) || + parameterType == typeof(DirectoryInfo); /// /// Is the parameter type a valid scalar or value type input parameter. diff --git a/src/MSBuildTaskHost/MSBuildTaskHost.csproj b/src/MSBuildTaskHost/MSBuildTaskHost.csproj index 56f0e0b4b02..ec6211e1de2 100644 --- a/src/MSBuildTaskHost/MSBuildTaskHost.csproj +++ b/src/MSBuildTaskHost/MSBuildTaskHost.csproj @@ -49,6 +49,15 @@ + + + BackEnd\TaskItemTypeHelper.cs + + + BackEnd\TaskParameterValueStringConverter.cs + + + diff --git a/src/Shared/TaskItemTypeHelper.cs b/src/Shared/TaskItemTypeHelper.cs new file mode 100644 index 00000000000..8469a75d0e6 --- /dev/null +++ b/src/Shared/TaskItemTypeHelper.cs @@ -0,0 +1,65 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.IO; +using System.Reflection; +using Microsoft.Build.Framework; + +namespace Microsoft.Build.Shared +{ + internal static class TaskItemTypeHelper + { + internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTaskItemTypeDefinitionFullName) + { + if (!parameterType.IsGenericType) + { + return false; + } + + Type genericTypeDefinition = parameterType.GetGenericTypeDefinition(); + if (!string.Equals(genericTypeDefinition.FullName, genericTaskItemTypeDefinitionFullName, StringComparison.Ordinal)) + { + return false; + } + + Type[] genericArguments = parameterType.GetGenericArguments(); + if (genericArguments.Length != 1) + { + return false; + } + + Type typeArg = genericArguments[0]; + return typeArg == typeof(AbsolutePath) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); + } + + internal static bool IsPathLikeITaskItemOfT(Type parameterType) + => IsPathLikeTaskItemOfT(parameterType, typeof(ITaskItem<>).FullName ?? string.Empty); + + internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type taskItemImplementationGenericType) + { + Type[] genericArguments = taskItemType.GetGenericArguments(); + Type valueType = genericArguments[0]; + + Type genericTypeDefinition = taskItemType.GetGenericTypeDefinition(); + Type constructedType = genericTypeDefinition == typeof(ITaskItem<>) + ? taskItemImplementationGenericType.MakeGenericType(valueType) + : genericTypeDefinition.MakeGenericType(valueType); + ConstructorInfo? constructor = constructedType.GetConstructor(new[] { typeof(ITaskItem) }); + if (constructor == null) + { + throw new InvalidOperationException($"Type '{constructedType.FullName}' does not have a constructor that takes ITaskItem."); + } + + try + { + return constructor.Invoke(new object[] { item }); + } + catch (TargetInvocationException e) when (e.InnerException != null) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw(); + throw; + } + } + } +} diff --git a/src/Shared/TaskParameter.cs b/src/Shared/TaskParameter.cs index 5db7716dac5..68864b2ff5b 100644 --- a/src/Shared/TaskParameter.cs +++ b/src/Shared/TaskParameter.cs @@ -479,7 +479,7 @@ private void TranslatePrimitiveTypeArray(ITranslator translator) /// Serializes or deserializes the value instance wrapped by this . /// /// - /// The value is converted to a string on the write side using , + /// The value is converted to a string on the write side using , /// the same canonical conversion the in-process engine uses when gathering task outputs /// (see TaskExecutionHost.GetValueOutputs). This guarantees identical string output across the /// in-process and out-of-process task host paths. The value is not converted back to its original @@ -491,7 +491,7 @@ private void TranslateValueType(ITranslator translator) string valueString = null; if (translator.Mode == TranslationDirection.WriteToStream) { - valueString = ValueTypeParser.ToString(_wrappedParameter); + valueString = TaskParameterValueStringConverter.ToString(_wrappedParameter); } translator.Translate(ref valueString); @@ -507,7 +507,7 @@ private void TranslateValueType(ITranslator translator) /// /// /// The array is assumed to be non-null. Each element is converted to a string on the write side - /// using , the same canonical conversion the in-process engine + /// using , the same canonical conversion the in-process engine /// uses when gathering task outputs. /// private void TranslateValueTypeArray(ITranslator translator) @@ -521,7 +521,7 @@ private void TranslateValueTypeArray(ITranslator translator) for (int i = 0; i < length; i++) { - string valueString = ValueTypeParser.ToString(array.GetValue(i)); + string valueString = TaskParameterValueStringConverter.ToString(array.GetValue(i)); translator.Translate(ref valueString); } } diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index 7c1ae9f6873..33bfadbccdb 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -4,6 +4,7 @@ using System; using System.IO; using Microsoft.Build.Framework; +using Microsoft.Build.Shared; #nullable disable @@ -19,64 +20,20 @@ internal static class TaskParameterTypeVerifier /// (AbsolutePath, FileInfo, or DirectoryInfo). /// internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTaskItemTypeDefinitionFullName) - { - if (!parameterType.IsGenericType) - { - return false; - } - - Type genericTypeDefinition = parameterType.GetGenericTypeDefinition(); - if (!string.Equals(genericTypeDefinition.FullName, genericTaskItemTypeDefinitionFullName, StringComparison.Ordinal)) - { - return false; - } - - Type[] genericArguments = parameterType.GetGenericArguments(); - if (genericArguments.Length != 1) - { - return false; - } - - Type typeArg = genericArguments[0]; - return typeArg == typeof(AbsolutePath) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); - } + => TaskItemTypeHelper.IsPathLikeTaskItemOfT(parameterType, genericTaskItemTypeDefinitionFullName); /// /// Checks if a type is ITaskItem<T> where T is path-like. /// internal static bool IsPathLikeITaskItemOfT(Type parameterType) - => IsPathLikeTaskItemOfT(parameterType, typeof(ITaskItem<>).FullName); + => TaskItemTypeHelper.IsPathLikeITaskItemOfT(parameterType); /// /// Creates an instance of TaskItem<T> (or a provided TaskItem implementation for ITaskItem<T>) /// from an . /// internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type taskItemImplementationGenericType) - { - // Get the T from TaskItem / ITaskItem. - Type[] genericArguments = taskItemType.GetGenericArguments(); - Type valueType = genericArguments[0]; - - Type genericTypeDefinition = taskItemType.GetGenericTypeDefinition(); - Type constructedType = genericTypeDefinition == typeof(ITaskItem<>) - ? taskItemImplementationGenericType.MakeGenericType(valueType) - : genericTypeDefinition.MakeGenericType(valueType); - ConstructorInfo constructor = constructedType.GetConstructor(new[] { typeof(ITaskItem) }); - if (constructor is null) - { - throw new InvalidOperationException($"Type '{constructedType.FullName}' does not have a constructor that takes ITaskItem."); - } - - try - { - return constructor.Invoke(new object[] { item }); - } - catch (TargetInvocationException e) when (e.InnerException is not null) - { - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw(); - throw; - } - } + => TaskItemTypeHelper.CreateTaskItemOfT(taskItemType, item, taskItemImplementationGenericType); /// /// Is the parameter type a valid scalar input value diff --git a/src/Shared/TaskParameterValueStringConverter.cs b/src/Shared/TaskParameterValueStringConverter.cs new file mode 100644 index 00000000000..ad69fa40af5 --- /dev/null +++ b/src/Shared/TaskParameterValueStringConverter.cs @@ -0,0 +1,38 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Globalization; +using System.IO; +using Microsoft.Build.Framework; + +namespace Microsoft.Build.Shared +{ + internal static class TaskParameterValueStringConverter + { + internal static string ToString(object value) + { + if (value == null) + { + return string.Empty; + } + + if (value is AbsolutePath absolutePath) + { + return absolutePath.Value ?? string.Empty; + } + + if (value is FileInfo fileInfo) + { + return fileInfo.FullName; + } + + if (value is DirectoryInfo directoryInfo) + { + return directoryInfo.FullName; + } + + return Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; + } + } +} diff --git a/src/Tasks/Microsoft.Build.Tasks.csproj b/src/Tasks/Microsoft.Build.Tasks.csproj index efb9ec991d7..5f6de9ff058 100644 --- a/src/Tasks/Microsoft.Build.Tasks.csproj +++ b/src/Tasks/Microsoft.Build.Tasks.csproj @@ -47,6 +47,8 @@ + + From 9603335424cba0cf2433d7e2b89af585aa67d01a Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Fri, 5 Jun 2026 16:22:29 -0500 Subject: [PATCH 20/27] Fix shared task-parameter helpers for TaskHost builds Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../BackEnd/TaskParameterTypeVerifier.cs | 4 ---- src/Shared/TaskItemTypeHelper.cs | 15 ++++++++----- .../TaskParameterValueStringConverter.cs | 21 +++++++++++++++---- 3 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs b/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs index 8e96b9e92d3..43925926087 100644 --- a/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs +++ b/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs @@ -32,7 +32,6 @@ internal static bool IsValidScalarInputParameter(Type parameterType) => parameterType.IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem) || - parameterType == typeof(AbsolutePath) || parameterType == typeof(FileInfo) || parameterType == typeof(DirectoryInfo) || IsPathLikeITaskItemOfT(parameterType); @@ -52,7 +51,6 @@ internal static bool IsValidVectorInputParameter(Type parameterType) return elementType.IsValueType || parameterType == typeof(string[]) || parameterType == typeof(ITaskItem[]) || - parameterType == typeof(AbsolutePath[]) || parameterType == typeof(FileInfo[]) || parameterType == typeof(DirectoryInfo[]) || IsPathLikeITaskItemOfT(elementType); @@ -86,12 +84,10 @@ internal static bool IsAssignableToITask(Type parameterType) internal static bool IsValueTypeOutputParameter(Type parameterType) => (parameterType.IsArray && parameterType.GetElementType().IsValueType) || parameterType == typeof(string[]) || - parameterType == typeof(AbsolutePath[]) || parameterType == typeof(FileInfo[]) || parameterType == typeof(DirectoryInfo[]) || parameterType.IsValueType || parameterType == typeof(string) || - parameterType == typeof(AbsolutePath) || parameterType == typeof(FileInfo) || parameterType == typeof(DirectoryInfo); diff --git a/src/Shared/TaskItemTypeHelper.cs b/src/Shared/TaskItemTypeHelper.cs index 8469a75d0e6..89b30db47fc 100644 --- a/src/Shared/TaskItemTypeHelper.cs +++ b/src/Shared/TaskItemTypeHelper.cs @@ -10,6 +10,12 @@ namespace Microsoft.Build.Shared { internal static class TaskItemTypeHelper { + private const string AbsolutePathFullName = "Microsoft.Build.Framework.AbsolutePath"; + private const string GenericITaskItemFullName = "Microsoft.Build.Framework.ITaskItem`1"; + + internal static bool IsAbsolutePathType(Type type) + => string.Equals(type.FullName, AbsolutePathFullName, StringComparison.Ordinal); + internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTaskItemTypeDefinitionFullName) { if (!parameterType.IsGenericType) @@ -30,11 +36,11 @@ internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTas } Type typeArg = genericArguments[0]; - return typeArg == typeof(AbsolutePath) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); + return IsAbsolutePathType(typeArg) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); } internal static bool IsPathLikeITaskItemOfT(Type parameterType) - => IsPathLikeTaskItemOfT(parameterType, typeof(ITaskItem<>).FullName ?? string.Empty); + => IsPathLikeTaskItemOfT(parameterType, GenericITaskItemFullName); internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type taskItemImplementationGenericType) { @@ -42,7 +48,7 @@ internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type Type valueType = genericArguments[0]; Type genericTypeDefinition = taskItemType.GetGenericTypeDefinition(); - Type constructedType = genericTypeDefinition == typeof(ITaskItem<>) + Type constructedType = string.Equals(genericTypeDefinition.FullName, GenericITaskItemFullName, StringComparison.Ordinal) ? taskItemImplementationGenericType.MakeGenericType(valueType) : genericTypeDefinition.MakeGenericType(valueType); ConstructorInfo? constructor = constructedType.GetConstructor(new[] { typeof(ITaskItem) }); @@ -57,8 +63,7 @@ internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type } catch (TargetInvocationException e) when (e.InnerException != null) { - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw(); - throw; + throw e.InnerException; } } } diff --git a/src/Shared/TaskParameterValueStringConverter.cs b/src/Shared/TaskParameterValueStringConverter.cs index ad69fa40af5..79632c824ec 100644 --- a/src/Shared/TaskParameterValueStringConverter.cs +++ b/src/Shared/TaskParameterValueStringConverter.cs @@ -4,22 +4,21 @@ using System; using System.Globalization; using System.IO; -using Microsoft.Build.Framework; namespace Microsoft.Build.Shared { internal static class TaskParameterValueStringConverter { - internal static string ToString(object value) + internal static string ToString(object? value) { if (value == null) { return string.Empty; } - if (value is AbsolutePath absolutePath) + if (TryGetAbsolutePathValue(value, out string absolutePathValue)) { - return absolutePath.Value ?? string.Empty; + return absolutePathValue; } if (value is FileInfo fileInfo) @@ -34,5 +33,19 @@ internal static string ToString(object value) return Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; } + + private static bool TryGetAbsolutePathValue(object value, out string absolutePathValue) + { + absolutePathValue = string.Empty; + + if (!TaskItemTypeHelper.IsAbsolutePathType(value.GetType())) + { + return false; + } + + object? rawValue = value.GetType().GetProperty("Value")?.GetValue(value, null); + absolutePathValue = rawValue as string ?? string.Empty; + return true; + } } } From ab16052957c8248790f213d594a827273039dff1 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Wed, 17 Jun 2026 13:04:26 -0500 Subject: [PATCH 21/27] Address Rainer and Jan review feedback - Rename ITaskItem_T.cs to ITaskItem`1.cs; file-scoped namespace - Move ValueTypeParser into Framework - Revert net35 task-host typed-parameter support - Refactor TaskParameterTypeVerifier with s_supportedTypes switch - Remove reflection in TaskParameterValueStringConverter - Consolidate string-to-value conversion via ConvertStringToParameterValue - Flatten GetItemOutputs with early returns - Rename TaskItemTypeHelper to TaskItemTypeDetector - Remove low-value comments; trim docs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- documentation/wiki/Tasks.md | 5 +- .../TaskExecutionHost/TaskExecutionHost.cs | 114 ++++++------------ src/Build/Microsoft.Build.csproj | 2 +- src/Framework/ITaskItem_T.cs | 24 ---- src/Framework/ITaskItem`1.cs | 23 ++++ .../Microsoft.Build.Framework.csproj | 3 - src/{Shared => Framework}/ValueTypeParser.cs | 0 src/MSBuild/MSBuild.csproj | 2 +- src/MSBuildTaskHost/BackEnd/TaskParameter.cs | 25 ++-- .../BackEnd/TaskParameterTypeVerifier.cs | 72 ++--------- src/MSBuildTaskHost/MSBuildTaskHost.csproj | 9 -- ...mTypeHelper.cs => TaskItemTypeDetector.cs} | 2 +- src/Shared/TaskParameterTypeVerifier.cs | 63 +++++----- .../TaskParameterValueStringConverter.cs | 19 +-- src/Tasks/Microsoft.Build.Tasks.csproj | 2 +- 15 files changed, 120 insertions(+), 245 deletions(-) delete mode 100644 src/Framework/ITaskItem_T.cs create mode 100644 src/Framework/ITaskItem`1.cs rename src/{Shared => Framework}/ValueTypeParser.cs (100%) rename src/Shared/{TaskItemTypeHelper.cs => TaskItemTypeDetector.cs} (98%) diff --git a/documentation/wiki/Tasks.md b/documentation/wiki/Tasks.md index 178e7100662..9dbf25ef20a 100644 --- a/documentation/wiki/Tasks.md +++ b/documentation/wiki/Tasks.md @@ -11,12 +11,11 @@ A task is a class implementing [`ITask`](https://github.com/dotnet/msbuild/blob/ - These properties can be: - **String types**: `string`, `string[]` - **Boolean types**: `bool`, `bool[]` - - **Numeric value types**: `int`, `long`, `short`, `byte`, `uint`, `ulong`, `ushort`, `sbyte`, `double`, `float`, `decimal`, and their array equivalents - - **Other value types**: `char`, `DateTime`, and their array equivalents - **Item types**: `ITaskItem` (representation of a file system object with metadata), `ITaskItem[]` - **Strongly-typed items**: `ITaskItem` where `T` is `AbsolutePath`, `FileInfo`, or `DirectoryInfo` (e.g., `ITaskItem`, `ITaskItem`), and their array equivalents - **Path types**: `AbsolutePath`, `AbsolutePath[]`, `FileInfo`, `FileInfo[]`, `DirectoryInfo`, `DirectoryInfo[]` - - **Custom value types**: Any struct implementing `IConvertible` (for output parameters only) + + > The engine also accepts arbitrary value types (such as `int`, `DateTime`, or any custom struct) by converting to/from their string representation, but using them is discouraged. Prefer the documented types above. - The properties can have attributes `[Required]` which causes the engine to check that it has a value when the task is run and `[Output]` which exposes the property to be used again in XML - Tasks have the `Log` property set by the engine to log messages/errors/warnings. diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index 06a583f5589..ed2e9343156 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -5,7 +5,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -776,29 +775,33 @@ private bool SetTaskItemParameter(TaskPropertyInfo parameter, ITaskItem item) /// private bool SetValueParameter(TaskPropertyInfo parameter, Type parameterType, string expandedParameterValue) { - // Special handling for AbsolutePath to use TaskEnvironment for proper path resolution - if (parameterType == typeof(AbsolutePath)) + return InternalSetTaskParameter(parameter, ConvertStringToParameterValue(expandedParameterValue, parameterType)); + } + + /// + /// Converts a single string value to an instance of , applying the same + /// conversions for both scalar parameters and the elements of array parameters. + /// + private object ConvertStringToParameterValue(string value, Type targetType) + { + // Path-like types are resolved through TaskEnvironment so the path is rooted consistently + // with the rest of the build before being handed to the task. + if (targetType == typeof(AbsolutePath)) { - return InternalSetTaskParameter(parameter, TaskEnvironment.GetAbsolutePath(expandedParameterValue)); + return TaskEnvironment.GetAbsolutePath(value); } - // Special handling for FileInfo - validate path through AbsolutePath first - if (parameterType == typeof(FileInfo)) + if (targetType == typeof(FileInfo)) { - AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(expandedParameterValue); - return InternalSetTaskParameter(parameter, new FileInfo(absolutePath.Value)); + return new FileInfo(TaskEnvironment.GetAbsolutePath(value).Value); } - // Special handling for DirectoryInfo - validate path through AbsolutePath first - if (parameterType == typeof(DirectoryInfo)) + if (targetType == typeof(DirectoryInfo)) { - AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(expandedParameterValue); - return InternalSetTaskParameter(parameter, new DirectoryInfo(absolutePath.Value)); + return new DirectoryInfo(TaskEnvironment.GetAbsolutePath(value).Value); } - // Use the unified ValueTypeParser for all other types - object parsedValue = ValueTypeParser.Parse(expandedParameterValue, parameterType); - return InternalSetTaskParameter(parameter, parsedValue); + return ValueTypeParser.Parse(value, targetType); } /// @@ -820,37 +823,11 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I foreach (TaskItem item in taskItems) { currentItem = item; - if (parameterType == typeof(string[])) - { - finalTaskInputs.Add(item.ItemSpec); - } - else if (parameterType == typeof(bool[])) - { - finalTaskInputs.Add(ConversionUtilities.ConvertStringToBool(item.ItemSpec)); - } - else if (parameterType == typeof(AbsolutePath[])) - { - finalTaskInputs.Add(TaskEnvironment.GetAbsolutePath(item.ItemSpec)); - } - else if (parameterType == typeof(FileInfo[])) - { - AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(item.ItemSpec); - finalTaskInputs.Add(new FileInfo(absolutePath.Value)); - } - else if (parameterType == typeof(DirectoryInfo[])) - { - AbsolutePath absolutePath = TaskEnvironment.GetAbsolutePath(item.ItemSpec); - finalTaskInputs.Add(new DirectoryInfo(absolutePath.Value)); - } - else - { - finalTaskInputs.Add(Convert.ChangeType(item.ItemSpec, elementType, CultureInfo.InvariantCulture)); - } + finalTaskInputs.Add(ConvertStringToParameterValue(item.ItemSpec, elementType)); } } else if (IsPathLikeTaskItemOrITaskItemOfT(elementType)) { - // Handle TaskItem[] foreach (TaskItem item in taskItems) { currentItem = item; @@ -861,7 +838,6 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I } else { - // Handle ITaskItem[] foreach (TaskItem item in taskItems) { // if we've been asked to remote these items then @@ -912,43 +888,30 @@ private ITaskItem[] GetItemOutputs(TaskPropertyInfo parameter) { object outputs = _taskFactoryWrapper.GetPropertyValue(TaskInstance, parameter); - if (!(outputs is ITaskItem[] taskItemOutputs)) + if (outputs is ITaskItem[] taskItemOutputs) { - if (outputs == null) - { - taskItemOutputs = null; - } - else + return taskItemOutputs; + } + + if (outputs == null) + { + return null; + } + + Type outputType = outputs.GetType(); + if (outputType.IsArray && IsPathLikeTaskItemOrITaskItemOfT(outputType.GetElementType())) + { + Array taskItemArray = (Array)outputs; + ITaskItem[] result = new ITaskItem[taskItemArray.Length]; + for (int i = 0; i < taskItemArray.Length; i++) { - // Check if it's a TaskItem or TaskItem[] - Type outputType = outputs.GetType(); - if (outputType.IsArray) - { - Type elementType = outputType.GetElementType(); - if (IsPathLikeTaskItemOrITaskItemOfT(elementType)) - { - // Convert TaskItem[] to ITaskItem[] - Array taskItemArray = (Array)outputs; - taskItemOutputs = new ITaskItem[taskItemArray.Length]; - for (int i = 0; i < taskItemArray.Length; i++) - { - taskItemOutputs[i] = (ITaskItem)taskItemArray.GetValue(i); - } - } - else - { - taskItemOutputs = [(ITaskItem)outputs]; - } - } - else - { - // Scalar value (including TaskItem) - taskItemOutputs = [(ITaskItem)outputs]; - } + result[i] = (ITaskItem)taskItemArray.GetValue(i); } + + return result; } - return taskItemOutputs; + return [(ITaskItem)outputs]; } /// @@ -971,7 +934,6 @@ private string[] GetValueOutputs(TaskPropertyInfo parameter) object output = convertibleOutputs.GetValue(i); if (output != null) { - // Use the unified ValueTypeParser for consistent formatting stringOutputs[i] = ValueTypeParser.ToString(output); } } diff --git a/src/Build/Microsoft.Build.csproj b/src/Build/Microsoft.Build.csproj index 18a471e2080..faa8ec52357 100644 --- a/src/Build/Microsoft.Build.csproj +++ b/src/Build/Microsoft.Build.csproj @@ -140,7 +140,7 @@ - + diff --git a/src/Framework/ITaskItem_T.cs b/src/Framework/ITaskItem_T.cs deleted file mode 100644 index 8dbdb88282c..00000000000 --- a/src/Framework/ITaskItem_T.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#nullable enable - -namespace Microsoft.Build.Framework -{ - /// - /// A strongly-typed task item interface that wraps a value of type - /// and provides access to it along with standard task item functionality. - /// - /// The type of the value. Supported types are , , and . - /// - /// This interface allows tasks to receive strongly-typed item parameters while still working with MSBuild's item system. - /// The value is parsed from the item's identity (ItemSpec) using MSBuild's standard parsing conventions. - /// - public interface ITaskItem : ITaskItem2 - { - /// - /// Gets the strongly-typed value parsed from the item's identity. - /// - T Value { get; } - } -} diff --git a/src/Framework/ITaskItem`1.cs b/src/Framework/ITaskItem`1.cs new file mode 100644 index 00000000000..32eed11567a --- /dev/null +++ b/src/Framework/ITaskItem`1.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable enable + +namespace Microsoft.Build.Framework; + +/// +/// A strongly-typed task item interface that wraps a value of type +/// and provides access to it along with standard task item functionality. +/// +/// The type of the value. Supported types are , , and . +/// +/// This interface allows tasks to receive strongly-typed item parameters while still working with MSBuild's item system. +/// The value is parsed from the item's identity (ItemSpec) using MSBuild's standard parsing conventions. +/// +public interface ITaskItem : ITaskItem2 +{ + /// + /// Gets the strongly-typed value parsed from the item's identity. + /// + T Value { get; } +} diff --git a/src/Framework/Microsoft.Build.Framework.csproj b/src/Framework/Microsoft.Build.Framework.csproj index bd63e72efce..dcb2abebb5b 100644 --- a/src/Framework/Microsoft.Build.Framework.csproj +++ b/src/Framework/Microsoft.Build.Framework.csproj @@ -65,9 +65,6 @@ - - Shared\ValueTypeParser.cs - diff --git a/src/Shared/ValueTypeParser.cs b/src/Framework/ValueTypeParser.cs similarity index 100% rename from src/Shared/ValueTypeParser.cs rename to src/Framework/ValueTypeParser.cs diff --git a/src/MSBuild/MSBuild.csproj b/src/MSBuild/MSBuild.csproj index afa81ad3b10..98f966c746e 100644 --- a/src/MSBuild/MSBuild.csproj +++ b/src/MSBuild/MSBuild.csproj @@ -85,7 +85,7 @@ - + diff --git a/src/MSBuildTaskHost/BackEnd/TaskParameter.cs b/src/MSBuildTaskHost/BackEnd/TaskParameter.cs index 4e03e9d4126..cae9c289530 100644 --- a/src/MSBuildTaskHost/BackEnd/TaskParameter.cs +++ b/src/MSBuildTaskHost/BackEnd/TaskParameter.cs @@ -5,10 +5,8 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Security; using Microsoft.Build.Framework; -using Microsoft.Build.Shared; using Microsoft.Build.TaskHost.Resources; using Microsoft.Build.TaskHost.Utilities; @@ -35,14 +33,12 @@ internal enum TaskParameterType PrimitiveTypeArray, /// - /// Parameter is a non-primitive value serialized as a string (for example a value type - /// such as , or /). + /// Parameter is a value type. Note: Must be . /// ValueType, /// - /// Parameter is an array of non-primitive values serialized as strings (for example an array - /// of value types, or []/[]). + /// Parameter is an array of value types. Note: Must be . /// ValueTypeArray, @@ -133,9 +129,7 @@ public TaskParameter(object? wrappedParameter) _wrappedParameter = taskItemArrayParameter; } - else if (wrappedParameterType.GetElementType().IsValueType - || wrappedParameterType.GetElementType() == typeof(FileInfo) - || wrappedParameterType.GetElementType() == typeof(DirectoryInfo)) + else if (wrappedParameterType.GetElementType().IsValueType) { _parameterType = TaskParameterType.ValueTypeArray; _wrappedParameter = wrappedParameter; @@ -170,9 +164,7 @@ public TaskParameter(object? wrappedParameter) _parameterType = TaskParameterType.ITaskItem; _wrappedParameter = new TaskParameterTaskItem((ITaskItem)wrappedParameter); } - else if (wrappedParameterType.IsValueType - || wrappedParameterType == typeof(FileInfo) - || wrappedParameterType == typeof(DirectoryInfo)) + else if (wrappedParameterType.IsValueType) { _parameterType = TaskParameterType.ValueType; _wrappedParameter = wrappedParameter; @@ -460,8 +452,9 @@ private void TranslatePrimitiveTypeArray(ITranslator translator) /// Serializes or deserializes the value type instance wrapped by this . /// /// - /// The value is converted to a string on the write side using , - /// the same canonical conversion used by the in-process engine for out-of-proc parity. + /// The value type is converted to/from string using the class. Note that we require + /// task parameter types to be so this conversion is guaranteed to work for parameters + /// that have made it this far. /// private void TranslateValueType(ITranslator translator) { @@ -469,7 +462,7 @@ private void TranslateValueType(ITranslator translator) if (translator.Mode == TranslationDirection.WriteToStream) { - valueString = TaskParameterValueStringConverter.ToString(_wrappedParameter); + valueString = (string)Convert.ChangeType(_wrappedParameter, typeof(string), CultureInfo.InvariantCulture); } translator.Translate(ref valueString); @@ -500,7 +493,7 @@ private void TranslateValueTypeArray(ITranslator translator) for (int i = 0; i < length; i++) { - string? valueString = TaskParameterValueStringConverter.ToString(array.GetValue(i)); + string? valueString = Convert.ToString(array.GetValue(i), CultureInfo.InvariantCulture); translator.Translate(ref valueString); } } diff --git a/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs b/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs index 43925926087..2c5c9989f09 100644 --- a/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs +++ b/src/MSBuildTaskHost/BackEnd/TaskParameterTypeVerifier.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.IO; using Microsoft.Build.Framework; -using Microsoft.Build.Shared; namespace Microsoft.Build.TaskHost.BackEnd; @@ -13,83 +11,35 @@ namespace Microsoft.Build.TaskHost.BackEnd; /// internal static class TaskParameterTypeVerifier { - /// - /// Checks if a type is the provided generic TaskItem type where T is a path-like type. - /// - internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTaskItemTypeDefinitionFullName) - => TaskItemTypeHelper.IsPathLikeTaskItemOfT(parameterType, genericTaskItemTypeDefinitionFullName); - - /// - /// Checks if a type is ITaskItem<T> where T is path-like. - /// - internal static bool IsPathLikeITaskItemOfT(Type parameterType) - => TaskItemTypeHelper.IsPathLikeITaskItemOfT(parameterType); - /// /// Is the parameter type a valid scalar input value. /// internal static bool IsValidScalarInputParameter(Type parameterType) - => parameterType.IsValueType || - parameterType == typeof(string) || - parameterType == typeof(ITaskItem) || - parameterType == typeof(FileInfo) || - parameterType == typeof(DirectoryInfo) || - IsPathLikeITaskItemOfT(parameterType); + => parameterType.IsValueType || parameterType == typeof(string) || parameterType == typeof(ITaskItem); /// /// Is the passed in parameterType a valid vector input parameter. /// internal static bool IsValidVectorInputParameter(Type parameterType) - { - if (!parameterType.IsArray) - { - return false; - } - - Type elementType = parameterType.GetElementType(); - - return elementType.IsValueType || - parameterType == typeof(string[]) || - parameterType == typeof(ITaskItem[]) || - parameterType == typeof(FileInfo[]) || - parameterType == typeof(DirectoryInfo[]) || - IsPathLikeITaskItemOfT(elementType); - } + => (parameterType.IsArray && parameterType.GetElementType().IsValueType) || + parameterType == typeof(string[]) || + parameterType == typeof(ITaskItem[]); /// - /// Is the passed in value type assignable to an ITaskItem or ITaskItem[] object. + /// Is the passed in value type assignable to an ITask or ITask[] object. /// internal static bool IsAssignableToITask(Type parameterType) - { - if (parameterType.IsArray && typeof(ITaskItem).IsAssignableFrom(parameterType.GetElementType())) - { - return true; - } - - bool result = typeof(ITaskItem[]).IsAssignableFrom(parameterType) || typeof(ITaskItem).IsAssignableFrom(parameterType); - - if (!result) - { - result = parameterType.IsArray - ? IsPathLikeITaskItemOfT(parameterType.GetElementType()) - : IsPathLikeITaskItemOfT(parameterType); - } - - return result; - } + => typeof(ITaskItem[]).IsAssignableFrom(parameterType) || // ITaskItem array or derived type, or + typeof(ITaskItem).IsAssignableFrom(parameterType); // ITaskItem or derived type /// /// Is the passed parameter a valid value type output parameter. /// internal static bool IsValueTypeOutputParameter(Type parameterType) - => (parameterType.IsArray && parameterType.GetElementType().IsValueType) || - parameterType == typeof(string[]) || - parameterType == typeof(FileInfo[]) || - parameterType == typeof(DirectoryInfo[]) || - parameterType.IsValueType || - parameterType == typeof(string) || - parameterType == typeof(FileInfo) || - parameterType == typeof(DirectoryInfo); + => (parameterType.IsArray && parameterType.GetElementType().IsValueType) || // array of value types, or + parameterType == typeof(string[]) || // string array, or + parameterType.IsValueType || // value type, or + parameterType == typeof(string); // string /// /// Is the parameter type a valid scalar or value type input parameter. diff --git a/src/MSBuildTaskHost/MSBuildTaskHost.csproj b/src/MSBuildTaskHost/MSBuildTaskHost.csproj index ec6211e1de2..56f0e0b4b02 100644 --- a/src/MSBuildTaskHost/MSBuildTaskHost.csproj +++ b/src/MSBuildTaskHost/MSBuildTaskHost.csproj @@ -49,15 +49,6 @@ - - - BackEnd\TaskItemTypeHelper.cs - - - BackEnd\TaskParameterValueStringConverter.cs - - - diff --git a/src/Shared/TaskItemTypeHelper.cs b/src/Shared/TaskItemTypeDetector.cs similarity index 98% rename from src/Shared/TaskItemTypeHelper.cs rename to src/Shared/TaskItemTypeDetector.cs index 89b30db47fc..a69dfa5481c 100644 --- a/src/Shared/TaskItemTypeHelper.cs +++ b/src/Shared/TaskItemTypeDetector.cs @@ -8,7 +8,7 @@ namespace Microsoft.Build.Shared { - internal static class TaskItemTypeHelper + internal static class TaskItemTypeDetector { private const string AbsolutePathFullName = "Microsoft.Build.Framework.AbsolutePath"; private const string GenericITaskItemFullName = "Microsoft.Build.Framework.ITaskItem`1"; diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index 33bfadbccdb..a9782d53037 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Collections.Generic; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Shared; @@ -15,38 +16,46 @@ namespace Microsoft.Build.BackEnd /// internal static class TaskParameterTypeVerifier { + /// + /// The non-value scalar types (and array element types) that MSBuild supports as task parameters + /// by converting them to/from their string representation. + /// + private static readonly HashSet s_supportedTypes = + [ + typeof(string), + typeof(AbsolutePath), + typeof(FileInfo), + typeof(DirectoryInfo), + ]; + /// /// Checks if a type is the provided generic TaskItem type where T is a path-like type /// (AbsolutePath, FileInfo, or DirectoryInfo). /// internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTaskItemTypeDefinitionFullName) - => TaskItemTypeHelper.IsPathLikeTaskItemOfT(parameterType, genericTaskItemTypeDefinitionFullName); + => TaskItemTypeDetector.IsPathLikeTaskItemOfT(parameterType, genericTaskItemTypeDefinitionFullName); /// /// Checks if a type is ITaskItem<T> where T is path-like. /// internal static bool IsPathLikeITaskItemOfT(Type parameterType) - => TaskItemTypeHelper.IsPathLikeITaskItemOfT(parameterType); + => TaskItemTypeDetector.IsPathLikeITaskItemOfT(parameterType); /// /// Creates an instance of TaskItem<T> (or a provided TaskItem implementation for ITaskItem<T>) /// from an . /// internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type taskItemImplementationGenericType) - => TaskItemTypeHelper.CreateTaskItemOfT(taskItemType, item, taskItemImplementationGenericType); + => TaskItemTypeDetector.CreateTaskItemOfT(taskItemType, item, taskItemImplementationGenericType); /// /// Is the parameter type a valid scalar input value /// internal static bool IsValidScalarInputParameter(Type parameterType) => parameterType.IsValueType || - parameterType == typeof(string) || - parameterType == typeof(ITaskItem) - || parameterType == typeof(AbsolutePath) - || parameterType == typeof(FileInfo) - || parameterType == typeof(DirectoryInfo) - || IsPathLikeITaskItemOfT(parameterType) - ; + parameterType == typeof(ITaskItem) || + s_supportedTypes.Contains(parameterType) || + IsPathLikeITaskItemOfT(parameterType); /// /// Is the passed in parameterType a valid vector input parameter @@ -60,15 +69,10 @@ internal static bool IsValidVectorInputParameter(Type parameterType) Type elementType = parameterType.GetElementType(); - bool result = elementType.IsValueType || - parameterType == typeof(string[]) || - parameterType == typeof(ITaskItem[]) - || parameterType == typeof(AbsolutePath[]) - || parameterType == typeof(FileInfo[]) - || parameterType == typeof(DirectoryInfo[]) - || IsPathLikeITaskItemOfT(elementType) - ; - return result; + return elementType.IsValueType || + parameterType == typeof(ITaskItem[]) || + s_supportedTypes.Contains(elementType) || + IsPathLikeITaskItemOfT(elementType); } /// @@ -105,20 +109,13 @@ internal static bool IsAssignableToITaskItem(Type parameterType) /// Is the passed parameter a valid value type output parameter /// internal static bool IsValueTypeOutputParameter(Type parameterType) - { - bool result = (parameterType.IsArray && parameterType.GetElementType().IsValueType) || /* array of value types, or */ - parameterType == typeof(string[]) || /* string array, or */ - parameterType == typeof(AbsolutePath[]) || /* AbsolutePath array, or */ - parameterType == typeof(FileInfo[]) || /* FileInfo array, or */ - parameterType == typeof(DirectoryInfo[]) || /* DirectoryInfo array, or */ - parameterType.IsValueType || /* value type, or */ - parameterType == typeof(string) /* string, or */ - || parameterType == typeof(AbsolutePath) /* AbsolutePath, or */ - || parameterType == typeof(FileInfo) /* FileInfo, or */ - || parameterType == typeof(DirectoryInfo) /* DirectoryInfo */ - ; - return result; - } + => parameterType switch + { + { IsValueType: true } => true, // value type + { IsArray: true } => parameterType.GetElementType() is { } element + && (element.IsValueType || s_supportedTypes.Contains(element)), // array of value type or supported type + _ => s_supportedTypes.Contains(parameterType), // supported scalar type + }; /// /// Is the parameter type a valid scalar or value type input parameter diff --git a/src/Shared/TaskParameterValueStringConverter.cs b/src/Shared/TaskParameterValueStringConverter.cs index 79632c824ec..02a66d9fecb 100644 --- a/src/Shared/TaskParameterValueStringConverter.cs +++ b/src/Shared/TaskParameterValueStringConverter.cs @@ -4,6 +4,7 @@ using System; using System.Globalization; using System.IO; +using Microsoft.Build.Framework; namespace Microsoft.Build.Shared { @@ -16,9 +17,9 @@ internal static string ToString(object? value) return string.Empty; } - if (TryGetAbsolutePathValue(value, out string absolutePathValue)) + if (value is AbsolutePath absolutePath) { - return absolutePathValue; + return absolutePath.Value ?? string.Empty; } if (value is FileInfo fileInfo) @@ -33,19 +34,5 @@ internal static string ToString(object? value) return Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; } - - private static bool TryGetAbsolutePathValue(object value, out string absolutePathValue) - { - absolutePathValue = string.Empty; - - if (!TaskItemTypeHelper.IsAbsolutePathType(value.GetType())) - { - return false; - } - - object? rawValue = value.GetType().GetProperty("Value")?.GetValue(value, null); - absolutePathValue = rawValue as string ?? string.Empty; - return true; - } } } diff --git a/src/Tasks/Microsoft.Build.Tasks.csproj b/src/Tasks/Microsoft.Build.Tasks.csproj index 5f6de9ff058..057ff755c2d 100644 --- a/src/Tasks/Microsoft.Build.Tasks.csproj +++ b/src/Tasks/Microsoft.Build.Tasks.csproj @@ -48,7 +48,7 @@ - + From 915167eb242b4678505d4899d63ad0287d2c914a Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Wed, 17 Jun 2026 14:15:28 -0500 Subject: [PATCH 22/27] Rip out abstracted reflection usage in TaskItem creation --- .../TaskExecutionHost/TaskExecutionHost.cs | 6 ++--- src/Shared/TaskItemTypeDetector.cs | 27 ------------------- src/Shared/TaskParameterTypeVerifier.cs | 7 ----- 3 files changed, 2 insertions(+), 38 deletions(-) diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index ed2e9343156..7e6370b73b0 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -832,7 +832,7 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I { currentItem = item; RecordItemForDisconnectIfNecessary(item); - object taskItemOfT = TaskParameterTypeVerifier.CreateTaskItemOfT(elementType, item, typeof(TaskItem<>)); + ITaskItem taskItemOfT = typeof(TaskItem<>).MakeGenericType(elementType).GetConstructor([typeof(ITaskItem)]).Invoke([item]) as ITaskItem; finalTaskInputs.Add(taskItemOfT); } } @@ -843,7 +843,6 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I // if we've been asked to remote these items then // remember them so we can disconnect them from remoting later RecordItemForDisconnectIfNecessary(item); - finalTaskInputs.Add(item); } } @@ -1311,8 +1310,7 @@ private bool InitializeTaskScalarParameter( if (IsPathLikeTaskItemOrITaskItemOfT(parameterType)) { - // Create TaskItem from ITaskItem - object taskItemOfT = TaskParameterTypeVerifier.CreateTaskItemOfT(parameterType, finalTaskItems[0], typeof(TaskItem<>)); + ITaskItem taskItemOfT = typeof(TaskItem<>).MakeGenericType(parameterType).GetConstructor(new[] { typeof(ITaskItem) }).Invoke([finalTaskItems[0]]) as ITaskItem; success = InternalSetTaskParameter(parameter, taskItemOfT); } else diff --git a/src/Shared/TaskItemTypeDetector.cs b/src/Shared/TaskItemTypeDetector.cs index a69dfa5481c..6ed349a6b72 100644 --- a/src/Shared/TaskItemTypeDetector.cs +++ b/src/Shared/TaskItemTypeDetector.cs @@ -3,8 +3,6 @@ using System; using System.IO; -using System.Reflection; -using Microsoft.Build.Framework; namespace Microsoft.Build.Shared { @@ -41,30 +39,5 @@ internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTas internal static bool IsPathLikeITaskItemOfT(Type parameterType) => IsPathLikeTaskItemOfT(parameterType, GenericITaskItemFullName); - - internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type taskItemImplementationGenericType) - { - Type[] genericArguments = taskItemType.GetGenericArguments(); - Type valueType = genericArguments[0]; - - Type genericTypeDefinition = taskItemType.GetGenericTypeDefinition(); - Type constructedType = string.Equals(genericTypeDefinition.FullName, GenericITaskItemFullName, StringComparison.Ordinal) - ? taskItemImplementationGenericType.MakeGenericType(valueType) - : genericTypeDefinition.MakeGenericType(valueType); - ConstructorInfo? constructor = constructedType.GetConstructor(new[] { typeof(ITaskItem) }); - if (constructor == null) - { - throw new InvalidOperationException($"Type '{constructedType.FullName}' does not have a constructor that takes ITaskItem."); - } - - try - { - return constructor.Invoke(new object[] { item }); - } - catch (TargetInvocationException e) when (e.InnerException != null) - { - throw e.InnerException; - } - } } } diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index a9782d53037..2cd5fe8d1f9 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -41,13 +41,6 @@ internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTas internal static bool IsPathLikeITaskItemOfT(Type parameterType) => TaskItemTypeDetector.IsPathLikeITaskItemOfT(parameterType); - /// - /// Creates an instance of TaskItem<T> (or a provided TaskItem implementation for ITaskItem<T>) - /// from an . - /// - internal static object CreateTaskItemOfT(Type taskItemType, ITaskItem item, Type taskItemImplementationGenericType) - => TaskItemTypeDetector.CreateTaskItemOfT(taskItemType, item, taskItemImplementationGenericType); - /// /// Is the parameter type a valid scalar input value /// From 865d6aa6cea158fc14be691ed9c14d1eafec54d9 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Wed, 17 Jun 2026 16:15:25 -0500 Subject: [PATCH 23/27] Fix TaskItem construction to use generic argument, not closed type The inlined reflection passed the closed TaskItem/ITaskItem type to MakeGenericType instead of its generic argument, producing TaskItem> instead of TaskItem. This broke TaskExecutionHost_Tests for path-like ITaskItem/TaskItem parameters with 'Cannot parse ... as type ITaskItem\1'. Extract GetGenericArguments()[0] before constructing the closed type. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index 7e6370b73b0..36f37c1b8fe 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -832,7 +832,7 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I { currentItem = item; RecordItemForDisconnectIfNecessary(item); - ITaskItem taskItemOfT = typeof(TaskItem<>).MakeGenericType(elementType).GetConstructor([typeof(ITaskItem)]).Invoke([item]) as ITaskItem; + ITaskItem taskItemOfT = typeof(TaskItem<>).MakeGenericType(elementType.GetGenericArguments()[0]).GetConstructor([typeof(ITaskItem)]).Invoke([item]) as ITaskItem; finalTaskInputs.Add(taskItemOfT); } } @@ -1310,7 +1310,7 @@ private bool InitializeTaskScalarParameter( if (IsPathLikeTaskItemOrITaskItemOfT(parameterType)) { - ITaskItem taskItemOfT = typeof(TaskItem<>).MakeGenericType(parameterType).GetConstructor(new[] { typeof(ITaskItem) }).Invoke([finalTaskItems[0]]) as ITaskItem; + ITaskItem taskItemOfT = typeof(TaskItem<>).MakeGenericType(parameterType.GetGenericArguments()[0]).GetConstructor(new[] { typeof(ITaskItem) }).Invoke([finalTaskItems[0]]) as ITaskItem; success = InternalSetTaskParameter(parameter, taskItemOfT); } else From 5888292924b62bddbc81486b32113e273095288d Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 18 Jun 2026 12:09:24 -0500 Subject: [PATCH 24/27] Add TestEnvironment.PublishTestFile for collecting CI artifacts Adds an opt-in TestEnvironment mechanism to publish files (e.g. binary logs from out-of-process MSBuild invocations) as CI build artifacts. On cleanup, registered files are copied into artifacts/log//TestArtifacts (already published by CI), attached to the xUnit result best-effort, and logged. Publication is failure-gated by default via xUnit v3 TestContext, with an 'always' override. Wires the BuildCheck binary-log EndToEndTests to register their binlogs so out-of-process failures are diagnosable in CI. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/BuildCheck.UnitTests/EndToEndTests.cs | 2 + .../ArtifactsLocationAttribute.cs | 9 +- .../Microsoft.Build.UnitTests.Shared.csproj | 1 + src/UnitTests.Shared/TestEnvironment.cs | 192 ++++++++++++++++++ 4 files changed, 203 insertions(+), 1 deletion(-) diff --git a/src/BuildCheck.UnitTests/EndToEndTests.cs b/src/BuildCheck.UnitTests/EndToEndTests.cs index ac262ae0f37..9d096607141 100644 --- a/src/BuildCheck.UnitTests/EndToEndTests.cs +++ b/src/BuildCheck.UnitTests/EndToEndTests.cs @@ -578,6 +578,7 @@ public void SampleCheckIntegrationTest_ReplayBinaryLogOfCheckedBuild(bool buildI var projectDirectory = Path.GetDirectoryName(projectFile.Path); string logFile = _env.ExpectFile(".binlog").Path; + _env.PublishTestFile(logFile); _ = RunnerUtilities.ExecBootstrapedMSBuild( $"{Path.GetFileName(projectFile.Path)} /m:1 -nr:False -restore {(checkRequested ? "-check" : string.Empty)} -bl:{logFile}", @@ -692,6 +693,7 @@ public void SampleCheckIntegrationTest_CheckOnBinaryLogReplay(bool buildInOutOfP string? projectDirectory = Path.GetDirectoryName(projectFile.Path); string logFile = _env.ExpectFile(".binlog").Path; + _env.PublishTestFile(logFile); _ = RunnerUtilities.ExecBootstrapedMSBuild( $"{Path.GetFileName(projectFile.Path)} /m:1 -nr:False -restore -bl:{logFile}", diff --git a/src/UnitTests.Shared/ArtifactsLocationAttribute.cs b/src/UnitTests.Shared/ArtifactsLocationAttribute.cs index 8aaeeeb85ea..9abbc29bc61 100644 --- a/src/UnitTests.Shared/ArtifactsLocationAttribute.cs +++ b/src/UnitTests.Shared/ArtifactsLocationAttribute.cs @@ -4,7 +4,14 @@ namespace Microsoft.Build.UnitTests.Shared; [System.AttributeUsage(System.AttributeTargets.Assembly)] -public sealed class ArtifactsLocationAttribute(string artifactsLocation) : System.Attribute +public sealed class ArtifactsLocationAttribute(string artifactsLocation, string? artifactsLogLocation = null) : System.Attribute { public string ArtifactsLocation { get; } = artifactsLocation; + + /// + /// The build's log output directory (artifacts/log/<Configuration>). This directory is published + /// as a build artifact by CI, so binary logs captured here for failing out-of-process MSBuild + /// invocations are automatically collected without any pipeline changes. + /// + public string? ArtifactsLogLocation { get; } = artifactsLogLocation; } diff --git a/src/UnitTests.Shared/Microsoft.Build.UnitTests.Shared.csproj b/src/UnitTests.Shared/Microsoft.Build.UnitTests.Shared.csproj index a10bd888634..6f43f823c3e 100644 --- a/src/UnitTests.Shared/Microsoft.Build.UnitTests.Shared.csproj +++ b/src/UnitTests.Shared/Microsoft.Build.UnitTests.Shared.csproj @@ -46,6 +46,7 @@ <_Parameter1>$(ArtifactsShippingPackagesDir) + <_Parameter2>$(ArtifactsLogDir) diff --git a/src/UnitTests.Shared/TestEnvironment.cs b/src/UnitTests.Shared/TestEnvironment.cs index d1b68e4de72..8bee052b1f8 100644 --- a/src/UnitTests.Shared/TestEnvironment.cs +++ b/src/UnitTests.Shared/TestEnvironment.cs @@ -43,6 +43,12 @@ public partial class TestEnvironment : IDisposable private bool _disposed; + /// + /// Files registered via to be collected as CI + /// build artifacts when the test completes. + /// + private readonly List<(string Path, bool Always)> _filesToPublish = new List<(string, bool)>(); + public TransientTestFolder DefaultTestDirectory => _defaultTestDirectory.Value; /// @@ -106,6 +112,10 @@ private void Cleanup() { _disposed = true; + // Publish registered files (e.g. binary logs) before reverting variants, which would + // otherwise delete the transient files/folders they live in. + PublishRegisteredFiles(); + // Reset test variants in reverse order to get back to original state. for (int i = _variants.Count - 1; i >= 0; i--) { @@ -124,6 +134,188 @@ private void Cleanup() } } + /// + /// Registers a file to be collected as a CI build artifact when the test completes. + /// + /// + /// + /// This is intended for diagnostics that are produced out-of-band — most notably binary logs + /// (-bl) emitted by out-of-process MSBuild invocations — which would otherwise be lost when + /// test cleanup deletes the transient files and folders they live in. + /// + /// + /// On cleanup the file is copied into the build's log output directory + /// (artifacts/log/<Configuration>/TestArtifacts). That directory is published as a build + /// artifact by CI, so registered files are collected automatically without any pipeline changes. The + /// file path is also written to the test output, and the file is attached to the xUnit test result on a + /// best-effort basis. + /// + /// + /// Typical usage is to point a binary log at a test-environment-unique path, run the build, and register + /// that path: + /// + /// string binlog = _env.ExpectFile(".binlog").Path; + /// _env.PublishTestFile(binlog); + /// RunnerUtilities.ExecBootstrapedMSBuild($"{project} -bl:{binlog}", out bool success); + /// + /// + /// + /// The absolute path of the file to publish. + /// + /// When (default), the file is only published if the test did not pass, keeping + /// artifacts from passing runs to a minimum. When , the file is published + /// regardless of the test outcome. + /// + public void PublishTestFile(string filePath, bool always = false) + { + if (string.IsNullOrEmpty(filePath)) + { + throw new ArgumentNullException(nameof(filePath)); + } + + _filesToPublish.Add((filePath, always)); + } + + /// + /// Copies and/or attaches files registered via so they are + /// collected as CI build artifacts. Invoked during cleanup before transient state is reverted. + /// + private void PublishRegisteredFiles() + { + if (_filesToPublish.Count == 0) + { + return; + } + + bool testPassed = DidCurrentTestPass(); + string destinationDirectory = ResolvePublishDirectory(); + string testNamePrefix = GetCurrentTestNamePrefix(); + + foreach ((string path, bool always) in _filesToPublish) + { + try + { + if (!always && testPassed) + { + continue; + } + + if (!File.Exists(path)) + { + Output?.WriteLine($"[PublishTestFile] Skipping '{path}' because it does not exist."); + continue; + } + + if (string.IsNullOrEmpty(destinationDirectory)) + { + Output?.WriteLine($"[PublishTestFile] No artifacts log directory is available; '{path}' was not published."); + } + else + { + Directory.CreateDirectory(destinationDirectory); + string destination = GetUniqueDestinationPath(destinationDirectory, testNamePrefix + Path.GetFileName(path)); + File.Copy(path, destination, overwrite: true); + Output?.WriteLine($"[PublishTestFile] Published '{path}' to '{destination}'."); + } + + TryAttachToTestResult(path); + } + catch (Exception e) + { + Output?.WriteLine($"[PublishTestFile] Failed to publish '{path}': {e}"); + } + } + } + + /// + /// The directory into which published files are copied. This lives under the build's log output + /// directory, which CI publishes as a build artifact. Returns if the location is + /// unknown (for example, when running outside the build). + /// + private static string ResolvePublishDirectory() + { + string logDirectory = RunnerUtilities.ArtifactsLocationAttribute?.ArtifactsLogLocation; + return string.IsNullOrEmpty(logDirectory) ? null : Path.Combine(logDirectory, "TestArtifacts"); + } + + /// + /// Returns only when the current test is known to have passed. Any other state + /// (failed, skipped, unknown, or not running under xUnit) returns so that + /// diagnostics are preserved by default. + /// + private static bool DidCurrentTestPass() + { + try + { + return Xunit.TestContext.Current?.TestState?.Result == Xunit.TestResult.Passed; + } + catch + { + return false; + } + } + + /// + /// Returns a sanitized, file-name-safe prefix derived from the current test method name, or an empty + /// string if it cannot be determined. + /// + private static string GetCurrentTestNamePrefix() + { + try + { + string methodName = Xunit.TestContext.Current?.TestMethod?.MethodName; + return string.IsNullOrEmpty(methodName) ? string.Empty : SanitizeFileName(methodName) + "_"; + } + catch + { + return string.Empty; + } + } + + /// + /// Attaches the file to the current xUnit test result on a best-effort basis. Failures are ignored + /// because attachment support depends on the test pipeline stage and is purely supplementary to the + /// copy into the published artifacts directory. + /// + private static void TryAttachToTestResult(string path) + { + try + { + Xunit.TestContext.Current?.AddAttachment(Path.GetFileName(path), File.ReadAllBytes(path), "application/octet-stream"); + } + catch + { + // Attachment is supplementary; ignore any failure. + } + } + + /// + /// Returns a destination path that does not collide with an existing file, disambiguating with a short + /// unique suffix when necessary. + /// + private static string GetUniqueDestinationPath(string directory, string fileName) + { + string candidate = Path.Combine(directory, fileName); + if (!File.Exists(candidate)) + { + return candidate; + } + + string stem = Path.GetFileNameWithoutExtension(fileName); + string extension = Path.GetExtension(fileName); + return Path.Combine(directory, $"{stem}.{Guid.NewGuid():N}{extension}"); + } + + private static string SanitizeFileName(string value) + { + foreach (char invalid in Path.GetInvalidFileNameChars()) + { + value = value.Replace(invalid, '_'); + } + + return value; + } + /// /// Evaluate the test with the given invariant. /// From 67efb903b61c008913140cd818ab855c2ba0a825 Mon Sep 17 00:00:00 2001 From: Veronika Ovsyannikova <150850103+OvesN@users.noreply.github.com> Date: Thu, 25 Jun 2026 16:37:14 +0200 Subject: [PATCH 25/27] Fix BuildCheck CustomCheck E2E tests (NU1605 restore downgrade) (#14137) Fixes #14163 Fixes BuildCheck tests in pipeline. Investigation flow -> found [log](https://dev.azure.com/dnceng-public/_apis/resources/Containers/54226185/CoreOnLinux%20build%20logs?itemPath=CoreOnLinux%20build%20logs%2FMicrosoft.Build.BuildCheck.UnitTests_net10.0_x64.log) for pipeline failure. From this log I found out that the BuildCheck `CustomCheck*` end-to-end tests fail at restore with **NU1605** (package downgrade of `Microsoft.Build.Framework`), so `-check` never runs and the expected diagnostics are never emitted. **Root cause:** `Microsoft.Build` had gained a `ProjectReference` to `Microsoft.Build.Utilities`, so the `Microsoft.Build` NuGet package declared a dependency on `Microsoft.Build.Utilities.Core`. During the `CustomCheck` test-package restore that dependency resolved to an older preview and was flagged as a downgrade-as-error. **Fix:** move the public `TaskItem` from `Microsoft.Build.Utilities` into `Microsoft.Build.Framework` so it is a single shared type usable from both the engine and Utilities. This removes the `Microsoft.Build` -> `Microsoft.Build.Utilities.Core` dependency without duplicating the type. A small internal `MutableTaskItem` backs the value constructor (Framework cannot reference `Utilities.TaskItem`); it is nullable-enabled and stores metadata in an `ImmutableDictionary` seeded from the shared `ImmutableDictionaryExtensions.EmptyMetadata` (case-insensitive comparer), matching the existing `Utilities.TaskItem` behavior. No product behavior change. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../BackEnd/TaskExecutionHost_Tests.cs | 20 ++++---- .../TaskExecutionHost/TaskExecutionHost.cs | 1 - src/Build/Microsoft.Build.csproj | 1 - src/Framework/MutableTaskItem.cs | 51 +++++++++++++++++++ src/{Utilities => Framework}/TaskItem_T.cs | 11 ++-- 5 files changed, 64 insertions(+), 20 deletions(-) create mode 100644 src/Framework/MutableTaskItem.cs rename src/{Utilities => Framework}/TaskItem_T.cs (94%) diff --git a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs index 5462db854a5..b32bb7f5f73 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -760,7 +760,7 @@ public void TestSetDirectoryInfoArrayParamEmptyItem() public void TestSetTaskItemFileInfoParam() { string filePath = NativeMethodsShared.IsWindows ? @"C:\temp\file.txt" : "/tmp/file.txt"; - ValidateTaskParameter("TaskItemFileInfoParam", filePath, new Microsoft.Build.Utilities.TaskItem(new FileInfo(filePath))); + ValidateTaskParameter("TaskItemFileInfoParam", filePath, new Microsoft.Build.Framework.TaskItem(new FileInfo(filePath))); } /// @@ -801,7 +801,7 @@ public void TestSetTaskItemFileInfoParamEmptyItem() public void TestSetTaskItemFileInfoArrayParam() { string filePath = NativeMethodsShared.IsWindows ? @"C:\temp\file.txt" : "/tmp/file.txt"; - ValidateTaskParameterArray("TaskItemFileInfoArrayParam", filePath, new Microsoft.Build.Utilities.TaskItem[] { new Microsoft.Build.Utilities.TaskItem(new FileInfo(filePath)) }); + ValidateTaskParameterArray("TaskItemFileInfoArrayParam", filePath, new Microsoft.Build.Framework.TaskItem[] { new Microsoft.Build.Framework.TaskItem(new FileInfo(filePath)) }); } /// @@ -812,9 +812,9 @@ public void TestSetTaskItemFileInfoArrayParamMultiple() { string path1 = NativeMethodsShared.IsWindows ? @"C:\temp\file1.txt" : "/tmp/file1.txt"; string path2 = NativeMethodsShared.IsWindows ? @"C:\temp\file2.txt" : "/tmp/file2.txt"; - ValidateTaskParameterArray("TaskItemFileInfoArrayParam", path1 + ";" + path2, new Microsoft.Build.Utilities.TaskItem[] { - new Microsoft.Build.Utilities.TaskItem(new FileInfo(path1)), - new Microsoft.Build.Utilities.TaskItem(new FileInfo(path2)) + ValidateTaskParameterArray("TaskItemFileInfoArrayParam", path1 + ";" + path2, new Microsoft.Build.Framework.TaskItem[] { + new Microsoft.Build.Framework.TaskItem(new FileInfo(path1)), + new Microsoft.Build.Framework.TaskItem(new FileInfo(path2)) }); } @@ -856,7 +856,7 @@ public void TestSetTaskItemFileInfoArrayParamEmptyItem() public void TestSetTaskItemDirectoryInfoParam() { string dirPath = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; - ValidateTaskParameter("TaskItemDirectoryInfoParam", dirPath, new Microsoft.Build.Utilities.TaskItem(new DirectoryInfo(dirPath))); + ValidateTaskParameter("TaskItemDirectoryInfoParam", dirPath, new Microsoft.Build.Framework.TaskItem(new DirectoryInfo(dirPath))); } /// @@ -897,7 +897,7 @@ public void TestSetTaskItemDirectoryInfoParamEmptyItem() public void TestSetTaskItemDirectoryInfoArrayParam() { string dirPath = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; - ValidateTaskParameterArray("TaskItemDirectoryInfoArrayParam", dirPath, new Microsoft.Build.Utilities.TaskItem[] { new Microsoft.Build.Utilities.TaskItem(new DirectoryInfo(dirPath)) }); + ValidateTaskParameterArray("TaskItemDirectoryInfoArrayParam", dirPath, new Microsoft.Build.Framework.TaskItem[] { new Microsoft.Build.Framework.TaskItem(new DirectoryInfo(dirPath)) }); } /// @@ -908,9 +908,9 @@ public void TestSetTaskItemDirectoryInfoArrayParamMultiple() { string path1 = NativeMethodsShared.IsWindows ? @"C:\temp" : "/tmp"; string path2 = NativeMethodsShared.IsWindows ? @"C:\Windows" : "/usr"; - ValidateTaskParameterArray("TaskItemDirectoryInfoArrayParam", path1 + ";" + path2, new Microsoft.Build.Utilities.TaskItem[] { - new Microsoft.Build.Utilities.TaskItem(new DirectoryInfo(path1)), - new Microsoft.Build.Utilities.TaskItem(new DirectoryInfo(path2)) + ValidateTaskParameterArray("TaskItemDirectoryInfoArrayParam", path1 + ";" + path2, new Microsoft.Build.Framework.TaskItem[] { + new Microsoft.Build.Framework.TaskItem(new DirectoryInfo(path1)), + new Microsoft.Build.Framework.TaskItem(new DirectoryInfo(path2)) }); } diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index 36f37c1b8fe..63555657a81 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -22,7 +22,6 @@ using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; -using Microsoft.Build.Utilities; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using Task = System.Threading.Tasks.Task; diff --git a/src/Build/Microsoft.Build.csproj b/src/Build/Microsoft.Build.csproj index faa8ec52357..9a26ec7ddeb 100644 --- a/src/Build/Microsoft.Build.csproj +++ b/src/Build/Microsoft.Build.csproj @@ -29,7 +29,6 @@ - diff --git a/src/Framework/MutableTaskItem.cs b/src/Framework/MutableTaskItem.cs new file mode 100644 index 00000000000..bedf806a9f8 --- /dev/null +++ b/src/Framework/MutableTaskItem.cs @@ -0,0 +1,51 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections; +using System.Collections.Generic; + +#nullable disable + +namespace Microsoft.Build.Framework +{ + internal sealed class MutableTaskItem : ITaskItem2 + { + private readonly Dictionary _metadata = new Dictionary(); + + public MutableTaskItem(string itemSpec) => ItemSpec = itemSpec; + + public string ItemSpec { get; set; } + + public ICollection MetadataNames => _metadata.Keys; + + public int MetadataCount => _metadata.Count; + + public string GetMetadata(string metadataName) => _metadata.TryGetValue(metadataName, out string value) ? value : string.Empty; + + public void SetMetadata(string metadataName, string metadataValue) => _metadata[metadataName] = metadataValue; + + public void RemoveMetadata(string metadataName) => _metadata.Remove(metadataName); + + public void CopyMetadataTo(ITaskItem destinationItem) + { + foreach (KeyValuePair metadatum in _metadata) + { + destinationItem.SetMetadata(metadatum.Key, metadatum.Value); + } + } + + public IDictionary CloneCustomMetadata() => new Dictionary(_metadata); + + public string EvaluatedIncludeEscaped + { + get => ItemSpec; + set => ItemSpec = value; + } + + public string GetMetadataValueEscaped(string metadataName) => GetMetadata(metadataName); + + public void SetMetadataValueLiteral(string metadataName, string metadataValue) => SetMetadata(metadataName, metadataValue); + + public IDictionary CloneCustomMetadataEscaped() => new Dictionary(_metadata); + } +} diff --git a/src/Utilities/TaskItem_T.cs b/src/Framework/TaskItem_T.cs similarity index 94% rename from src/Utilities/TaskItem_T.cs rename to src/Framework/TaskItem_T.cs index fbc4f0d6f10..002ded1d45a 100644 --- a/src/Utilities/TaskItem_T.cs +++ b/src/Framework/TaskItem_T.cs @@ -4,14 +4,9 @@ using System; using System.Collections; using System.Collections.Generic; -using Microsoft.Build.Framework; using Microsoft.Build.Shared; -// Alias to avoid ambiguity: within TaskItem, "TaskItem" refers to this generic struct; -// use TaskItemImpl to refer to the non-generic Utilities.TaskItem class. -using TaskItemImpl = Microsoft.Build.Utilities.TaskItem; - -namespace Microsoft.Build.Utilities +namespace Microsoft.Build.Framework { /// /// A strongly-typed wrapper around that parses the item's identity @@ -40,9 +35,9 @@ public TaskItem(T value) { Value = value; - // Use a mutable TaskItem as backing so metadata mutations are supported + // Use a mutable backing so metadata mutations are supported string itemSpec = ValueTypeParser.ToString(value); - _backingItem = new TaskItemImpl(itemSpec); + _backingItem = new MutableTaskItem(itemSpec); } /// From 7ddc75c25b0595770dc12b737e51706ec5b7ce09 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Thu, 25 Jun 2026 11:07:23 -0500 Subject: [PATCH 26/27] Add typed-parameter binding benchmark and cache TaskItem constructor delegates Adds a BenchmarkDotNet benchmark (TaskParameterBindingBenchmark) that drives the real TaskExecutionHost.SetTaskParameters path to measure the engine's per-parameter binding overhead for the new typed task parameters (AbsolutePath, FileInfo, DirectoryInfo, and ITaskItem of each) against string and ITaskItem baselines. Also optimizes the engine binding path: the ITaskItem wrapping previously called typeof(TaskItem<>).MakeGenericType(...).GetConstructor(...).Invoke(...) per item. It now caches a compiled Func per generic argument T, so the MakeGenericType/GetConstructor/reflection-Invoke work happens once. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../TaskExecutionHost/TaskExecutionHost.cs | 33 +- .../TaskParameterBindingBenchmark.cs | 294 ++++++++++++++++++ 2 files changed, 325 insertions(+), 2 deletions(-) create mode 100644 src/MSBuild.Benchmarks/TaskParameterBindingBenchmark.cs diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index 63555657a81..9c4e023530d 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -3,10 +3,12 @@ using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; +using System.Linq.Expressions; using System.Reflection; #if FEATURE_APPDOMAIN using System.Runtime.Remoting; @@ -761,6 +763,33 @@ private static bool IsPathLikeTaskItemOrITaskItemOfT(Type parameterType) => TaskParameterTypeVerifier.IsPathLikeITaskItemOfT(parameterType) || TaskParameterTypeVerifier.IsPathLikeTaskItemOfT(parameterType, typeof(TaskItem<>).FullName); + /// + /// Cache of compiled constructor delegates that wrap an into a + /// , keyed by the generic argument T. Building the closed generic type and + /// resolving the constructor via reflection on every parameter binding is expensive, so the delegate + /// is compiled once per T and reused. + /// + private static readonly ConcurrentDictionary> s_taskItemOfTFactories = new(); + + /// + /// Wraps the given into a TaskItem<T> where T is + /// , using a cached compiled constructor delegate. + /// + private static ITaskItem CreateTaskItemOfT(Type genericArgument, ITaskItem item) + { + Func factory = s_taskItemOfTFactories.GetOrAdd(genericArgument, static t => + { + ConstructorInfo constructor = typeof(TaskItem<>).MakeGenericType(t).GetConstructor([typeof(ITaskItem)]); + ParameterExpression itemParameter = Expression.Parameter(typeof(ITaskItem), "item"); + return Expression.Lambda>( + Expression.Convert(Expression.New(constructor, itemParameter), typeof(ITaskItem)), + itemParameter).Compile(); + }); + + return factory(item); + } + + /// /// Called on the local side. /// @@ -831,7 +860,7 @@ private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, I { currentItem = item; RecordItemForDisconnectIfNecessary(item); - ITaskItem taskItemOfT = typeof(TaskItem<>).MakeGenericType(elementType.GetGenericArguments()[0]).GetConstructor([typeof(ITaskItem)]).Invoke([item]) as ITaskItem; + ITaskItem taskItemOfT = CreateTaskItemOfT(elementType.GetGenericArguments()[0], item); finalTaskInputs.Add(taskItemOfT); } } @@ -1309,7 +1338,7 @@ private bool InitializeTaskScalarParameter( if (IsPathLikeTaskItemOrITaskItemOfT(parameterType)) { - ITaskItem taskItemOfT = typeof(TaskItem<>).MakeGenericType(parameterType.GetGenericArguments()[0]).GetConstructor(new[] { typeof(ITaskItem) }).Invoke([finalTaskItems[0]]) as ITaskItem; + ITaskItem taskItemOfT = CreateTaskItemOfT(parameterType.GetGenericArguments()[0], finalTaskItems[0]); success = InternalSetTaskParameter(parameter, taskItemOfT); } else diff --git a/src/MSBuild.Benchmarks/TaskParameterBindingBenchmark.cs b/src/MSBuild.Benchmarks/TaskParameterBindingBenchmark.cs new file mode 100644 index 00000000000..4cfb675ba7a --- /dev/null +++ b/src/MSBuild.Benchmarks/TaskParameterBindingBenchmark.cs @@ -0,0 +1,294 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Threading; +using BenchmarkDotNet.Attributes; +using Microsoft.Build.BackEnd; +using Microsoft.Build.BackEnd.Logging; +using Microsoft.Build.Collections; +using Microsoft.Build.Construction; +using Microsoft.Build.Evaluation; +using Microsoft.Build.Execution; +using Microsoft.Build.Framework; +using Microsoft.Build.Shared; + +namespace MSBuild.Benchmarks; + +/// +/// Benchmarks the per-parameter binding cost the engine pays when converting a task +/// parameter's string value into the task's declared CLR type. +/// +/// Each benchmark drives the real path +/// (expansion + type detection + conversion + property set) for a single scalar parameter, +/// so the new path-like types (, , +/// ) and the strongly-typed variants +/// can be compared against the pre-existing string and bindings. +/// +/// Task-input logging is disabled (the unit-test host constructor leaves LogTaskInputs +/// false), so the measurements reflect binding work rather than logging overhead. +/// +[MemoryDiagnoser] +public class TaskParameterBindingBenchmark +{ + private const string TaskName = "BindingBenchmarkTask"; + + private TaskExecutionHost _host = null!; + private ProjectCollection _projectCollection = null!; + + private Dictionary _stringParam = null!; + private Dictionary _itemParam = null!; + private Dictionary _absolutePathParam = null!; + private Dictionary _fileInfoParam = null!; + private Dictionary _directoryInfoParam = null!; + private Dictionary _taskItemAbsolutePathParam = null!; + private Dictionary _taskItemFileInfoParam = null!; + private Dictionary _taskItemDirectoryInfoParam = null!; + + [GlobalSetup] + public void GlobalSetup() + { + _projectCollection = new ProjectCollection(); + ProjectRootElement xml = ProjectRootElement.Create(_projectCollection); + xml.FullPath = Path.Combine(Path.GetTempPath(), "binding-benchmark.proj"); + xml.AddTarget("Build"); + ProjectInstance project = new(xml, globalProperties: null, toolsVersion: null, _projectCollection); + + ILoggingService loggingService = LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); + TargetLoggingContext targetLoggingContext = new( + loggingService, + new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1)); + + _host = new TaskExecutionHost(); + + AssemblyLoadInfo loadInfo = AssemblyLoadInfo.Create(typeof(BindingBenchmarkTaskFactory).FullName, null); + LoadedType loadedType = new( + typeof(BindingBenchmarkTaskFactory), + loadInfo, + typeof(BindingBenchmarkTaskFactory).Assembly, + typeof(ITaskItem)); + + BindingBenchmarkTaskFactory factory = new(); + _host._UNITTESTONLY_TaskFactoryWrapper = new TaskFactoryWrapper(factory, loadedType, TaskName, TaskHostParameters.Empty); + + StubBuildEngine buildEngine = new(); + _host.InitializeForTask( + buildEngine, + targetLoggingContext, + project, + TaskName, + ElementLocation.Create("none", 1, 1), + taskHost: null, + continueOnError: false, + projectFile: "binding-benchmark.proj", +#if FEATURE_APPDOMAIN + null, +#endif + hostServices: null, + isOutOfProc: false, + CancellationToken.None, + TaskEnvironment.Fallback); + + _host.FindTask(TaskHostParameters.Empty); + + TaskLoggingContext taskLoggingContext = new(loggingService, targetLoggingContext.BuildEventContext); + + ItemDictionary items = new(); + Lookup lookup = new(items, new PropertyDictionary()); + ItemBucket bucket = new(FrozenSet.Empty, new Dictionary(), lookup, 0); + bucket.Initialize(null); + + _host.InitializeForBatch(taskLoggingContext, bucket, TaskHostParameters.Empty, scheduledNodeId: 1); + + // Literal values with no expansion tokens, so the per-type conversion is the only variable. + const string FilePath = "subdir/example.txt"; + const string DirPath = "subdir/nested"; + + _stringParam = BuildParameter("StringParam", FilePath); + _itemParam = BuildParameter("ItemParam", FilePath); + _absolutePathParam = BuildParameter("AbsolutePathParam", FilePath); + _fileInfoParam = BuildParameter("FileInfoParam", FilePath); + _directoryInfoParam = BuildParameter("DirectoryInfoParam", DirPath); + _taskItemAbsolutePathParam = BuildParameter("TaskItemAbsolutePathParam", FilePath); + _taskItemFileInfoParam = BuildParameter("TaskItemFileInfoParam", FilePath); + _taskItemDirectoryInfoParam = BuildParameter("TaskItemDirectoryInfoParam", DirPath); + } + + [GlobalCleanup] + public void GlobalCleanup() + { + ((IDisposable)_host)?.Dispose(); + _projectCollection?.Dispose(); + } + + private static Dictionary BuildParameter(string name, string value) + => new(StringComparer.OrdinalIgnoreCase) + { + [name] = (value, ElementLocation.Create("binding-benchmark.proj", 1, 1)), + }; + + [Benchmark(Baseline = true)] + public bool String() => _host.SetTaskParameters(_stringParam); + + [Benchmark] + public bool Item() => _host.SetTaskParameters(_itemParam); + + [Benchmark] + public bool AbsolutePath() => _host.SetTaskParameters(_absolutePathParam); + + [Benchmark] + public bool FileInfo() => _host.SetTaskParameters(_fileInfoParam); + + [Benchmark] + public bool DirectoryInfo() => _host.SetTaskParameters(_directoryInfoParam); + + [Benchmark] + public bool TaskItemOfAbsolutePath() => _host.SetTaskParameters(_taskItemAbsolutePathParam); + + [Benchmark] + public bool TaskItemOfFileInfo() => _host.SetTaskParameters(_taskItemFileInfoParam); + + [Benchmark] + public bool TaskItemOfDirectoryInfo() => _host.SetTaskParameters(_taskItemDirectoryInfoParam); + + /// + /// A minimal task exposing one parameter per binding type under test. Implements + /// so the host's property setter is a constant cost across + /// all parameters, leaving the per-type conversion as the only variable. + /// + private sealed class BindingBenchmarkTask : ITask, IGeneratedTask + { + public IBuildEngine BuildEngine { get; set; } = null!; + + public ITaskHost HostObject { get; set; } = null!; + + public string StringParam { get; set; } = null!; + + public ITaskItem ItemParam { get; set; } = null!; + + public AbsolutePath AbsolutePathParam { get; set; } + + public FileInfo FileInfoParam { get; set; } = null!; + + public DirectoryInfo DirectoryInfoParam { get; set; } = null!; + + public ITaskItem TaskItemAbsolutePathParam { get; set; } = null!; + + public ITaskItem TaskItemFileInfoParam { get; set; } = null!; + + public ITaskItem TaskItemDirectoryInfoParam { get; set; } = null!; + + public bool Execute() => true; + + public void SetPropertyValue(TaskPropertyInfo property, object value) + { + switch (property.Name) + { + case nameof(StringParam): StringParam = (string)value; break; + case nameof(ItemParam): ItemParam = (ITaskItem)value; break; + case nameof(AbsolutePathParam): AbsolutePathParam = (AbsolutePath)value; break; + case nameof(FileInfoParam): FileInfoParam = (FileInfo)value; break; + case nameof(DirectoryInfoParam): DirectoryInfoParam = (DirectoryInfo)value; break; + case nameof(TaskItemAbsolutePathParam): TaskItemAbsolutePathParam = (ITaskItem)value; break; + case nameof(TaskItemFileInfoParam): TaskItemFileInfoParam = (ITaskItem)value; break; + case nameof(TaskItemDirectoryInfoParam): TaskItemDirectoryInfoParam = (ITaskItem)value; break; + default: throw new ArgumentException($"Unknown property '{property.Name}'.", nameof(property)); + } + } + + public object GetPropertyValue(TaskPropertyInfo property) + => property.Name switch + { + nameof(StringParam) => StringParam, + nameof(ItemParam) => ItemParam, + nameof(AbsolutePathParam) => AbsolutePathParam, + nameof(FileInfoParam) => FileInfoParam, + nameof(DirectoryInfoParam) => DirectoryInfoParam, + nameof(TaskItemAbsolutePathParam) => TaskItemAbsolutePathParam, + nameof(TaskItemFileInfoParam) => TaskItemFileInfoParam, + nameof(TaskItemDirectoryInfoParam) => TaskItemDirectoryInfoParam, + _ => throw new ArgumentException($"Unknown property '{property.Name}'.", nameof(property)), + }; + } + + /// + /// Task factory which produces instances and reports + /// their public properties as task parameters. + /// + private sealed class BindingBenchmarkTaskFactory : ITaskFactory + { + public string FactoryName => nameof(BindingBenchmarkTaskFactory); + + public Type TaskType => typeof(BindingBenchmarkTask); + + public bool Initialize(string taskName, IDictionary parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) => true; + + public TaskPropertyInfo[] GetTaskParameters() + { + PropertyInfo[] properties = typeof(BindingBenchmarkTask).GetProperties(BindingFlags.Instance | BindingFlags.Public); + TaskPropertyInfo[] result = new TaskPropertyInfo[properties.Length]; + for (int i = 0; i < properties.Length; i++) + { + result[i] = new TaskPropertyInfo( + properties[i].Name, + properties[i].PropertyType, + output: properties[i].GetCustomAttributes(typeof(OutputAttribute), false).Length > 0, + required: properties[i].GetCustomAttributes(typeof(RequiredAttribute), false).Length > 0); + } + + return result; + } + + public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) => new BindingBenchmarkTask(); + + public void CleanupTask(ITask task) + { + } + } + + /// + /// A no-op build engine. None of its members are invoked while binding input parameters. + /// + private sealed class StubBuildEngine : IBuildEngine2 + { + public bool ContinueOnError => false; + + public int LineNumberOfTaskNode => 0; + + public int ColumnNumberOfTaskNode => 0; + + public string ProjectFileOfTaskNode => "binding-benchmark.proj"; + + public bool IsRunningMultipleNodes => false; + + public void LogErrorEvent(BuildErrorEventArgs e) + { + } + + public void LogWarningEvent(BuildWarningEventArgs e) + { + } + + public void LogMessageEvent(BuildMessageEventArgs e) + { + } + + public void LogCustomEvent(CustomBuildEventArgs e) + { + } + + public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs) + => throw new NotImplementedException(); + + public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, string toolsVersion) + => throw new NotImplementedException(); + + public bool BuildProjectFilesInParallel(string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion) + => throw new NotImplementedException(); + } +} From 00180578d2586a4f5f0bf5c6b5b86c0b4c0e1406 Mon Sep 17 00:00:00 2001 From: Chet Husk Date: Wed, 1 Jul 2026 10:18:46 -0500 Subject: [PATCH 27/27] Address review feedback: nullable pragmas, case-insensitive metadata, unify type detector, remove test-publish infra - Remove redundant #nullable enable/disable pragmas from new files (repo enables nullable via Directory.Build.props); make MutableTaskItem and the TaskParameterTypeVerifier test nullable-clean. - MutableTaskItem: back metadata with a case-insensitive comparer (metadata names are case-insensitive). - ValueTypeParser: document the already-rooted-path invariant for AbsolutePath/FileInfo/DirectoryInfo; drop the numeric TypeCode switch in favor of Convert.ChangeType (InvariantCulture) for consistency. - Unify the 'supported path type' check: move TaskItemTypeDetector into Framework (shared via InternalsVisibleTo, mirroring ValueTypeParser) so TaskItem and the engine share one IsSupportedPathType; AbsolutePath now matched via typeof. - Remove the PublishTestFile test-artifact infrastructure (TestEnvironment/ArtifactsLocationAttribute/EndToEndTests) as no longer needed. - Expand Tasks.md with per-type guidance for the new parameter types. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- documentation/wiki/Tasks.md | 9 + .../TaskParameterTypeVerifier_Tests.cs | 2 - src/Build/Microsoft.Build.csproj | 1 - src/BuildCheck.UnitTests/EndToEndTests.cs | 2 - src/Framework/ITaskItem`1.cs | 2 - src/Framework/MutableTaskItem.cs | 11 +- .../TaskItemTypeDetector.cs | 19 +- src/Framework/TaskItem_T.cs | 11 +- src/Framework/ValueTypeParser.cs | 47 ++--- src/MSBuild/MSBuild.csproj | 1 - src/Tasks/Microsoft.Build.Tasks.csproj | 1 - .../ArtifactsLocationAttribute.cs | 9 +- .../Microsoft.Build.UnitTests.Shared.csproj | 1 - src/UnitTests.Shared/TestEnvironment.cs | 192 ------------------ 14 files changed, 46 insertions(+), 262 deletions(-) rename src/{Shared => Framework}/TaskItemTypeDetector.cs (54%) diff --git a/documentation/wiki/Tasks.md b/documentation/wiki/Tasks.md index 9dbf25ef20a..2eaf5985c76 100644 --- a/documentation/wiki/Tasks.md +++ b/documentation/wiki/Tasks.md @@ -16,6 +16,15 @@ A task is a class implementing [`ITask`](https://github.com/dotnet/msbuild/blob/ - **Path types**: `AbsolutePath`, `AbsolutePath[]`, `FileInfo`, `FileInfo[]`, `DirectoryInfo`, `DirectoryInfo[]` > The engine also accepts arbitrary value types (such as `int`, `DateTime`, or any custom struct) by converting to/from their string representation, but using them is discouraged. Prefer the documented types above. + + Guidance on choosing a type: + - Use `string`/`string[]` only when the value is genuinely free-form text (a message, an identifier, a raw switch). If the value is a path, prefer one of the path types below so the engine roots it consistently and you avoid re-implementing path resolution in the task. + - Use `AbsolutePath` when you need a fully-rooted path but do not need to touch the file system. The engine roots the incoming value against the project directory for you, and `AbsolutePath` is a lightweight struct that just carries the rooted string — pick it over `string` whenever a parameter is conceptually a path. + - Use `FileInfo` when the parameter represents a single file and the task wants the `System.IO.FileInfo` conveniences (`Exists`, `Length`, `Directory`, `LastWriteTime`, etc.) without constructing the `FileInfo` itself. The value is rooted before the `FileInfo` is created, so relative inputs won't accidentally resolve against the process working directory. + - Use `DirectoryInfo` for the directory equivalent of the above (a single directory parameter where the task wants `System.IO.DirectoryInfo` members). As with `FileInfo`, the path is rooted before construction. + - Use `ITaskItem`/`ITaskItem[]` when the task needs item **metadata** (e.g. `Identity`, `RecursiveDir`, or custom metadata) in addition to the item spec. + - Use `ITaskItem` (e.g. `ITaskItem`, `ITaskItem`, `ITaskItem`) when you need **both** item metadata **and** the strongly-typed, pre-rooted value — the `Value` property exposes the parsed `T` while the item still carries its metadata. Prefer this over taking a bare `ITaskItem` and re-parsing `ItemSpec` yourself. + - Prefer the scalar path types (`AbsolutePath`/`FileInfo`/`DirectoryInfo`) over `string` even for optional parameters; they make the task's intent explicit and centralize rooting in the engine. - The properties can have attributes `[Required]` which causes the engine to check that it has a value when the task is run and `[Output]` which exposes the property to be used again in XML - Tasks have the `Log` property set by the engine to log messages/errors/warnings. diff --git a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs index 6244dd8599d..0a9d526a04e 100644 --- a/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskParameterTypeVerifier_Tests.cs @@ -9,8 +9,6 @@ using Shouldly; using Xunit; -#nullable disable - namespace Microsoft.Build.UnitTests.BackEnd { /// diff --git a/src/Build/Microsoft.Build.csproj b/src/Build/Microsoft.Build.csproj index 9a26ec7ddeb..f0c1cacaa83 100644 --- a/src/Build/Microsoft.Build.csproj +++ b/src/Build/Microsoft.Build.csproj @@ -139,7 +139,6 @@ - diff --git a/src/BuildCheck.UnitTests/EndToEndTests.cs b/src/BuildCheck.UnitTests/EndToEndTests.cs index 9d096607141..ac262ae0f37 100644 --- a/src/BuildCheck.UnitTests/EndToEndTests.cs +++ b/src/BuildCheck.UnitTests/EndToEndTests.cs @@ -578,7 +578,6 @@ public void SampleCheckIntegrationTest_ReplayBinaryLogOfCheckedBuild(bool buildI var projectDirectory = Path.GetDirectoryName(projectFile.Path); string logFile = _env.ExpectFile(".binlog").Path; - _env.PublishTestFile(logFile); _ = RunnerUtilities.ExecBootstrapedMSBuild( $"{Path.GetFileName(projectFile.Path)} /m:1 -nr:False -restore {(checkRequested ? "-check" : string.Empty)} -bl:{logFile}", @@ -693,7 +692,6 @@ public void SampleCheckIntegrationTest_CheckOnBinaryLogReplay(bool buildInOutOfP string? projectDirectory = Path.GetDirectoryName(projectFile.Path); string logFile = _env.ExpectFile(".binlog").Path; - _env.PublishTestFile(logFile); _ = RunnerUtilities.ExecBootstrapedMSBuild( $"{Path.GetFileName(projectFile.Path)} /m:1 -nr:False -restore -bl:{logFile}", diff --git a/src/Framework/ITaskItem`1.cs b/src/Framework/ITaskItem`1.cs index 32eed11567a..59fb884dde1 100644 --- a/src/Framework/ITaskItem`1.cs +++ b/src/Framework/ITaskItem`1.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable - namespace Microsoft.Build.Framework; /// diff --git a/src/Framework/MutableTaskItem.cs b/src/Framework/MutableTaskItem.cs index bedf806a9f8..7f29688e65d 100644 --- a/src/Framework/MutableTaskItem.cs +++ b/src/Framework/MutableTaskItem.cs @@ -1,16 +1,19 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; using System.Collections; using System.Collections.Generic; -#nullable disable - namespace Microsoft.Build.Framework { internal sealed class MutableTaskItem : ITaskItem2 { - private readonly Dictionary _metadata = new Dictionary(); + // MSBuild metadata names are case-insensitive, so the backing store must use a case-insensitive + // comparer; otherwise GetMetadata("fullpath") and GetMetadata("FullPath") would resolve differently. + // (The engine's MSBuildNameIgnoreCaseComparer is not available in the Framework assembly, so we use + // the equivalent ordinal, case-insensitive comparer here.) + private readonly Dictionary _metadata = new Dictionary(StringComparer.OrdinalIgnoreCase); public MutableTaskItem(string itemSpec) => ItemSpec = itemSpec; @@ -20,7 +23,7 @@ internal sealed class MutableTaskItem : ITaskItem2 public int MetadataCount => _metadata.Count; - public string GetMetadata(string metadataName) => _metadata.TryGetValue(metadataName, out string value) ? value : string.Empty; + public string GetMetadata(string metadataName) => _metadata.TryGetValue(metadataName, out string? value) ? value ?? string.Empty : string.Empty; public void SetMetadata(string metadataName, string metadataValue) => _metadata[metadataName] = metadataValue; diff --git a/src/Shared/TaskItemTypeDetector.cs b/src/Framework/TaskItemTypeDetector.cs similarity index 54% rename from src/Shared/TaskItemTypeDetector.cs rename to src/Framework/TaskItemTypeDetector.cs index 6ed349a6b72..71f6d3cf1c9 100644 --- a/src/Shared/TaskItemTypeDetector.cs +++ b/src/Framework/TaskItemTypeDetector.cs @@ -3,16 +3,27 @@ using System; using System.IO; +using Microsoft.Build.Framework; namespace Microsoft.Build.Shared { internal static class TaskItemTypeDetector { - private const string AbsolutePathFullName = "Microsoft.Build.Framework.AbsolutePath"; + // The generic type definitions (ITaskItem/TaskItem) are matched by full type name because + // callers pass the FullName of whichever definition they care about (see IsPathLikeTaskItemOfT). private const string GenericITaskItemFullName = "Microsoft.Build.Framework.ITaskItem`1"; - internal static bool IsAbsolutePathType(Type type) - => string.Equals(type.FullName, AbsolutePathFullName, StringComparison.Ordinal); + internal static bool IsAbsolutePathType(Type type) => type == typeof(AbsolutePath); + + /// + /// Returns true if is one of the strongly-typed path types supported as a + /// task parameter or as the T in ITaskItem<T>/TaskItem<T> + /// (, , or ). This is the + /// single definition of "supported path type" shared by the engine parameter-binding code and + /// TaskItem<T>. + /// + internal static bool IsSupportedPathType(Type type) + => type == typeof(AbsolutePath) || type == typeof(FileInfo) || type == typeof(DirectoryInfo); internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTaskItemTypeDefinitionFullName) { @@ -34,7 +45,7 @@ internal static bool IsPathLikeTaskItemOfT(Type parameterType, string genericTas } Type typeArg = genericArguments[0]; - return IsAbsolutePathType(typeArg) || typeArg == typeof(FileInfo) || typeArg == typeof(DirectoryInfo); + return IsSupportedPathType(typeArg); } internal static bool IsPathLikeITaskItemOfT(Type parameterType) diff --git a/src/Framework/TaskItem_T.cs b/src/Framework/TaskItem_T.cs index 002ded1d45a..b54706b1d21 100644 --- a/src/Framework/TaskItem_T.cs +++ b/src/Framework/TaskItem_T.cs @@ -63,19 +63,10 @@ public TaskItem(ITaskItem item) // For path-like types, prefer the FullPath metadata (which is always absolute) // over ItemSpec which may be relative. - string parseFrom = IsPathLikeType() ? GetFullPathOrItemSpec(item, itemSpec) : itemSpec; + string parseFrom = TaskItemTypeDetector.IsSupportedPathType(typeof(T)) ? GetFullPathOrItemSpec(item, itemSpec) : itemSpec; Value = ParseValue(parseFrom); } - /// Returns true if T is a path-like type that benefits from absolute path resolution. - private static bool IsPathLikeType() - { - Type t = typeof(T); - return t == typeof(System.IO.FileInfo) || - t == typeof(System.IO.DirectoryInfo) || - t == typeof(AbsolutePath); - } - /// Returns the FullPath metadata value if non-empty, otherwise falls back to itemSpec. private static string GetFullPathOrItemSpec(ITaskItem item, string itemSpec) { diff --git a/src/Framework/ValueTypeParser.cs b/src/Framework/ValueTypeParser.cs index 6cac1a1dd60..5ecfc873842 100644 --- a/src/Framework/ValueTypeParser.cs +++ b/src/Framework/ValueTypeParser.cs @@ -6,8 +6,6 @@ using System.IO; using Microsoft.Build.Framework; -#nullable enable - namespace Microsoft.Build.Shared { /// @@ -37,6 +35,14 @@ public static object Parse(string value, Type targetType) { try { + // Path-like types (AbsolutePath/FileInfo/DirectoryInfo) are constructed directly from + // 'value' without rooting it here, because callers are expected to pass an already-rooted + // (absolute) path. The engine's parameter-binding path roots the string via + // TaskEnvironment.GetAbsolutePath before calling Parse, and the TaskItem path derives + // 'value' from the item's FullPath metadata (also absolute). Constructing FileInfo/ + // DirectoryInfo from a relative string would silently resolve against the current working + // directory, so we rely on that rooting invariant rather than re-resolving here. + // Special handling for AbsolutePath if (targetType == typeof(AbsolutePath)) { @@ -67,38 +73,11 @@ public static object Parse(string value, Type targetType) return value; } - // Use TypeCode-based parsing for built-in types - TypeCode typeCode = Type.GetTypeCode(targetType); - switch (typeCode) - { - case TypeCode.Int32: - return int.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.Int64: - return long.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.Double: - return double.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.Single: - return float.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.Decimal: - return decimal.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.Byte: - return byte.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.SByte: - return sbyte.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.Int16: - return short.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.UInt16: - return ushort.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.UInt32: - return uint.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.UInt64: - return ulong.Parse(value, CultureInfo.InvariantCulture); - case TypeCode.Char: - return char.Parse(value); - default: - // Fallback to Convert.ChangeType for other types - return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture); - } + // Everything else (numeric types, char, etc.) is converted via Convert.ChangeType, pinned + // to InvariantCulture. This is deliberately permissive: a future analyzer is expected to + // steer authors toward the first-class supported types above and away from relying on this + // general-purpose conversion for parameter types we don't really intend to support. + return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture); } catch (Exception ex) when (ex is FormatException || ex is InvalidCastException || ex is OverflowException || ex is ArgumentException || ex is NotSupportedException) { diff --git a/src/MSBuild/MSBuild.csproj b/src/MSBuild/MSBuild.csproj index 98f966c746e..f98c0dffefa 100644 --- a/src/MSBuild/MSBuild.csproj +++ b/src/MSBuild/MSBuild.csproj @@ -85,7 +85,6 @@ - diff --git a/src/Tasks/Microsoft.Build.Tasks.csproj b/src/Tasks/Microsoft.Build.Tasks.csproj index 057ff755c2d..c766af3919b 100644 --- a/src/Tasks/Microsoft.Build.Tasks.csproj +++ b/src/Tasks/Microsoft.Build.Tasks.csproj @@ -48,7 +48,6 @@ - diff --git a/src/UnitTests.Shared/ArtifactsLocationAttribute.cs b/src/UnitTests.Shared/ArtifactsLocationAttribute.cs index 9abbc29bc61..8aaeeeb85ea 100644 --- a/src/UnitTests.Shared/ArtifactsLocationAttribute.cs +++ b/src/UnitTests.Shared/ArtifactsLocationAttribute.cs @@ -4,14 +4,7 @@ namespace Microsoft.Build.UnitTests.Shared; [System.AttributeUsage(System.AttributeTargets.Assembly)] -public sealed class ArtifactsLocationAttribute(string artifactsLocation, string? artifactsLogLocation = null) : System.Attribute +public sealed class ArtifactsLocationAttribute(string artifactsLocation) : System.Attribute { public string ArtifactsLocation { get; } = artifactsLocation; - - /// - /// The build's log output directory (artifacts/log/<Configuration>). This directory is published - /// as a build artifact by CI, so binary logs captured here for failing out-of-process MSBuild - /// invocations are automatically collected without any pipeline changes. - /// - public string? ArtifactsLogLocation { get; } = artifactsLogLocation; } diff --git a/src/UnitTests.Shared/Microsoft.Build.UnitTests.Shared.csproj b/src/UnitTests.Shared/Microsoft.Build.UnitTests.Shared.csproj index 6f43f823c3e..a10bd888634 100644 --- a/src/UnitTests.Shared/Microsoft.Build.UnitTests.Shared.csproj +++ b/src/UnitTests.Shared/Microsoft.Build.UnitTests.Shared.csproj @@ -46,7 +46,6 @@ <_Parameter1>$(ArtifactsShippingPackagesDir) - <_Parameter2>$(ArtifactsLogDir) diff --git a/src/UnitTests.Shared/TestEnvironment.cs b/src/UnitTests.Shared/TestEnvironment.cs index 8bee052b1f8..d1b68e4de72 100644 --- a/src/UnitTests.Shared/TestEnvironment.cs +++ b/src/UnitTests.Shared/TestEnvironment.cs @@ -43,12 +43,6 @@ public partial class TestEnvironment : IDisposable private bool _disposed; - /// - /// Files registered via to be collected as CI - /// build artifacts when the test completes. - /// - private readonly List<(string Path, bool Always)> _filesToPublish = new List<(string, bool)>(); - public TransientTestFolder DefaultTestDirectory => _defaultTestDirectory.Value; /// @@ -112,10 +106,6 @@ private void Cleanup() { _disposed = true; - // Publish registered files (e.g. binary logs) before reverting variants, which would - // otherwise delete the transient files/folders they live in. - PublishRegisteredFiles(); - // Reset test variants in reverse order to get back to original state. for (int i = _variants.Count - 1; i >= 0; i--) { @@ -134,188 +124,6 @@ private void Cleanup() } } - /// - /// Registers a file to be collected as a CI build artifact when the test completes. - /// - /// - /// - /// This is intended for diagnostics that are produced out-of-band — most notably binary logs - /// (-bl) emitted by out-of-process MSBuild invocations — which would otherwise be lost when - /// test cleanup deletes the transient files and folders they live in. - /// - /// - /// On cleanup the file is copied into the build's log output directory - /// (artifacts/log/<Configuration>/TestArtifacts). That directory is published as a build - /// artifact by CI, so registered files are collected automatically without any pipeline changes. The - /// file path is also written to the test output, and the file is attached to the xUnit test result on a - /// best-effort basis. - /// - /// - /// Typical usage is to point a binary log at a test-environment-unique path, run the build, and register - /// that path: - /// - /// string binlog = _env.ExpectFile(".binlog").Path; - /// _env.PublishTestFile(binlog); - /// RunnerUtilities.ExecBootstrapedMSBuild($"{project} -bl:{binlog}", out bool success); - /// - /// - /// - /// The absolute path of the file to publish. - /// - /// When (default), the file is only published if the test did not pass, keeping - /// artifacts from passing runs to a minimum. When , the file is published - /// regardless of the test outcome. - /// - public void PublishTestFile(string filePath, bool always = false) - { - if (string.IsNullOrEmpty(filePath)) - { - throw new ArgumentNullException(nameof(filePath)); - } - - _filesToPublish.Add((filePath, always)); - } - - /// - /// Copies and/or attaches files registered via so they are - /// collected as CI build artifacts. Invoked during cleanup before transient state is reverted. - /// - private void PublishRegisteredFiles() - { - if (_filesToPublish.Count == 0) - { - return; - } - - bool testPassed = DidCurrentTestPass(); - string destinationDirectory = ResolvePublishDirectory(); - string testNamePrefix = GetCurrentTestNamePrefix(); - - foreach ((string path, bool always) in _filesToPublish) - { - try - { - if (!always && testPassed) - { - continue; - } - - if (!File.Exists(path)) - { - Output?.WriteLine($"[PublishTestFile] Skipping '{path}' because it does not exist."); - continue; - } - - if (string.IsNullOrEmpty(destinationDirectory)) - { - Output?.WriteLine($"[PublishTestFile] No artifacts log directory is available; '{path}' was not published."); - } - else - { - Directory.CreateDirectory(destinationDirectory); - string destination = GetUniqueDestinationPath(destinationDirectory, testNamePrefix + Path.GetFileName(path)); - File.Copy(path, destination, overwrite: true); - Output?.WriteLine($"[PublishTestFile] Published '{path}' to '{destination}'."); - } - - TryAttachToTestResult(path); - } - catch (Exception e) - { - Output?.WriteLine($"[PublishTestFile] Failed to publish '{path}': {e}"); - } - } - } - - /// - /// The directory into which published files are copied. This lives under the build's log output - /// directory, which CI publishes as a build artifact. Returns if the location is - /// unknown (for example, when running outside the build). - /// - private static string ResolvePublishDirectory() - { - string logDirectory = RunnerUtilities.ArtifactsLocationAttribute?.ArtifactsLogLocation; - return string.IsNullOrEmpty(logDirectory) ? null : Path.Combine(logDirectory, "TestArtifacts"); - } - - /// - /// Returns only when the current test is known to have passed. Any other state - /// (failed, skipped, unknown, or not running under xUnit) returns so that - /// diagnostics are preserved by default. - /// - private static bool DidCurrentTestPass() - { - try - { - return Xunit.TestContext.Current?.TestState?.Result == Xunit.TestResult.Passed; - } - catch - { - return false; - } - } - - /// - /// Returns a sanitized, file-name-safe prefix derived from the current test method name, or an empty - /// string if it cannot be determined. - /// - private static string GetCurrentTestNamePrefix() - { - try - { - string methodName = Xunit.TestContext.Current?.TestMethod?.MethodName; - return string.IsNullOrEmpty(methodName) ? string.Empty : SanitizeFileName(methodName) + "_"; - } - catch - { - return string.Empty; - } - } - - /// - /// Attaches the file to the current xUnit test result on a best-effort basis. Failures are ignored - /// because attachment support depends on the test pipeline stage and is purely supplementary to the - /// copy into the published artifacts directory. - /// - private static void TryAttachToTestResult(string path) - { - try - { - Xunit.TestContext.Current?.AddAttachment(Path.GetFileName(path), File.ReadAllBytes(path), "application/octet-stream"); - } - catch - { - // Attachment is supplementary; ignore any failure. - } - } - - /// - /// Returns a destination path that does not collide with an existing file, disambiguating with a short - /// unique suffix when necessary. - /// - private static string GetUniqueDestinationPath(string directory, string fileName) - { - string candidate = Path.Combine(directory, fileName); - if (!File.Exists(candidate)) - { - return candidate; - } - - string stem = Path.GetFileNameWithoutExtension(fileName); - string extension = Path.GetExtension(fileName); - return Path.Combine(directory, $"{stem}.{Guid.NewGuid():N}{extension}"); - } - - private static string SanitizeFileName(string value) - { - foreach (char invalid in Path.GetInvalidFileNameChars()) - { - value = value.Replace(invalid, '_'); - } - - return value; - } - /// /// Evaluate the test with the given invariant. ///