Skip to content

Add PostAction for dotnet.config #50285

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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.

15 changes: 15 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,19 @@ 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>
</data>
<data name="PostAction_CreateDotnetConfig_CreatedNewSection" xml:space="preserve">
<value>Created new section in 'dotnet.config' file</value>
</data>
<data name="PostAction_CreateDotnetConfig_ValueAlreadyExist" xml:space="preserve">
<value>The required value in 'dotnet.config' is already set.</value>
</data>
<data name="PostAction_CreateDotnetConfig_ManuallyUpdate" xml:space="preserve">
<value>Updating existing in 'dotnet.config' is not yet supported. Please, manually update 'dotnet.config' to have '{0}' under section '{1}'.</value>
</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,145 @@
// 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.Output.WriteStdErr(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.Output.WriteStdErr(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 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'.
// at System.IO.Enumeration.FileSystemEnumerator`1.CreateDirectoryHandle(String path, Boolean ignoreNotFound)
// at System.IO.Enumeration.FileSystemEnumerator`1.Init()
// at System.IO.Enumeration.FileSystemEnumerable`1..ctor(String directory, FindTransform transform, EnumerationOptions options, Boolean isNormalized)
// at System.IO.Enumeration.FileSystemEnumerableFactory.UserFiles(String directory, String expression, EnumerationOptions options)
// at System.IO.Directory.InternalEnumeratePaths(String path, String searchPattern, SearchTarget searchTarget, EnumerationOptions enumerationOptions)
// at Microsoft.TemplateEngine.Utils.PhysicalFileSystem.EnumerateFiles(String path, String pattern, SearchOption searchOption)
// at Microsoft.TemplateEngine.TestHelper.MonitoredFileSystem.EnumerateFiles(String path, String pattern, SearchOption searchOption)
// at Microsoft.TemplateEngine.Utils.InMemoryFileSystem.EnumerateFiles(String path, String pattern, SearchOption searchOption)+MoveNext()
// at Microsoft.TemplateEngine.Utils.InMemoryFileSystem.EnumerateFiles(String path, String pattern, SearchOption searchOption)+MoveNext()
// at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)
// at Microsoft.TemplateEngine.Cli.PostActionProcessors.CreateOrUpdateDotnetConfigPostActionProcessor.GetRootDirectory(IPhysicalFileSystem fileSystem, String outputBasePath) in /_/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/CreateOrUpdateDotnetConfigPostActionProcessor.cs:line 113
// at Microsoft.TemplateEngine.Cli.PostActionProcessors.CreateOrUpdateDotnetConfigPostActionProcessor.ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, String outputBasePath) in /_/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/CreateOrUpdateDotnetConfigPostActionProcessor.cs:line 47
// at Microsoft.TemplateEngine.Cli.PostActionProcessors.PostActionProcessorBase.Process(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, String outputBasePath) in /_/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs:line 26
// at Microsoft.TemplateEngine.Cli.UnitTests.PostActionTests.CreateOrUpdateDotnetConfigPostActionTests.CreatesDotnetConfigWhenDoesNotExist() in /Users/runner/work/1/s/test/Microsoft.TemplateEngine.Cli.UnitTests/PostActionTests/CreateOrUpdateDotnetConfigPostActionTests.cs:line 84
// at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
// at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
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.

Loading
Loading