Skip to content

Commit

Permalink
implement the feature of changing the name of a model (#4285)
Browse files Browse the repository at this point in the history
Fixes #4256 
Fixes #4261

In order to get our mocking system working properly and make everything
aligned, I changed the `SourceInputModel` to public and added it to the
`CodeModelPlugin` so that our plugin writers could override something on
it to do some advanced stuffs
  • Loading branch information
ArcturusZhang authored Sep 4, 2024
1 parent 04b1986 commit cd6e362
Show file tree
Hide file tree
Showing 17 changed files with 201 additions and 282 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.Generator.CSharp.ClientModel.Providers;
using Microsoft.Generator.CSharp.Input;
using Microsoft.Generator.CSharp.Primitives;
using Microsoft.Generator.CSharp.Providers;
using Microsoft.Generator.CSharp.SourceInput;
using Moq;
using Moq.Protected;

Expand Down Expand Up @@ -96,6 +98,9 @@ public static Mock<ClientModelPlugin> LoadMockPlugin(
mockPluginInstance.Setup(p => p.InputLibrary).Returns(createInputLibrary);
}

var sourceInputModel = new Mock<SourceInputModel>(() => new SourceInputModel(null)) { CallBase = true };
mockPluginInstance.Setup(p => p.SourceInputModel).Returns(sourceInputModel.Object);

codeModelInstance!.SetValue(null, mockPluginInstance.Object);
clientModelInstance!.SetValue(null, mockPluginInstance.Object);
mockPluginInstance.Object.Configure();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Generator.CSharp.Primitives;
using Microsoft.Generator.CSharp.SourceInput;

namespace Microsoft.Generator.CSharp
{
internal sealed class CSharpGen
{
private const string ConfigurationFileName = "Configuration.json";
private const string CodeModelFileName = "tspCodeModel.json";
private const string GeneratedFolderName = "Generated";

private static readonly string[] _filesToKeep = [ConfigurationFileName, CodeModelFileName];

Expand All @@ -25,10 +25,11 @@ public async Task ExecuteAsync()
{
GeneratedCodeWorkspace.Initialize();
var outputPath = CodeModelPlugin.Instance.Configuration.OutputDirectory;
var generatedSourceOutputPath = ParseGeneratedSourceOutputPath(outputPath);
var generatedTestOutputPath = Path.Combine(outputPath, "..", "..", "tests", GeneratedFolderName);
var generatedSourceOutputPath = CodeModelPlugin.Instance.Configuration.ProjectGeneratedDirectory;
var generatedTestOutputPath = CodeModelPlugin.Instance.Configuration.TestGeneratedDirectory;

GeneratedCodeWorkspace workspace = await GeneratedCodeWorkspace.Create();
await CodeModelPlugin.Instance.InitializeSourceInputModelAsync();

var output = CodeModelPlugin.Instance.OutputLibrary;
Directory.CreateDirectory(Path.Combine(generatedSourceOutputPath, "Models"));
Expand Down Expand Up @@ -82,23 +83,6 @@ public async Task ExecuteAsync()
}
}

/// <summary>
/// Parses and updates the output path for the generated code.
/// </summary>
/// <param name="outputPath">The output path.</param>
/// <returns>The parsed output path string.</returns>
internal static string ParseGeneratedSourceOutputPath(string outputPath)
{
if (!outputPath.EndsWith("src", StringComparison.Ordinal) && !outputPath.EndsWith("src/", StringComparison.Ordinal))
{
outputPath = Path.Combine(outputPath, "src");
}

outputPath = Path.Combine(outputPath, GeneratedFolderName);

return outputPath;
}

/// <summary>
/// Clears the output directory specified by <paramref name="path"/>. If <paramref name="filesToKeep"/> is not null,
/// the specified files in the output directory will not be deleted.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Generator.CSharp.Input;
using Microsoft.Generator.CSharp.Primitives;
using Microsoft.Generator.CSharp.Providers;
using Microsoft.Generator.CSharp.SourceInput;

namespace Microsoft.Generator.CSharp
{
Expand Down Expand Up @@ -53,11 +55,11 @@ protected CodeModelPlugin()
}

internal bool IsNewProject { get; set; }

private Lazy<InputLibrary> _inputLibrary;

// Extensibility points to be implemented by a plugin
public virtual TypeFactory TypeFactory { get; }
public virtual SourceInputModel SourceInputModel => _sourceInputModel ?? throw new InvalidOperationException($"SourceInputModel has not been initialized yet");
public virtual string LicenseString => string.Empty;
public virtual OutputLibrary OutputLibrary { get; } = new();
public virtual InputLibrary InputLibrary => _inputLibrary.Value;
Expand All @@ -72,5 +74,12 @@ public virtual void AddVisitor(LibraryVisitor visitor)
{
_visitors.Add(visitor);
}

private SourceInputModel? _sourceInputModel;
internal async Task InitializeSourceInputModelAsync()
{
GeneratedCodeWorkspace existingCode = GeneratedCodeWorkspace.CreateExistingCodeProject(Instance.Configuration.ProjectDirectory, Instance.Configuration.ProjectGeneratedDirectory);
_sourceInputModel = new SourceInputModel(await existingCode.GetCompilationAsync());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class Configuration
"Enum",
];

private const string GeneratedFolderName = "Generated";
private const string ConfigurationFileName = "Configuration.json";

// for mocking
Expand Down Expand Up @@ -144,6 +145,15 @@ private static class Options
private string? _projectDirectory;
internal string ProjectDirectory => _projectDirectory ??= Path.Combine(OutputDirectory, "src");

private string? _testProjectDirectory;
internal string TestProjectDirectory => _testProjectDirectory ??= Path.Combine(OutputDirectory, "tests");

private string? _projectGeneratedDirectory;
internal string ProjectGeneratedDirectory => _projectGeneratedDirectory ??= Path.Combine(ProjectDirectory, GeneratedFolderName);

private string? _testGeneratedDirectory;
internal string TestGeneratedDirectory => _testGeneratedDirectory ??= Path.Combine(TestProjectDirectory, GeneratedFolderName);

internal string LibraryName { get; }

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ public static void Initialize()
_cachedProject = Task.Run(CreateGeneratedCodeProject);
}

internal async Task<CSharpCompilation> GetCompilationAsync()
{
var compilation = await _project.GetCompilationAsync();
Debug.Assert(compilation is CSharpCompilation);

return (CSharpCompilation)compilation;
}

public void AddPlainFiles(string name, string content)
{
PlainFiles.Add(name, content);
Expand Down Expand Up @@ -140,17 +148,18 @@ internal static async Task<GeneratedCodeWorkspace> Create()
return new GeneratedCodeWorkspace(generatedCodeProject);
}

public static GeneratedCodeWorkspace CreateExistingCodeProject(string outputDirectory)
internal static GeneratedCodeWorkspace CreateExistingCodeProject(string projectDirectory, string generatedDirectory)
{
var workspace = new AdhocWorkspace();
var newOptionSet = workspace.Options.WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, _newLine);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(newOptionSet));
Project project = workspace.AddProject("ExistingCode", LanguageNames.CSharp);

