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
3 changes: 2 additions & 1 deletion src/Cli/Microsoft.TemplateEngine.Cli/Components.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ public static class Components
(typeof(IPostActionProcessor), new ChmodPostActionProcessor()),
(typeof(IPostActionProcessor), new InstructionDisplayPostActionProcessor()),
(typeof(IPostActionProcessor), new ProcessStartPostActionProcessor()),
(typeof(IPostActionProcessor), new AddJsonPropertyPostActionProcessor())
(typeof(IPostActionProcessor), new AddJsonPropertyPostActionProcessor()),
(typeof(IPostActionProcessor), new CreateOrUpdateDotnetConfigPostActionProcessor()),
};
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions src/Cli/Microsoft.TemplateEngine.Cli/LocalizableStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -953,4 +953,23 @@ The header is followed by the list of parameters and their errors (might be seve
<data name="PostAction_ModifyJson_Verbose_AttemptingToFindJsonFile" xml:space="preserve">
<value>Attempting to find json file '{0}' in '{1}'</value>
</data>
<data name="PostAction_DotnetConfig_Error_ArgumentNotConfigured" xml:space="preserve">
<value>Post action argument '{0}' is mandatory, but not configured.</value>
</data>
<data name="PostAction_CreateDotnetConfig_Succeeded" xml:space="preserve">
<value>Successfully created 'dotnet.config' file.</value>
<comment>{Locked="dotnet.config"}</comment>
</data>
<data name="PostAction_CreateDotnetConfig_CreatedNewSection" xml:space="preserve">
<value>Created new section in 'dotnet.config' file</value>
<comment>{Locked="dotnet.config"}</comment>
</data>
<data name="PostAction_CreateDotnetConfig_ValueAlreadyExist" xml:space="preserve">
<value>The required value in 'dotnet.config' is already set.</value>
<comment>{Locked="dotnet.config"}</comment>
</data>
<data name="PostAction_CreateDotnetConfig_ManuallyUpdate" xml:space="preserve">
<value>Updating existing values in 'dotnet.config' is not yet supported. Please, manually update 'dotnet.config' to have '{0}' under section '{1}'.</value>
<comment>{Locked="dotnet.config"}</comment>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<PackageReference Include="Microsoft.TemplateEngine.Edge" />
<PackageReference Include="Microsoft.TemplateSearch.Common" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" />
<PackageReference Include="Microsoft.Extensions.Configuration.Ini" />
<PackageReference Include="Wcwidth.Sources" ExcludeAssets="all" GeneratePathProperty="true" />
<PackageReference Include="System.CommandLine" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.DotNet.Cli.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem;

namespace Microsoft.TemplateEngine.Cli.PostActionProcessors
{
internal sealed class CreateOrUpdateDotnetConfigPostActionProcessor : PostActionProcessorBase
{
private const string SectionArgument = "section";
private const string KeyArgument = "key";
private const string ValueArgument = "value";

public override Guid Id => ActionProcessorId;

internal static Guid ActionProcessorId { get; } = new Guid("597E7933-0D87-452C-B094-8FA0EEF7FD97");

protected override bool ProcessInternal(
IEngineEnvironmentSettings environment,
IPostAction action,
ICreationEffects creationEffects,
ICreationResult templateCreationResult,
string outputBasePath)
{
if (!action.Args.TryGetValue(SectionArgument, out string? sectionName))
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_DotnetConfig_Error_ArgumentNotConfigured, SectionArgument));
return false;
}

if (!action.Args.TryGetValue(KeyArgument, out string? key))
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_DotnetConfig_Error_ArgumentNotConfigured, KeyArgument));
return false;
}

if (!action.Args.TryGetValue(ValueArgument, out string? value))
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_DotnetConfig_Error_ArgumentNotConfigured, ValueArgument));
return false;
}

var fileSystem = environment.Host.FileSystem;
var repoRoot = GetRootDirectory(fileSystem, outputBasePath);
var dotnetConfigFilePath = Path.Combine(repoRoot, "dotnet.config");
if (!fileSystem.FileExists(dotnetConfigFilePath))
{
fileSystem.WriteAllText(dotnetConfigFilePath, $"""
[{sectionName}]
{key} = "{value}"

""");

Reporter.Output.WriteLine(LocalizableStrings.PostAction_CreateDotnetConfig_Succeeded);
return true;
}

var builder = new ConfigurationBuilder();
using var stream = fileSystem.OpenRead(dotnetConfigFilePath);
builder.AddIniStream(stream);
IConfigurationRoot config = builder.Build();
var section = config.GetSection(sectionName);

if (!section.Exists())
{
var existingContent = fileSystem.ReadAllText(dotnetConfigFilePath);
fileSystem.WriteAllText(dotnetConfigFilePath, $"""
{existingContent}

[{sectionName}]
{key} = "{value}"

""");

Reporter.Output.WriteLine(LocalizableStrings.PostAction_CreateDotnetConfig_CreatedNewSection);
return true;
}

string? existingValue = section[key];
if (string.IsNullOrEmpty(existingValue))
{
// The section exists, but the key/value pair does not.
Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_CreateDotnetConfig_ManuallyUpdate, $"{key} = \"{value}\"", $"[{sectionName}]"));
return false;
}

if (existingValue.Equals(value, StringComparison.Ordinal))
{
// The key already exists with the same value, nothing to do.
Reporter.Output.WriteLine(LocalizableStrings.PostAction_CreateDotnetConfig_ValueAlreadyExist);
return true;
}

Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_CreateDotnetConfig_ManuallyUpdate, $"{key} = \"{value}\"", $"[{sectionName}]"));
return false;
}

private static string GetRootDirectory(IPhysicalFileSystem fileSystem, string outputBasePath)
{
string? currentDirectory = outputBasePath;
string? directoryWithSln = null;
while (currentDirectory is not null)
{
if (fileSystem.FileExists(Path.Combine(currentDirectory, "dotnet.config")) ||
fileSystem.DirectoryExists(Path.Combine(currentDirectory, ".git")))
{
return currentDirectory;
}

// DirectoryExists here should always be true in practice, but for the way tests are mocking the file system, it's not.
// The check was added to prevent test failures similar to:
// System.IO.DirectoryNotFoundException : Could not find a part of the path '/Users/runner/work/1/s/artifacts/bin/Microsoft.TemplateEngine.Cli.UnitTests/Release/sandbox'.
// We get to this exception when doing `EnumerateFiles` on a directory that was virtually created in memory (not really available on disk).
// EnumerateFiles tries to access the physical file system, which then fails.
if (fileSystem.DirectoryExists(currentDirectory) &&
(fileSystem.EnumerateFiles(currentDirectory, "*.sln", SearchOption.TopDirectoryOnly).Any() ||
fileSystem.EnumerateFiles(currentDirectory, "*.slnx", SearchOption.TopDirectoryOnly).Any()))
{
directoryWithSln = currentDirectory;
}

currentDirectory = Directory.GetParent(currentDirectory)?.FullName;
}

return directoryWithSln ?? outputBasePath;
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading