Skip to content

Commit

Permalink
Add configurable comment languages
Browse files Browse the repository at this point in the history
Add System.Xml.Schema namespace to usings
Fix #160
  • Loading branch information
Michael Ganss committed Dec 23, 2020
1 parent d3e7c4a commit aff29bb
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 29 deletions.
8 changes: 7 additions & 1 deletion XmlSchemaClassGenerator.Console/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ static void Main(string[] args)
var collectionSettersMode = CollectionSettersMode.Private;
var doNotForceIsNullable = false;
var compactTypeNames = false;
var commentLanguages = new[] { "en" };
var supportedCommentLanguages = new[] { "en", "de" };

var options = new OptionSet {
{ "h|help", "show this message and exit", v => showHelp = v != null },
Expand Down Expand Up @@ -115,7 +117,9 @@ A file name may be given by appending a pipe sign (|) followed by a file name (l
{ "sf|separateFiles", "generate a separate file for each class (default is false)", v => separateClasses = v != null },
{ "sg|separateSubstitutes", "generate a separate property for each element of a substitution group (default is false)", v => separateSubstitutes = v != null },
{ "dnfin|doNotForceIsNullable", "do not force generator to emit IsNullable = true in XmlElement annotation for nillable elements when element is nullable (minOccurs < 1 or parent element is choice) (default is false)", v => doNotForceIsNullable = v != null },
{ "cn|compactTypeNames", "use type names without namespace qualifier for types in the using list (default is false)", v => compactTypeNames = v != null }
{ "cn|compactTypeNames", "use type names without namespace qualifier for types in the using list (default is false)", v => compactTypeNames = v != null },
{ "cl|commentLanguages=", $"comment languages to use (default is {string.Join(", ", commentLanguages)}; supported are {string.Join(", ", supportedCommentLanguages)})",
v => commentLanguages = v.Split(',').Select(l => l.Trim()).ToArray() }
};

var globsAndUris = options.Parse(args);
Expand Down Expand Up @@ -190,6 +194,8 @@ A file name may be given by appending a pipe sign (|) followed by a file name (l
CompactTypeNames = compactTypeNames
};

generator.CommentLanguages.AddRange(commentLanguages);

if (pclCompatible)
{
generator.UseXElementForAny = true;
Expand Down
5 changes: 4 additions & 1 deletion XmlSchemaClassGenerator.Tests/Compiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,12 @@ public static Assembly GenerateFiles(string name, IEnumerable<string> files, Gen
CollectionType = generatorPrototype.CollectionType,
CollectionImplementationType = generatorPrototype.CollectionImplementationType,
SeparateSubstitutes = generatorPrototype.SeparateSubstitutes,
CompactTypeNames = generatorPrototype.CompactTypeNames
CompactTypeNames = generatorPrototype.CompactTypeNames,
};

gen.CommentLanguages.Clear();
gen.CommentLanguages.AddRange(generatorPrototype.CommentLanguages);

output.Configuration = gen.Configuration;

gen.Generate(files);
Expand Down
6 changes: 5 additions & 1 deletion XmlSchemaClassGenerator.Tests/XmlTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ private static IEnumerable<string> ConvertXml(string name, IEnumerable<string> x
DoNotForceIsNullable = generatorPrototype.DoNotForceIsNullable
};

gen.CommentLanguages.Clear();
gen.CommentLanguages.AddRange(generatorPrototype.CommentLanguages);

var set = new XmlSchemaSet();

foreach (var xsd in xsds)
Expand Down Expand Up @@ -980,7 +983,8 @@ public void ComplexTypeWithAttributeGroupExtension()
NamespaceProvider = new NamespaceProvider
{
GenerateNamespace = key => "Test"
}
},
CommentLanguages = { "de", "en" }
};

