Skip to content
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

add source generator #281

Draft
wants to merge 9 commits into
base: master
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XMLSchema1"
targetNamespace="mysamplenamespace"
elementFormDefault="qualified"
xmlns="http://tempuri.org/XMLSchema1.xsd"
xmlns:mstns="http://tempuri.org/XMLSchema1.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="MyRootElement">
<xs:complexType id="RootType">
<xs:all>
<xs:element name="Child1">
<xs:simpleType id="Child1Type">
<xs:restriction base="xs:boolean"/>
</xs:simpleType>
</xs:element>
<xs:element name="Child2">
<xs:simpleType id="Child2Type">
<xs:restriction base="xs:string"/>
</xs:simpleType>
</xs:element>
<xs:element name="ComplexChild1">
<xs:complexType id="SomeComplexType">
<xs:all>
<xs:element name="Child11"></xs:element>
</xs:all>
</xs:complexType>
</xs:element>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
21 changes: 21 additions & 0 deletions XmlSchemaClassGenerator.SourceGenerator.Tests/SimpleSchemaTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Xunit;

namespace XmlSchemaClassGenerator.SourceGenerator.Tests
{
public class SimpleSchemaTests
{
[Fact]
public void Compiles()
{
new Sample.Generated.MyRootElement
{
Child1 = true,
Child2 = "foo",
ComplexChild1 = new Sample.Generated.MyRootElementComplexChild1
{
Child11 = null
}
};
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<Import Project="..\XmlSchemaClassGenerator.SourceGenerator\XmlSchemaClassGenerator.SourceGenerator.props"/>

<ItemGroup>
<ProjectReference Include="..\XmlSchemaClassGenerator.SourceGenerator\XmlSchemaClassGenerator.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>

<ItemGroup>
<AdditionalFiles Include="Samples\simple_schema.xsd"
xscgen_SeparateFiles="true"
xscgen_Namespace="Sample.Generated" />
</ItemGroup>

<ItemGroup>
<Content Update="Samples\simple_schema.xsd">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<IncludeBuildOutput>false</IncludeBuildOutput>
<NoPackageAnalysis>true</NoPackageAnalysis>

<PackageId>XmlSchemaClassGenerator.SourceGenerator</PackageId>
<Authors>Sven Hübner</Authors>
<Description>Source generator for POCOs from XSD schema files, based on XmlSchemaClassGenerator</Description>
<PackageTags>xml;xsd;Schema;Source Generator;poco;XmlSchemaClassGenerator</PackageTags>
<PackageProjectUrl>https://github.com/mganss/XmlSchemaClassGenerator</PackageProjectUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>git://github.com/mganss/XmlSchemaClassGenerator</RepositoryUrl>
<RootNamespace>XmlSchemaClassGenerator</RootNamespace>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\XmlSchemaClassGenerator\XmlSchemaClassGenerator.csproj" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.CodeDom" Version="6.0.0" PrivateAssets="all" GeneratePathProperty="true" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0" PrivateAssets="all" GeneratePathProperty="true" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" PrivateAssets="all" GeneratePathProperty="true" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" PrivateAssets="all" GeneratePathProperty="true" />
<PackageReference Include="System.Collections.Immutable" Version="5.0.0" PrivateAssets="all" GeneratePathProperty="true" />
<PackageReference Include="System.Memory" Version="4.5.4" PrivateAssets="all" GeneratePathProperty="true" />
</ItemGroup>

<PropertyGroup>
<GetTargetPathDependsOn>$(GetTargetPathDependsOn);GetDependencyTargetPaths</GetTargetPathDependsOn>
</PropertyGroup>

<Target Name="GetDependencyTargetPaths">
<ItemGroup>
<TargetPathWithTargetPlatformMoniker Include="..\XmlSchemaClassGenerator\bin\$(Configuration)\$(TargetFramework)\XmlSchemaClassGenerator.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGSystem_CodeDom)\lib\netstandard2.0\System.CodeDom.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGSystem_Text_Encoding_CodePages)\lib\netstandard2.0\System.Text.Encoding.CodePages.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGSystem_ValueTuple)\lib\netstandard1.0\System.ValueTuple.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGSystem_Runtime_CompilerServices_Unsafe)\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGSystem_Collections_Immutable)\lib\netstandard2.0\System.Collections.Immutable.dll" IncludeRuntimeDependency="false" />
<TargetPathWithTargetPlatformMoniker Include="$(PKGSystem_Memory)\lib\netstandard2.0\System.Memory.dll" IncludeRuntimeDependency="false" />
</ItemGroup>
</Target>

<ItemGroup>
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="..\XmlSchemaClassGenerator\bin\$(Configuration)\$(TargetFramework)\XmlSchemaClassGenerator.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(PKGSystem_CodeDom)\lib\netstandard2.0\System.CodeDom.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(PKGSystem_Text_Encoding_CodePages)\lib\netstandard2.0\System.Text.Encoding.CodePages.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(PKGSystem_ValueTuple)\lib\netstandard1.0\System.ValueTuple.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(PKGSystem_Runtime_CompilerServices_Unsafe)\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(PKGSystem_Collections_Immutable)\lib\netstandard2.0\System.Collections.Immutable.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(PKGSystem_Memory)\lib\netstandard2.0\System.Memory.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />

<None Include="XmlSchemaClassGenerator.SourceGenerator.props" Pack="true" PackagePath="build/$(PackageId).props" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<Project>
<ItemGroup>
<CompilerVisibleItemMetadata Include="AdditionalFiles" MetadataName="xscgen_Namespace" />
<CompilerVisibleItemMetadata Include="AdditionalFiles" MetadataName="xscgen_SeparateFiles" />
<CompilerVisibleItemMetadata Include="AdditionalFiles" MetadataName="xscgen_Prefix" />
</ItemGroup>
</Project>
171 changes: 171 additions & 0 deletions XmlSchemaClassGenerator.SourceGenerator/XsdSourceGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;

namespace XmlSchemaClassGenerator
{
[Generator]
public class XsdSourceGenerator : ISourceGenerator
{
internal class MemoryOutputWriter : OutputWriter
{
private readonly bool separateFiles;
private readonly string schemaFileName;
private readonly string prefix;

public ICollection<(string Name, string Content)> Contents { get; private set; } = new List<(string, string)>();

public MemoryOutputWriter(bool separateFiles, string schemaFileName, string prefix)
{
this.separateFiles = separateFiles;
this.schemaFileName = schemaFileName;
this.prefix = prefix;
}

public override void Write(CodeNamespace cn)
{
var cu = new CodeCompileUnit();
cu.Namespaces.Add(cn);

if (separateFiles)
{
WriteSeparateFiles(cn);
}
else
{
using (var writer = new StringWriter())
{
Write(writer, cu);
Contents.Add(($"{this.prefix ?? string.Empty}{this.schemaFileName}.g.cs", writer.ToString()));
}
}
}

private void WriteSeparateFiles(CodeNamespace cn)
{
var validName = GetSanitizedName(cn.Name);
var ccu = new CodeCompileUnit();
var cns = new CodeNamespace(validName);

cns.Imports.AddRange(cn.Imports.Cast<CodeNamespaceImport>().ToArray());
cns.Comments.AddRange(cn.Comments);
ccu.Namespaces.Add(cns);

foreach (CodeTypeDeclaration ctd in cn.Types)
{
var contentName = ctd.Name;
cns.Types.Clear();
cns.Types.Add(ctd);
using (var writer = new StringWriter())
{
Write(writer, ccu);
Contents.Add(($"{this.prefix ?? string.Empty}{contentName}.g.cs", writer.ToString()));
}
}
}

static readonly Regex InvalidCharacters = new Regex($"[{string.Join("", Path.GetInvalidFileNameChars())}]", RegexOptions.Compiled);

private string GetSanitizedName(string name) => InvalidCharacters.Replace(name, "_");
}

public void Execute(GeneratorExecutionContext context)
{
#if DEBUG
if (!Debugger.IsAttached)
{
// Debugger.Launch();
}
#endif
var sources = GetConfigurations(context);

foreach (var source in sources)
{
var schemaStr = source.AdditionalText.GetText().ToString();
var stringReader = new StringReader(schemaStr);

var schemaSet = new XmlSchemaSet();
schemaSet.Add(null, XmlReader.Create(stringReader));

var generator = new Generator();
generator.NamespaceProvider.Add(new NamespaceKey(), source.Namespace);
generator.SeparateClasses = source.GenerateSeparateFiles;
MemoryOutputWriter memoryOutputWriter = new MemoryOutputWriter(
source.GenerateSeparateFiles,
Path.GetFileNameWithoutExtension(source.AdditionalText.Path),
source.Prefix);
generator.OutputWriter = memoryOutputWriter;
generator.Generate(schemaSet);

foreach (var (name, content) in memoryOutputWriter.Contents)
{
context.AddSource(name, content);
}
}
}

public void Initialize(GeneratorInitializationContext context)
{
// do nothing
}

static IEnumerable<GenerationSource> GetConfigurations(GeneratorExecutionContext context)
{
foreach (AdditionalText file in context.AdditionalFiles)
{
AnalyzerConfigOptions fileOptions = context.AnalyzerConfigOptions.GetOptions(file);
if (!fileOptions.TryGetValue("build_metadata.AdditionalFiles.xscgen_namespace", out var @namespace))
{
@namespace = "Generated";
}

if (!fileOptions.TryGetValue("build_metadata.AdditionalFiles.xscgen_prefix", out var prefix))
{
prefix = null;
}

bool generateSeparateFiles =
fileOptions.TryGetValue("build_metadata.AdditionalFiles.xscgen_separatefiles", out var generateSeparateFilesStr) &&
bool.TryParse(generateSeparateFilesStr, out var parsedGenerateSeparateFiles) &&
parsedGenerateSeparateFiles;

if (Path.GetExtension(file.Path).Equals(".xsd", StringComparison.OrdinalIgnoreCase))
{
yield return new GenerationSource(
file,
@namespace,
generateSeparateFiles,
prefix);
}
}
}

sealed class GenerationSource
{
public GenerationSource(
AdditionalText additionalText,
string @namespace,
bool generateSeparateFiles,
string prefix)
{
AdditionalText = additionalText;
Namespace = @namespace;
GenerateSeparateFiles = generateSeparateFiles;
Prefix = prefix;
}

public AdditionalText AdditionalText { get; }
public string Namespace { get; }
public bool GenerateSeparateFiles { get; }
public string Prefix { get; }
}
}
}
12 changes: 12 additions & 0 deletions XmlSchemaClassGenerator.sln
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "xscgen-proj", "xscgen-proj\xscgen-proj.csproj", "{2F20FF02-12AB-448B-BC78-DD76DD4C9E66}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XmlSchemaClassGenerator.SourceGenerator", "XmlSchemaClassGenerator.SourceGenerator\XmlSchemaClassGenerator.SourceGenerator.csproj", "{1A4760D7-7618-41E8-BC97-C68566B7A16C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XmlSchemaClassGenerator.SourceGenerator.Tests", "XmlSchemaClassGenerator.SourceGenerator.Tests\XmlSchemaClassGenerator.SourceGenerator.Tests.csproj", "{333F3108-2714-4706-ABA7-4298EFEBFCA7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -50,6 +54,14 @@ Global
{2F20FF02-12AB-448B-BC78-DD76DD4C9E66}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2F20FF02-12AB-448B-BC78-DD76DD4C9E66}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2F20FF02-12AB-448B-BC78-DD76DD4C9E66}.Release|Any CPU.Build.0 = Release|Any CPU
{1A4760D7-7618-41E8-BC97-C68566B7A16C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1A4760D7-7618-41E8-BC97-C68566B7A16C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1A4760D7-7618-41E8-BC97-C68566B7A16C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1A4760D7-7618-41E8-BC97-C68566B7A16C}.Release|Any CPU.Build.0 = Release|Any CPU
{333F3108-2714-4706-ABA7-4298EFEBFCA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{333F3108-2714-4706-ABA7-4298EFEBFCA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{333F3108-2714-4706-ABA7-4298EFEBFCA7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{333F3108-2714-4706-ABA7-4298EFEBFCA7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
2 changes: 1 addition & 1 deletion XmlSchemaClassGenerator/XmlSchemaClassGenerator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="System.Collections.Immutable" Version="6.0.0" />
<PackageReference Include="System.Collections.Immutable" Version="5.0.0" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup>
Expand Down