if (Path.IsPathRooted(outputDirectory))
if (Path.IsPathRooted(projectDirectory))
{
outputDirectory = Path.GetFullPath(outputDirectory);
project = AddDirectory(project, outputDirectory, null);
projectDirectory = Path.GetFullPath(projectDirectory);

project = AddDirectory(project, projectDirectory, skipPredicate: sourceFile => sourceFile.StartsWith(generatedDirectory));
}

project = project
Expand All @@ -161,7 +170,7 @@ public static GeneratedCodeWorkspace CreateExistingCodeProject(string outputDire
return new GeneratedCodeWorkspace(project);
}

public static async Task<Compilation?> CreatePreviousContractFromDll(string xmlDocumentationpath, string dllPath)
internal static async Task<Compilation?> CreatePreviousContractFromDll(string xmlDocumentationpath, string dllPath)
{
var workspace = new AdhocWorkspace();
Project project = workspace.AddProject("PreviousContract", LanguageNames.CSharp);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.Generator.CSharp.Expressions;
using Microsoft.Generator.CSharp.Primitives;
using Microsoft.Generator.CSharp.Statements;

namespace Microsoft.Generator.CSharp.Providers
{
public class NamedTypeSymbolProvider : TypeProvider
internal sealed class NamedTypeSymbolProvider : TypeProvider
{
private INamedTypeSymbol _namedTypeSymbol;

Expand All @@ -21,6 +20,8 @@ public NamedTypeSymbolProvider(INamedTypeSymbol namedTypeSymbol)
_namedTypeSymbol = namedTypeSymbol;
}

private protected sealed override TypeProvider? GetCustomCodeView() => null;

protected override string BuildRelativeFilePath() => throw new InvalidOperationException("This type should not be writting in generation");

protected override string BuildName() => _namedTypeSymbol.Name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ namespace Microsoft.Generator.CSharp.Providers
{
public abstract class TypeProvider
{
private Lazy<TypeProvider?> _customCodeView;
protected TypeProvider()
{
_customCodeView = new(GetCustomCodeView);
}

private protected virtual TypeProvider? GetCustomCodeView()
=> CodeModelPlugin.Instance.SourceInputModel.FindForType(GetNamespace(), BuildName());

public TypeProvider? CustomCodeView => _customCodeView.Value;

protected string? _deprecated;

/// <summary>
Expand All @@ -22,7 +33,7 @@ public abstract class TypeProvider

private string? _relativeFilePath;

public string Name => _name ??= BuildName();
public string Name => _name ??= CustomCodeView?.Name ?? BuildName();

private string? _name;

Expand All @@ -45,7 +56,7 @@ public string? Deprecated
private CSharpType? _type;
public CSharpType Type => _type ??= new(
this,
GetNamespace(),
CustomCodeView?.GetNamespace() ?? GetNamespace(),
GetTypeArguments(),
GetBaseType());

Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Loading

0 comments on commit cd6e362

Please sign in to comment.