var contents = ConvertXml(nameof(ComplexTypeWithAttributeGroupExtension), xsd, generator);
Expand Down
24 changes: 9 additions & 15 deletions XmlSchemaClassGenerator.Tests/XsdElsterDatenabholung5.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,16 @@ public void CanGenerateClasses()
{
GenerateNamespace = key =>
{
switch (Path.GetFileName(key.Source.LocalPath))
return (Path.GetFileName(key.Source.LocalPath)) switch
{
case "th000008_extern.xsd":
case "ndh000010_extern.xsd":
case "headerbasis000002.xsd":
return "Elster.Basis";
case "datenabholung_5.xsd":
case "elster0810_datenabholung_5.xsd":
return key.XmlSchemaNamespace switch
{
"http://www.elster.de/2002/XMLSchema" => "Elster.Datenabholung5",
_ => throw new NotSupportedException(string.Format("Namespace {0} for schema {1}", key.XmlSchemaNamespace, key.Source)),
};
default:
throw new NotSupportedException(string.Format("Namespace {0} for schema {1}", key.XmlSchemaNamespace, key.Source));
}
"th000008_extern.xsd" or "ndh000010_extern.xsd" or "headerbasis000002.xsd" => "Elster.Basis",
"datenabholung_5.xsd" or "elster0810_datenabholung_5.xsd" => key.XmlSchemaNamespace switch
{
"http://www.elster.de/2002/XMLSchema" => "Elster.Datenabholung5",
_ => throw new NotSupportedException(string.Format("Namespace {0} for schema {1}", key.XmlSchemaNamespace, key.Source)),
},
_ => throw new NotSupportedException(string.Format("Namespace {0} for schema {1}", key.XmlSchemaNamespace, key.Source)),
};
}
}
};
Expand Down
1 change: 1 addition & 0 deletions XmlSchemaClassGenerator/CodeUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,7 @@ public static KeyValuePair<NamespaceKey, string> ParseNamespace(string nsArg, st
("System.ComponentModel.DataAnnotations", c => c.CompactTypeNames && (c.DataAnnotationMode != DataAnnotationMode.None || c.EntityFramework)),
("System.Diagnostics", c => c.CompactTypeNames && c.GenerateDebuggerStepThroughAttribute),
("System.Linq", c => c.EnableDataBinding),
("System.Xml.Schema", c => c.CompactTypeNames),
("System.Xml.Serialization", c => c.CompactTypeNames)
};

Expand Down
5 changes: 5 additions & 0 deletions XmlSchemaClassGenerator/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,11 @@ public bool CompactTypeNames
set { _configuration.CompactTypeNames = value; }
}

public List<string> CommentLanguages
{
get { return _configuration.CommentLanguages; }
}

static Generator()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Expand Down
6 changes: 6 additions & 0 deletions XmlSchemaClassGenerator/GeneratorConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -279,5 +280,10 @@ public void WriteLog(string message)
/// Generates type names without namespace qualifiers for namespaces in using list
/// </summary>
public bool CompactTypeNames { get; set; }

