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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Arcade.sln
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.DotNet.SourceBuil
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.DotNet.SourceBuild.Tasks.Tests", "src\Microsoft.DotNet.SourceBuild\tests\Microsoft.DotNet.SourceBuild.Tasks.Tests.csproj", "{CE5278A3-2442-4309-A543-5BA5C1C76A2A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.DotNet.Build.Tasks.Templating", "src\Microsoft.DotNet.Build.Tasks.Templating\src\Microsoft.DotNet.Build.Tasks.Templating.csproj", "{AED823B2-2167-408E-9732-ECAD854FDCA5}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.DotNet.Build.Tasks.Templating.Tests", "src\Microsoft.DotNet.Build.Tasks.Templating\test\Microsoft.DotNet.Build.Tasks.Templating.Tests.csproj", "{FB4168D5-6EA6-4777-AD4F-95758C177FE8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -723,6 +727,30 @@ Global
{CE5278A3-2442-4309-A543-5BA5C1C76A2A}.Release|x64.Build.0 = Release|Any CPU
{CE5278A3-2442-4309-A543-5BA5C1C76A2A}.Release|x86.ActiveCfg = Release|Any CPU
{CE5278A3-2442-4309-A543-5BA5C1C76A2A}.Release|x86.Build.0 = Release|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Debug|x64.ActiveCfg = Debug|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Debug|x64.Build.0 = Debug|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Debug|x86.ActiveCfg = Debug|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Debug|x86.Build.0 = Debug|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Release|Any CPU.Build.0 = Release|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Release|x64.ActiveCfg = Release|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Release|x64.Build.0 = Release|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Release|x86.ActiveCfg = Release|Any CPU
{AED823B2-2167-408E-9732-ECAD854FDCA5}.Release|x86.Build.0 = Release|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Debug|x64.ActiveCfg = Debug|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Debug|x64.Build.0 = Debug|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Debug|x86.ActiveCfg = Debug|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Debug|x86.Build.0 = Debug|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Release|Any CPU.Build.0 = Release|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Release|x64.ActiveCfg = Release|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Release|x64.Build.0 = Release|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Release|x86.ActiveCfg = Release|Any CPU
{FB4168D5-6EA6-4777-AD4F-95758C177FE8}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -753,6 +781,7 @@ Global
{6F517597-E9E2-43B2-B7E2-757132EA525C} = {E41E23C4-5CB0-4C61-9E05-EEFFEC4B356D}
{1CC55B23-6212-4120-BF52-8DED9CFF9FBC} = {6F517597-E9E2-43B2-B7E2-757132EA525C}
{CE5278A3-2442-4309-A543-5BA5C1C76A2A} = {C53DD924-C212-49EA-9BC4-1827421361EF}
{FB4168D5-6EA6-4777-AD4F-95758C177FE8} = {C53DD924-C212-49EA-9BC4-1827421361EF}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {32B9C883-432E-4FC8-A1BF-090EB033DD5B}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// 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.Generic;
using System.IO;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Microsoft.DotNet.Build.Tasks.Templating
{
/// <summary>
/// <para>
/// Generates a new file at <see cref="OutputPath"/>.
/// </para>
/// <para>
/// The <see cref="TemplateFile"/> can define variables for substitution using <see cref="Properties"/>.
/// </para>
/// <example>
/// The input file might look like this:
/// <code>
/// 2 + 2 = ${Sum}
/// </code>
/// When the task is invoked like this, it will produce "2 + 2 = 4"
/// <code>
/// &lt;GenerateFileFromTemplate Properties="Sum=4;OtherValue=123;" ... &gt;
/// </code>
/// </example>
/// </summary>
public class GenerateFileFromTemplate : Task
{
/// <summary>
/// The template file using the variable syntax <c>${VarName}</c>.
/// If your template file needs to output this format, you can escape the dollar sign with a backtick e.g. <c>`${NotReplaced}</c>.
/// </summary>
[Required]
public string TemplateFile { get; set; }

/// <summary>
/// The destination for the generated file.
/// </summary>
[Required]
public string OutputPath { get; set; }

/// <summary>
/// Key=Value pairs of values, separated by semicolons e.g. <c>Properties="Sum=4;OtherValue=123;"</c>.
/// </summary>
[Required]
public string[] Properties { get; set; }

/// <summary>
/// The destination for the generated file resolved by this task.
/// </summary>
[Output]
public string ResolvedOutputPath { get; set; }

public override bool Execute()
{
ResolvedOutputPath = Path.GetFullPath(OutputPath.Replace('\\', '/'));

if (!File.Exists(TemplateFile))
{
Log.LogError($"File {TemplateFile} does not exist");
return false;
}

IDictionary<string, string> values = MSBuildListSplitter.GetNamedProperties(Properties, Log);
string template = File.ReadAllText(TemplateFile);

string result = Replace(template, values);
Directory.CreateDirectory(Path.GetDirectoryName(ResolvedOutputPath));
File.WriteAllText(ResolvedOutputPath, result);

return !Log.HasLoggedErrors;
}

public string Replace(string template, IDictionary<string, string> values)
{
StringBuilder sb = new();
StringBuilder varNameSb = new();
int line = 1;
for (int i = 0; i < template.Length; i++)
{
char templateChar = template[i];
char nextTemplateChar = i + 1 >= template.Length
? '\0'
: template[i + 1];

// count lines in the template file
if (templateChar == '\n')
{
line++;
}

if (templateChar == '`' && (nextTemplateChar == '$' || nextTemplateChar == '`'))
{
// skip the backtick for known escape characters
i++;
sb.Append(nextTemplateChar);
continue;
}

if (templateChar != '$' || nextTemplateChar != '{')
{
// variables begin with ${. Moving on.
sb.Append(templateChar);
continue;
}

varNameSb.Clear();
i += 2;
for (; i < template.Length; i++)
{
templateChar = template[i];
if (templateChar != '}')
{
varNameSb.Append(templateChar);
}
else
{
// Found the end of the variable substitution
string varName = varNameSb.ToString();
if (values.TryGetValue(varName, out string value))
{
sb.Append(value);
}
else
{
Log.LogWarning(null, null, null, TemplateFile,
line, 0, 0, 0,
message: $"No property value is available for '{varName}'");
}

varNameSb.Clear();
break;
}
}

if (varNameSb.Length > 0)
{
Log.LogWarning(null, null, null, TemplateFile,
line, 0, 0, 0,
message: "Expected closing bracket for variable placeholder. No substitution will be made.");
sb.Append("${").Append(varNameSb.ToString());
}
}

return sb.ToString();
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// 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.Generic;
using Microsoft.Build.Utilities;

namespace Microsoft.DotNet.Build.Tasks.Templating
{
internal static class MSBuildListSplitter
{
public static IDictionary<string, string> GetNamedProperties(string[] input, TaskLoggingHelper log)
{
Dictionary<string, string> values = new(StringComparer.OrdinalIgnoreCase);
if (input == null)
{
return values;
}

foreach (string item in input)
{
int splitIdx = item.IndexOf('=');
if (splitIdx < 0)
{
log.LogWarning($"Property: {item} does not have a valid '=' separator");
continue;
}

string key = item.Substring(0, splitIdx).Trim();
if (string.IsNullOrEmpty(key))
{
log.LogWarning($"Property: {item} does not have a valid property name");
continue;
}

string value = item.Substring(splitIdx + 1);
values[key] = value;
}

return values;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. -->
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Description>Templating task package</Description>
<PackageTags>Arcade Build Tool Templating</PackageTags>
<IncludeSymbols>false</IncludeSymbols>
<IncludeSource>false</IncludeSource>
<IsPackable>true</IsPackable>
<BuildOutputTargetFolder>tools\</BuildOutputTargetFolder>
<DevelopmentDependency>true</DevelopmentDependency>
<SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking>
<EnableDefaultNoneItems>false</EnableDefaultNoneItems>
</PropertyGroup>

<ItemGroup>
<None Include="build/**/*.*" Pack="true">
<PackagePath>build</PackagePath>
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="$(MicrosoftBuildUtilitiesCoreVersion)" />
</ItemGroup>

<Import Project="$(RepoRoot)eng\BuildTask.targets" />
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. -->
<Project>

<PropertyGroup>
<MicrosoftDotNetBuildTasksTemplatingAssembly>$(MSBuildThisFileDirectory)..\tools\netstandard2.0\Microsoft.DotNet.Build.Tasks.Templating.dll</MicrosoftDotNetBuildTasksTemplatingAssembly>
</PropertyGroup>

<UsingTask TaskName="Microsoft.DotNet.Build.Tasks.Templating.GenerateFileFromTemplate" AssemblyFile="$(MicrosoftDotNetBuildTasksTemplatingAssembly)" />

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// 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 Microsoft.DotNet.Arcade.Sdk.Tests.Utilities;
using Xunit;

namespace Microsoft.DotNet.Build.Tasks.Templating.Tests
{
public class GenerateFileFromTemplateTests
{
[Fact]
public void GenerateFileFromTemplate_SubstitutesValidProperties()
{
string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string filePath = Path.Combine(tempDir, "Directory.Build.props");

try
{
GenerateFileFromTemplate task = new();
task.TemplateFile = GetFullPath("Directory.Build.props.in");
task.OutputPath = filePath;
task.Properties = new[] { "DefaultNetCoreTargetFramework=net6.0" };

Assert.True(task.Execute());
Assert.Equal(ReadAllText("Directory.Build.props.in").Replace("${DefaultNetCoreTargetFramework}", "net6.0"), File.ReadAllText(filePath));
}
finally
{
Directory.Delete(tempDir, true);
}
}

[Theory]
[InlineData("DefaultNetCoreTargetFramework=")]
[InlineData("=net6.0")]
[InlineData("net6.0")]
[InlineData("DefaultNetCoreTargetFramework:net6.0")]
[InlineData("Default_NetCore_Target_Framework=net6.0")]
public void GenerateFileFromTemplate_RemovesInvalidProperties(string invalidProperty)
{
string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string filePath = Path.Combine(tempDir, "Directory.Build.props");

try
{
GenerateFileFromTemplate task = new();
task.BuildEngine = new MockEngine();
task.TemplateFile = GetFullPath("Directory.Build.props.in");
task.OutputPath = filePath;
task.Properties = new[] { invalidProperty };

Assert.True(task.Execute());
Assert.Equal(ReadAllText("Directory.Build.props.in").Replace("${DefaultNetCoreTargetFramework}", string.Empty), File.ReadAllText(filePath));
}
finally
{
Directory.Delete(tempDir, true);
}
}

[Theory]
[InlineData("Directory.Build.props.malformedbraces.in")]
[InlineData("Directory.Build.props.nobraces.in")]
public void GenerateFileFromTemplate_IgnoresMalformedTemplate(string filename)
{
string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string filePath = Path.Combine(tempDir, "Directory.Build.props");

try
{
GenerateFileFromTemplate task = new();
task.BuildEngine = new MockEngine();
task.TemplateFile = GetFullPath(filename);
task.OutputPath = filePath;
task.Properties = new[] { "DefaultNetCoreTargetFramework=net6.0" };

Assert.True(task.Execute());
Assert.Equal(ReadAllText(filename), File.ReadAllText(filePath));
}
finally
{
Directory.Delete(tempDir, true);
}
}

public static string GetFullPath(string relativeTestInputPath)
{
return Path.Combine(
Path.GetDirectoryName(typeof(GenerateFileFromTemplateTests).Assembly.Location),
"testassets",
relativeTestInputPath);
}

public static string ReadAllText(string relativeTestInputPath)
{
string path = GetFullPath(relativeTestInputPath);
return File.ReadAllText(path);
}
}
}
Loading