Skip to content

Commit

Permalink
chore: refactor for modern Roslyn best practices
Browse files Browse the repository at this point in the history
  • Loading branch information
dansiegel committed Sep 1, 2024
1 parent b9cdc92 commit b75a606
Show file tree
Hide file tree
Showing 18 changed files with 188 additions and 68 deletions.
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
<PackageVersion Include="System.Numerics.Vectors" Version="4.5.0" />
<PackageVersion Include="System.ObjectModel" Version="4.3.0" />
<PackageVersion Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
<PackageVersion Include="System.Text.Json" Version="8.0.4" />
<PackageVersion Include="System.Text.Json" Version="8.0.0" />
<PackageVersion Include="McMaster.Extensions.CommandLineUtils" Version="4.1.1" />
</ItemGroup>
<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
<PackageReference Include="Microsoft.Build" Pack="false" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Pack="false" />
<PackageReference Include="NuGetizer" PrivateAssets="all" />
<PackageReference Include="PolySharp">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Linq;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text.Json;
using CodeGenHelpers;
using Microsoft.CodeAnalysis;
using Mobile.BuildTools.AppSettings.Diagnostics;
Expand All @@ -16,7 +17,7 @@ namespace Mobile.BuildTools.AppSettings.Generators
[Generator]
public sealed class AppSettingsGenerator : GeneratorBase
{
private const string _autoGeneratedMessage = @"This code was generated by Mobile.BuildTools. For more information please visit
public const string AutoGeneratedMessage = @"This code was generated by Mobile.BuildTools. For more information please visit
https://mobilebuildtools.com or to file an issue please see
https://github.com/dansiegel/Mobile.BuildTools
Expand All @@ -30,11 +31,12 @@ the code is regenerated.

protected override void Generate()
{
var settings = ConfigHelper.GetSettingsConfig(this);
var settings = ConfigHelper.GetSettingsConfig(ProjectName, Config);
if (settings is null || !settings.Any())
return;

int i = 0;
var i = 0;

var assembly = typeof(AppSettingsGenerator).Assembly;
var toolVersion = FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion;
var compileGeneratedAttribute = @$"[GeneratedCodeAttribute(""{typeof(AppSettingsGenerator).FullName}"", ""{toolVersion}"")]";
Expand Down Expand Up @@ -87,7 +89,7 @@ protected override void Generate()
.WithAccessModifier(settingsConfig.Accessibility.ToRoslynAccessibility())
.MakeStaticClass();

IEnumerable<INamedTypeSymbol> interfaces = Array.Empty<INamedTypeSymbol>();
IEnumerable<INamedTypeSymbol> interfaces = [];
if(typeSymbol != null)
{
if (typeSymbol.IsStatic)
Expand All @@ -99,7 +101,7 @@ protected override void Generate()
builder.AddNamespaceImport("System")
.AddNamespaceImport("GeneratedCodeAttribute = System.CodeDom.Compiler.GeneratedCodeAttribute")
.Builder
.WithAutoGeneratedMessage(_autoGeneratedMessage);
.WithAutoGeneratedMessage(AutoGeneratedMessage);

foreach(var valueConfig in settingsConfig.Properties)
{
Expand All @@ -117,7 +119,7 @@ private void AddProperty(ref ClassBuilder builder, IDictionary<string, string> s

var value = secrets[valueConfig.Name];
var output = string.Empty;
var isArray = valueConfig.IsArray.HasValue ? valueConfig.IsArray.Value : false;
var isArray = valueConfig.IsArray ?? false;
var mapping = valueConfig.PropertyType.GetPropertyTypeMapping();
var valueHandler = mapping.Handler;
var typeDeclaration = mapping.Type.GetStandardTypeName();
Expand Down Expand Up @@ -180,13 +182,11 @@ private void AddProperty(ref ClassBuilder builder, IDictionary<string, string> s
}
}

private string[] GetValueArray(string value, string delimeter)
{
return value.Split(delimeter[0])
private string[] GetValueArray(string value, string delimeter) =>
value.Split(delimeter[0])
.Select(x => x.Trim())
.Where(x => !string.IsNullOrEmpty(x))
.ToArray();
}

private CodeGenHelpers.ValueType GetValueType(string value, PropertyType propertyType)
{
Expand All @@ -204,12 +204,25 @@ private CodeGenHelpers.ValueType GetValueType(string value, PropertyType propert
}
}

private IDictionary<string, string> GetEnvironmentSettings()
{
var buildToolsEnvFile = GeneratorContext.AdditionalFiles.FirstOrDefault(x => Path.GetFileName(x.Path) == Constants.BuildToolsEnvironmentSettings);
if (buildToolsEnvFile is null)
return new Dictionary<string, string>();

var json = buildToolsEnvFile.GetText().ToString();
if (string.IsNullOrEmpty(json))
return new Dictionary<string, string>();

return JsonSerializer.Deserialize<BuildEnvironment>(json).Environment;
}

internal IDictionary<string, string> GetMergedSecrets(SettingsConfig settingsConfig, out bool hasErrors)
{
if (string.IsNullOrEmpty(settingsConfig.Prefix))
settingsConfig.Prefix = "BuildTools_";

var env = EnvironmentAnalyzer.GatherEnvironmentVariables(this);
var env = GetEnvironmentSettings();
var secrets = new Dictionary<string, string>();
hasErrors = false;
foreach (var prop in settingsConfig.Properties)
Expand Down
51 changes: 16 additions & 35 deletions src/Mobile.BuildTools.AppSettings/Generators/GeneratorBase.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using CodeGenHelpers;
using Microsoft.CodeAnalysis;
using Mobile.BuildTools.AppSettings.Diagnostics;
using Mobile.BuildTools.Build;
using Mobile.BuildTools.Logging;
using Mobile.BuildTools.Models;
using Mobile.BuildTools.Models.Settings;
using Mobile.BuildTools.Utils;

namespace Mobile.BuildTools.AppSettings.Generators
{
public abstract class GeneratorBase : ISourceGenerator, IBuildConfiguration
public abstract class GeneratorBase : ISourceGenerator
{
private GeneratorExecutionContext _context;
protected GeneratorExecutionContext GeneratorContext { get; private set; }
private string _configurationPath;

Check warning on line 13 in src/Mobile.BuildTools.AppSettings/Generators/GeneratorBase.cs

View workflow job for this annotation

GitHub Actions / build / Build Mobile.BuildTools

The field 'GeneratorBase._configurationPath' is never used
private string _buildConfiguration;
private string _intermediateOutputDir;
Expand All @@ -28,24 +24,10 @@ public abstract class GeneratorBase : ISourceGenerator, IBuildConfiguration
protected string ProjectDirectory => _projectDirectory;
protected string SolutionDirectory { get; private set; }
protected BuildToolsConfig Config { get; private set; }
protected IBuildConfiguration BuildConfiguration => this;

string IBuildConfiguration.BuildConfiguration => _buildConfiguration;
bool IBuildConfiguration.BuildingInsideVisualStudio { get; }
IDictionary<string, string> IBuildConfiguration.GlobalProperties => _props;
string IBuildConfiguration.ProjectName => ProjectName;
string IBuildConfiguration.ProjectDirectory => ProjectDirectory;
string IBuildConfiguration.SolutionDirectory => SolutionDirectory;

// This shouldn't be an issue for the Source Generator
string IBuildConfiguration.IntermediateOutputPath => _intermediateOutputDir;
ILog IBuildConfiguration.Logger => new ConsoleLogger();
BuildToolsConfig IBuildConfiguration.Configuration => Config;
Utils.Platform IBuildConfiguration.Platform => _targetFrameworkAssembly.GetTargetPlatform();

public void Execute(GeneratorExecutionContext context)
{
_context = context;
GeneratorContext = context;

if (!TryGet(context, "MSBuildProjectName", ref _projectName)
|| !TryGet(context, "MSBuildProjectDirectory", ref _projectDirectory)
Expand All @@ -55,9 +37,14 @@ public void Execute(GeneratorExecutionContext context)
|| !TryGet(context, "IntermediateOutputPath", ref _intermediateOutputDir))
return;

SolutionDirectory = EnvironmentAnalyzer.LocateSolution(ProjectDirectory);
_configurationPath = ConfigHelper.GetConfigurationPath(ProjectDirectory);
Config = ConfigHelper.GetConfig(_configurationPath);
//SolutionDirectory = EnvironmentAnalyzer.LocateSolution(ProjectDirectory);
//_configurationPath = ConfigHelper.GetConfigurationPath(ProjectDirectory);
var buildToolsConfig = context.AdditionalFiles.FirstOrDefault(x => Path.GetFileName(x.Path) == Constants.BuildToolsConfigFileName);
if (buildToolsConfig is null)
return;

var json = buildToolsConfig.GetText().ToString();
Config = JsonSerializer.Deserialize<BuildToolsConfig>(json, ConfigHelper.GetSerializerSettings());

try
{
Expand Down Expand Up @@ -100,25 +87,19 @@ public void Initialize(GeneratorInitializationContext context)

protected bool TryGetTypeSymbol(string fullyQualifiedTypeName, out INamedTypeSymbol typeSymbol)
{
typeSymbol = _context.Compilation.GetTypeByMetadataName(fullyQualifiedTypeName);
typeSymbol = GeneratorContext.Compilation.GetTypeByMetadataName(fullyQualifiedTypeName);
return typeSymbol != null;
}

protected void AddSource(ClassBuilder builder)
{
_context.ReportDiagnostic(Diagnostic.Create(Descriptors.CreatedClass, null, builder.FullyQualifiedName));
_context.AddSource(builder.FullyQualifiedName, builder.Build());
GeneratorContext.ReportDiagnostic(Diagnostic.Create(Descriptors.CreatedClass, null, builder.FullyQualifiedName));
GeneratorContext.AddSource(builder.FullyQualifiedName, builder.Build());
}

protected void ReportDiagnostic(DiagnosticDescriptor descriptor, params string[] messageArgs)
{
_context.ReportDiagnostic(Diagnostic.Create(descriptor, null, messageArgs));
GeneratorContext.ReportDiagnostic(Diagnostic.Create(descriptor, null, messageArgs));
}

void IBuildConfiguration.SaveConfiguration() =>
ConfigHelper.SaveConfig(Config, _configurationPath);

IEnumerable<SettingsConfig> IBuildConfiguration.GetSettingsConfig() =>
ConfigHelper.GetSettingsConfig(this);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,20 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackFolder>analyzers\dotnet\cs</PackFolder>
<IncludeSource>false</IncludeSource>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<DefineConstants>$(DefineConstants);ANALYZERS</DefineConstants>
</PropertyGroup>

<ItemGroup>
<None Update="build\**" Pack="true" PackagePath="build\%(Filename)%(Extension)" />
<Compile Include="..\Mobile.BuildTools.Reference\Build\**\*.cs" LinkBase="Reference\Build" />
<MBTReferenceExclude Include="..\Mobile.BuildTools.Reference\Utils\CIBuildEnvironmentUtils.cs" Visible="false" />
<MBTReferenceExclude Include="..\Mobile.BuildTools.Reference\Utils\EnvironmentAnalyzer.cs" Visible="false" />
<MBTReferenceExclude Include="..\Mobile.BuildTools.Reference\Utils\ImageSearchUtil.cs" Visible="false" />

<Compile Include="..\Mobile.BuildTools.Reference\Extensions\**\*.cs" LinkBase="Reference\Extensions" />
<Compile Include="..\Mobile.BuildTools.Reference\Handlers\**\*.cs" LinkBase="Reference\Handlers" />
<Compile Include="..\Mobile.BuildTools.Reference\Logging\**\*.cs" LinkBase="Reference\Logging" />
<Compile Include="..\Mobile.BuildTools.Reference\Models\**\*.cs" LinkBase="Reference\Models" />
<Compile Include="..\Mobile.BuildTools.Reference\Utils\**\*.cs" LinkBase="Reference\Utils" />
<Compile Include="..\Mobile.BuildTools.Reference\Utils\**\*.cs" LinkBase="Reference\Utils" Exclude="@(MBTReferenceExclude)" />
<Compile Include="..\Mobile.BuildTools.Reference\Constants.cs" Link="Reference\Constants.cs" />
</ItemGroup>

Expand All @@ -29,13 +33,19 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.Common" PrivateAssets="all" Pack="false" />
<PackageReference Include="System.Text.Json" PrivateAssets="all" />
<PackageReference Include="PolySharp">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Text.Json" PrivateAssets="all" NoWarn="NU1903" />
<PackageReference Include="NuGetizer" PrivateAssets="all" />
</ItemGroup>

<Target Name="ExcludeTFM"
BeforeTargets="_AddPackageManifest"
AfterTargets="InferPackageContents">
<ItemGroup>
<ProjectReference Include="..\Mobile.BuildTools.Core\Mobile.BuildTools.Core.csproj" ReferenceOutputAssembly="False" />
</ItemGroup>

<Target Name="ExcludeTFM" BeforeTargets="_AddPackageManifest" AfterTargets="InferPackageContents">
<PropertyGroup>
<IsPackagingProject>true</IsPackagingProject>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
<PackageReference Include="Microsoft.Build" Pack="false" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Pack="false" />
<PackageReference Include="NuGetizer" PrivateAssets="all" />
<PackageReference Include="PolySharp">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net8.0;net8.0-android;net8.0-ios;net8.0-macos;net8.0-maccatalyst</TargetFrameworks>
Expand Down Expand Up @@ -69,10 +69,6 @@
<Compile Include="**/*.tizen.cs" />
</ItemGroup>

<ItemGroup>
<None Include="buildTransitive\*.props" Pack="true" PackagePath="buildTransitive\%(Filename)%(Extension)" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="NuGetizer" PrivateAssets="all" />
<ProjectReference Include="..\Mobile.BuildTools.Core\Mobile.BuildTools.Core.csproj"
Expand Down
7 changes: 5 additions & 2 deletions src/Mobile.BuildTools.Core/Mobile.BuildTools.Core.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net472</TargetFramework>
Expand All @@ -11,14 +11,17 @@
</PropertyGroup>

<ItemGroup>
<None Update="buildTransitive\$(MSBuildProjectName).props;buildTransitive\$(MSBuildProjectName).targets" Pack="True" PackFolder="buildTransitive" />
<InternalsVisibleTo Include="Mobile.BuildTools.Tests" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Build" Pack="false" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Pack="false" />
<PackageReference Include="NuGetizer" PrivateAssets="all" />
<PackageReference Include="PolySharp">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
Expand Down
27 changes: 26 additions & 1 deletion src/Mobile.BuildTools.Core/Package.targets
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
AssemblyFile="$(_MobileBuildToolsCoreParentBuildTasksDll)"/>
<UsingTask TaskName="Mobile.BuildTools.Tasks.GoogleTask"
AssemblyFile="$(_MobileBuildToolsCoreParentBuildTasksDll)"/>
<UsingTask TaskName="Mobile.BuildTools.Tasks.EnvironmentSettingsTask"
AssemblyFile="$(_MobileBuildToolsCoreParentBuildTasksDll)"/>

<Target Name="MobileBuildToolsInit"
BeforeTargets="CoreCompile;_CoreXamlG;XamlG;XamlC;Build;"
Expand All @@ -18,7 +20,7 @@
</Target>

<Target Name="_LocateBuildToolsConfig"
BeforeTargets="CoreCompile">
BeforeTargets="CoreCompile;GenerateMSBuildEditorConfigFileShouldRun;GenerateMSBuildEditorConfigFileCore">
<LocateBuildToolsConfigTask ProjectDir="$(MSBuildProjectDirectory)"
ProjectName="$(MSBuildProjectName)"
SolutionDir="$(SolutionDir)"
Expand All @@ -42,6 +44,29 @@
<Output TaskParameter="EnableTemplateManifests"
PropertyName="BuildToolsEnableTemplateManifests" />
</LocateBuildToolsConfigTask>

<ItemGroup>
<AdditionalFiles Include="$(BuildToolsConfigFilePath)" />
</ItemGroup>
</Target>

<Target Name="_ConfigureBuildToolsAppSettingsEnvironment"
AfterTargets="_LocateBuildToolsConfig"
BeforeTargets="CoreCompile;GenerateMSBuildEditorConfigFileShouldRun;GenerateMSBuildEditorConfigFileCore">
<EnvironmentSettingsTask ConfigurationPath="$(BuildToolsConfigFilePath)"
ProjectName="$(MSBuildProjectName)"
ProjectDirectory="$(MSBuildProjectDirectory)"
SolutionDirectory="$(SolutionDir)"
Configuration="$(Configuration)"
IntermediateOutputPath="$(IntermediateOutputPath)"
TargetFrameworkIdentifier="$(TargetFrameworkIdentifier)">
<Output TaskParameter="EnvironmentSettings"
ItemName="BuildToolsEnvironmentSettings" />
</EnvironmentSettingsTask>

<ItemGroup>
<AdditionalFiles Include="$(BuildToolsEnvironmentSettings)" />
</ItemGroup>
</Target>

<Target Name="CIEnvironmentDump">
Expand Down
Loading

0 comments on commit b75a606

Please sign in to comment.