/// <summary>
/// The language identifiers comments will be generated for, e.g. "en", "de-DE".
/// </summary>
public List<string> CommentLanguages { get; } = new List<string>();
}
}
24 changes: 13 additions & 11 deletions XmlSchemaClassGenerator/TypeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public static CodeNamespace Generate(string namespaceName, IEnumerable<Namespace
{
var codeNamespace = new CodeNamespace(namespaceName);

foreach (var (Namespace, Condition) in CodeUtilities.UsingNamespaces.Where(n => n.Condition(conf)))
foreach (var (Namespace, Condition) in CodeUtilities.UsingNamespaces.Where(n => n.Condition(conf)).OrderBy(n => n.Namespace))
codeNamespace.Imports.Add(new CodeNamespaceImport(Namespace));

var typeModels = parts.SelectMany(x => x.Types.Values).ToList();
Expand All @@ -62,14 +62,16 @@ public class DocumentationModel
public string Text { get; set; }
public static bool DisableComments { get; set; }

public static IEnumerable<CodeCommentStatement> GetComments(IList<DocumentationModel> docs)
public static IEnumerable<CodeCommentStatement> GetComments(IList<DocumentationModel> docs, GeneratorConfiguration conf)
{
if (DisableComments || docs.Count == 0)
yield break;

yield return new CodeCommentStatement("<summary>", true);

foreach (var doc in docs.OrderBy(d => d.Language))
foreach (var doc in docs
.Where(d => conf.CommentLanguages.Any(l => d.Language.StartsWith(l, StringComparison.OrdinalIgnoreCase)))
.OrderBy(d => d.Language))
{
var text = doc.Text;
var comment = string.Format(@"<para{0}>{1}</para>",
Expand All @@ -84,7 +86,7 @@ public static void AddDescription(CodeAttributeDeclarationCollection attributes,
{
if (!conf.GenerateDescriptionAttribute || DisableComments || !docs.Any()) return;

var doc = GetSingleDoc(docs);
var doc = GetSingleDoc(docs.Where(d => conf.CommentLanguages.Any(l => d.Language.StartsWith(l, StringComparison.OrdinalIgnoreCase))));

if (doc != null)
{
Expand Down Expand Up @@ -127,7 +129,7 @@ public virtual CodeTypeDeclaration Generate()
{
var typeDeclaration = new CodeTypeDeclaration { Name = Name };

typeDeclaration.Comments.AddRange(DocumentationModel.GetComments(Documentation).ToArray());
typeDeclaration.Comments.AddRange(DocumentationModel.GetComments(Documentation, Configuration).ToArray());

DocumentationModel.AddDescription(typeDeclaration.CustomAttributes, Documentation, Configuration);

Expand Down Expand Up @@ -387,7 +389,7 @@ public override CodeTypeDeclaration Generate()
}
}

member.Comments.AddRange(DocumentationModel.GetComments(docs).ToArray());
member.Comments.AddRange(DocumentationModel.GetComments(docs, Configuration).ToArray());

member.CustomAttributes.Add(attribute);
classDeclaration.Members.Add(member);
Expand Down Expand Up @@ -766,7 +768,7 @@ private void AddDocs(CodeTypeMember member)
member.CustomAttributes.AddRange(simpleType.GetRestrictionAttributes().ToArray());
}

member.Comments.AddRange(DocumentationModel.GetComments(docs).ToArray());
member.Comments.AddRange(DocumentationModel.GetComments(docs, Configuration).ToArray());
}

private CodeAttributeDeclaration CreateDefaultValueAttribute(CodeTypeReference typeReference, CodeExpression defaultValueExpression)
Expand Down Expand Up @@ -969,7 +971,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi
specifiedMember.Attributes = MemberAttributes.Public;
var specifiedDocs = new[] { new DocumentationModel { Language = "en", Text = string.Format("Gets or sets a value indicating whether the {0} property is specified.", Name) },
new DocumentationModel { Language = "de", Text = string.Format("Ruft einen Wert ab, der angibt, ob die {0}-Eigenschaft spezifiziert ist, oder legt diesen fest.", Name) } };
specifiedMember.Comments.AddRange(DocumentationModel.GetComments(specifiedDocs).ToArray());
specifiedMember.Comments.AddRange(DocumentationModel.GetComments(specifiedDocs, Configuration).ToArray());
typeDeclaration.Members.Add(specifiedMember);

var specifiedMemberPropertyModel = new PropertyModel(Configuration)
Expand Down Expand Up @@ -1078,7 +1080,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi

var specifiedDocs = new[] { new DocumentationModel { Language = "en", Text = string.Format("Gets a value indicating whether the {0} collection is empty.", Name) },
new DocumentationModel { Language = "de", Text = string.Format("Ruft einen Wert ab, der angibt, ob die {0}-Collection leer ist.", Name) } };
specifiedProperty.Comments.AddRange(DocumentationModel.GetComments(specifiedDocs).ToArray());
specifiedProperty.Comments.AddRange(DocumentationModel.GetComments(specifiedDocs, Configuration).ToArray());

Configuration.MemberVisitor(specifiedProperty, this);

Expand All @@ -1098,7 +1100,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi
constructor = new CodeConstructor { Attributes = MemberAttributes.Public | MemberAttributes.Final };
var constructorDocs = new[] { new DocumentationModel { Language = "en", Text = string.Format(@"Initializes a new instance of the <see cref=""{0}"" /> class.", typeDeclaration.Name) },
new DocumentationModel { Language = "de", Text = string.Format(@"Initialisiert eine neue Instanz der <see cref=""{0}"" /> Klasse.", typeDeclaration.Name) } };
constructor.Comments.AddRange(DocumentationModel.GetComments(constructorDocs).ToArray());
constructor.Comments.AddRange(DocumentationModel.GetComments(constructorDocs, Configuration).ToArray());
typeDeclaration.Members.Add(constructor);
}

Expand Down Expand Up @@ -1341,7 +1343,7 @@ public override CodeTypeDeclaration Generate()
docs.Add(obsolete);
}

member.Comments.AddRange(DocumentationModel.GetComments(docs).ToArray());
member.Comments.AddRange(DocumentationModel.GetComments(docs, Configuration).ToArray());

enumDeclaration.Members.Add(member);
}
Expand Down

0 comments on commit aff29bb

Please sign in to comment.