From 5ed1eb4b3ab8e0d7e60be0d348f550b7bbd7f015 Mon Sep 17 00:00:00 2001 From: Trais McAllister Date: Mon, 19 Jun 2023 15:14:40 -0700 Subject: [PATCH] Refactored Scriban templates - Removed Scriban template abstracts into separate library - Referenced new Scriban library --- .../Models/ExampleClass.cs | 4 +- .../Models/ExampleEnum.cs | 2 +- ...nectTranspiler.Sinks.CSharp.Example.csproj | 2 +- .../Program.cs | 3 +- .../Transpiler.cs | 2 +- .../Attributes/ScribanTemplateAttribute.cs | 25 --- .../CsharpTranspiler.cs | 207 +----------------- .../IncludeSharedTemplates.cs | 49 ----- .../Models/Class.cs | 2 +- .../Models/Enum.cs | 2 +- .../Models/IFileSource.cs | 20 -- .../Models/MTConnectHelperMethods.cs | 63 ------ .../Models/ScribanHelperMethods.cs | 201 +---------------- .../Models/Summary.cs | 2 +- .../MtconnectTranspiler.Sinks.CSharp.csproj | 3 +- .../MtconnectVersionedObject.cs | 1 + 16 files changed, 20 insertions(+), 568 deletions(-) delete mode 100644 MtconnectTranspiler.Sinks.CSharp/Attributes/ScribanTemplateAttribute.cs delete mode 100644 MtconnectTranspiler.Sinks.CSharp/IncludeSharedTemplates.cs delete mode 100644 MtconnectTranspiler.Sinks.CSharp/Models/IFileSource.cs delete mode 100644 MtconnectTranspiler.Sinks.CSharp/Models/MTConnectHelperMethods.cs diff --git a/MtconnectTranspiler.Sinks.CSharp.Example/Models/ExampleClass.cs b/MtconnectTranspiler.Sinks.CSharp.Example/Models/ExampleClass.cs index 3998a5e6..73fc315c 100644 --- a/MtconnectTranspiler.Sinks.CSharp.Example/Models/ExampleClass.cs +++ b/MtconnectTranspiler.Sinks.CSharp.Example/Models/ExampleClass.cs @@ -1,5 +1,5 @@ -using MtconnectTranspiler.Sinks.CSharp.Attributes; -using MtconnectTranspiler.Sinks.CSharp.Models; +using MtconnectTranspiler.Sinks.CSharp.Models; +using MtconnectTranspiler.Sinks.ScribanTemplates; using MtconnectTranspiler.Xmi; using MtconnectTranspiler.Xmi.UML; diff --git a/MtconnectTranspiler.Sinks.CSharp.Example/Models/ExampleEnum.cs b/MtconnectTranspiler.Sinks.CSharp.Example/Models/ExampleEnum.cs index bcb98105..b8021139 100644 --- a/MtconnectTranspiler.Sinks.CSharp.Example/Models/ExampleEnum.cs +++ b/MtconnectTranspiler.Sinks.CSharp.Example/Models/ExampleEnum.cs @@ -1,4 +1,4 @@ -using MtconnectTranspiler.Sinks.CSharp.Attributes; +using MtconnectTranspiler.Sinks.ScribanTemplates; using MtconnectTranspiler.Xmi; using MtconnectTranspiler.Xmi.UML; diff --git a/MtconnectTranspiler.Sinks.CSharp.Example/MtconnectTranspiler.Sinks.CSharp.Example.csproj b/MtconnectTranspiler.Sinks.CSharp.Example/MtconnectTranspiler.Sinks.CSharp.Example.csproj index ce5134a0..e081829c 100644 --- a/MtconnectTranspiler.Sinks.CSharp.Example/MtconnectTranspiler.Sinks.CSharp.Example.csproj +++ b/MtconnectTranspiler.Sinks.CSharp.Example/MtconnectTranspiler.Sinks.CSharp.Example.csproj @@ -10,7 +10,7 @@ - + diff --git a/MtconnectTranspiler.Sinks.CSharp.Example/Program.cs b/MtconnectTranspiler.Sinks.CSharp.Example/Program.cs index c188cf52..0331fdb3 100644 --- a/MtconnectTranspiler.Sinks.CSharp.Example/Program.cs +++ b/MtconnectTranspiler.Sinks.CSharp.Example/Program.cs @@ -1,6 +1,7 @@ using ConsoulLibrary; using Microsoft.Extensions.Logging; using MtconnectTranspiler; +using MtconnectTranspiler.Sinks; using MtconnectTranspiler.Sinks.CSharp.Example; internal class Program @@ -18,7 +19,7 @@ private static void Main(string[] args) var logFactory = LoggerFactory.Create((o) => o.AddConsoulLogger()); var dispatchLogger = logFactory.CreateLogger(); - var transpilerLogger = logFactory.CreateLogger(); + var transpilerLogger = logFactory.CreateLogger(); // NOTE: The GitHubRelease can be a reference to a specific tag referring to the version in which to download. diff --git a/MtconnectTranspiler.Sinks.CSharp.Example/Transpiler.cs b/MtconnectTranspiler.Sinks.CSharp.Example/Transpiler.cs index aaf04b8c..7c5e4ba2 100644 --- a/MtconnectTranspiler.Sinks.CSharp.Example/Transpiler.cs +++ b/MtconnectTranspiler.Sinks.CSharp.Example/Transpiler.cs @@ -20,7 +20,7 @@ internal class Transpiler : CsharpTranspiler /// /// /// - public Transpiler(string projectPath, ILogger? logger = default) : base(projectPath, logger) { } + public Transpiler(string projectPath, ILogger? logger = default) : base(projectPath, logger) { } public override void Transpile(XmiDocument model, CancellationToken cancellationToken = default) { diff --git a/MtconnectTranspiler.Sinks.CSharp/Attributes/ScribanTemplateAttribute.cs b/MtconnectTranspiler.Sinks.CSharp/Attributes/ScribanTemplateAttribute.cs deleted file mode 100644 index ab1a7376..00000000 --- a/MtconnectTranspiler.Sinks.CSharp/Attributes/ScribanTemplateAttribute.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace MtconnectTranspiler.Sinks.CSharp.Attributes -{ - /// - /// An attribute used to relate a class with a Scriban-formatted template contained in the "Templates" folder of the project. - /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - public class ScribanTemplateAttribute : Attribute - { - /// - /// Reference to the filename within the "Templates" folder to pull the Scriban template. - /// - public string Filename { get; } - - /// - /// Constructs a new to reference a Scriban template relative to an entity. - /// - /// - public ScribanTemplateAttribute(string filename) - { - Filename = filename; - } - } -} diff --git a/MtconnectTranspiler.Sinks.CSharp/CsharpTranspiler.cs b/MtconnectTranspiler.Sinks.CSharp/CsharpTranspiler.cs index 2538260c..d0b5bb0b 100644 --- a/MtconnectTranspiler.Sinks.CSharp/CsharpTranspiler.cs +++ b/MtconnectTranspiler.Sinks.CSharp/CsharpTranspiler.cs @@ -1,215 +1,18 @@ -using MtconnectTranspiler.Sinks.CSharp.Attributes; -using MtconnectTranspiler.Sinks.CSharp.Models; -using Scriban; -using Scriban.Runtime; -using System.Collections.Generic; -using System; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Threading; -using Microsoft.Extensions.Logging; -using MtconnectTranspiler.Xmi; +using Microsoft.Extensions.Logging; +using MtconnectTranspiler.Sinks.ScribanTemplates; namespace MtconnectTranspiler.Sinks.CSharp { /// /// A base class for transpiling the MTConnect Standard SysML model into C# files. /// - public abstract class CsharpTranspiler : ITranspilerSink + public abstract class CsharpTranspiler : ScribanTranspiler { - /// - protected ILogger _logger; - - /// - /// The root output directory for the transpiled code. - /// - public string ProjectPath { get; set; } - - private string _templatesPath { get; set; } - /// - /// Reference to the directory containing all Scriban template files. - /// - public string TemplatesPath - { - get - { - if (string.IsNullOrEmpty(_templatesPath)) - { - _templatesPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates"); - } - return _templatesPath; - } - set - { - _templatesPath = value; - (TemplateContext.TemplateLoader as IncludeSharedTemplates).TemplatesPath = value; - } - } - - /// - /// Reference to the template rendering context. - /// - protected TemplateContext TemplateContext { get; set; } - - /// - /// Reference to the core template rendering model. - /// - protected ScriptObject Model { get; set; } - /// /// Constructs a new instance of the transpiler that can transpile the model into C# files. /// - /// + /// /// - public CsharpTranspiler(string projectPath, ILogger logger = default) - { - ProjectPath = projectPath; - _logger = logger; - - TemplateContext = new TemplateContext - { - TemplateLoader = new IncludeSharedTemplates() - }; - - var helperFunctions = new ScribanHelperMethods(); - TemplateContext.PushGlobal(helperFunctions); - - var mtconnectFunctions = new MTConnectHelperMethods(); - TemplateContext.PushGlobal(mtconnectFunctions); - - - Model = new ScriptObject(); - Model.SetValue("version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString(), true); - TemplateContext.PushGlobal(Model); - } - - /// - /// - /// - /// - /// - public abstract void Transpile(XmiDocument model, CancellationToken cancellationToken = default); - - /// - /// An internal cache of s based on the source .scriban file location. - /// - protected Dictionary templateCache = new Dictionary(); - /// - /// Retrieves a from a .scriban file at the given . - /// - /// Location of the .scriban file to parse a . - /// Reference to the parsed from the given .scriban at the . - /// - protected Template GetTemplate(string filepath) - { - if (templateCache.TryGetValue(filepath, out Template template)) return template; - - if (!File.Exists(filepath)) throw new FileNotFoundException("Could not find template file", filepath); - - string templateContent = File.ReadAllText(filepath); - template = Template.Parse(templateContent); - - if (template != null) - { - if (templateCache.ContainsKey(filepath)) return templateCache[filepath]; - _logger?.LogInformation("Registering Template from file: {Filepath}", filepath); - templateCache.Add(filepath, template); - return template; - } - - throw new InvalidOperationException(); - } - - /// - /// Renders the into C#. - /// - /// The member name used in the for the provided . - /// The value for the provided reference. - /// The to render C#. - /// Raw C# code. - protected string RenderTemplateWithModel(string member, object value, Template template) - { - if (value == null) return String.Empty; - if (Model.Contains(member)) - { - Model.Remove(member); - } - Model.SetValue(member, value, true); - string csharp = template.Render(TemplateContext); - - Model.Remove(member); - - return csharp; - } - - /// - /// Processes a collection of objects, decorated with the , into a C# file. - /// - /// An implementation of . - /// Collection of objects, decorated with . - /// Location to save the .cs files. - /// Flag for whether or not the output file should be overwritten - protected void ProcessTemplate(IEnumerable items, string folderPath, bool overwriteExisting = false) where T : IFileSource - { - if (items == null || items.Any() == false) return; - - foreach (var item in items) ProcessTemplate(item, folderPath, overwriteExisting); - } - /// - /// Processes an object, decorated with the , into a C# file. - /// - /// An implementation of . - /// An object, decorated with . - /// Location to save the .cs file. - /// Flag for whether or not the output file should be overwritten - /// - /// - protected void ProcessTemplate(T item, string folderPath, bool overwriteExisting = false) where T : IFileSource - { - if (item == null) return; - - System.Type type = typeof(T); - - ScribanTemplateAttribute attr = type.GetCustomAttribute() - ?? throw new NotImplementedException("The type of " + typeof(T).Name + " must be decorated with the ScribanTemplateAttribute"); - - Template template = GetTemplate(Path.Combine(TemplatesPath, attr.Filename)); - if (template == null) - { - var templateNotFound = new FileNotFoundException(); - _logger?.LogError(templateNotFound, "Could not find template"); - throw templateNotFound; - } - - string filepath = Path.Combine(folderPath, item.Filename); - - string csharp; - try - { - csharp = RenderTemplateWithModel("source", item, template); - } - catch (Exception ex) - { - _logger?.LogError(ex, "Failed to render C#"); - throw ex; - } - - if (!string.IsNullOrEmpty(csharp)) - { - try - { - XmiTranspilerExtensions.WriteToFile(filepath, csharp, overwriteExisting); - } - catch (Exception ex) - { - _logger?.LogError(ex, "Failed to write to file: {Filepath}", filepath); - throw ex; - } - } else - { - _logger?.LogWarning("Cannot write an empty C# file: {Filepath}", filepath); - } - } + public CsharpTranspiler(string projectPath, ILogger logger = default) : base(projectPath, logger) { } } } \ No newline at end of file diff --git a/MtconnectTranspiler.Sinks.CSharp/IncludeSharedTemplates.cs b/MtconnectTranspiler.Sinks.CSharp/IncludeSharedTemplates.cs deleted file mode 100644 index ce560765..00000000 --- a/MtconnectTranspiler.Sinks.CSharp/IncludeSharedTemplates.cs +++ /dev/null @@ -1,49 +0,0 @@ -using MtconnectTranspiler.Sinks.CSharp.Models; -using Scriban; -using Scriban.Parsing; -using Scriban.Runtime; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace MtconnectTranspiler.Sinks.CSharp -{ - /// - /// Used as the in the . - /// - public class IncludeSharedTemplates : ITemplateLoader - { - /// - /// Reference to the directory containing all Scriban template files. - /// - public string TemplatesPath { get; set; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates"); - - /// - public string GetPath(TemplateContext context, SourceSpan callerSpan, string templateName) - { - return Path.Combine(TemplatesPath, templateName); - } - - /// - public string Load(TemplateContext context, SourceSpan callerSpan, string templatePath) - { - if (!File.Exists(templatePath)) templatePath = Path.Combine(TemplatesPath, templatePath); - if (!File.Exists(templatePath)) throw new FileNotFoundException("Could not find template file", templatePath); - - var mtconnectFunctions = new MTConnectHelperMethods(); - context.PushGlobal(mtconnectFunctions); - return File.ReadAllText(templatePath); - } - - /// - public async ValueTask LoadAsync(TemplateContext context, SourceSpan callerSpan, string templatePath) - { - if (!File.Exists(templatePath)) templatePath = Path.Combine(TemplatesPath, templatePath); - if (!File.Exists(templatePath)) throw new FileNotFoundException("Could not find template file", templatePath); - - var mtconnectFunctions = new MTConnectHelperMethods(); - context.PushGlobal(mtconnectFunctions); - return await Task.FromResult(File.ReadAllText(templatePath)); - } - } -} \ No newline at end of file diff --git a/MtconnectTranspiler.Sinks.CSharp/Models/Class.cs b/MtconnectTranspiler.Sinks.CSharp/Models/Class.cs index b210d064..a60a1935 100644 --- a/MtconnectTranspiler.Sinks.CSharp/Models/Class.cs +++ b/MtconnectTranspiler.Sinks.CSharp/Models/Class.cs @@ -1,4 +1,4 @@ -using MtconnectTranspiler.Sinks.CSharp.Attributes; +using MtconnectTranspiler.Sinks.ScribanTemplates; using MtconnectTranspiler.Xmi; using MtconnectTranspiler.Xmi.UML; using System.Collections.Generic; diff --git a/MtconnectTranspiler.Sinks.CSharp/Models/Enum.cs b/MtconnectTranspiler.Sinks.CSharp/Models/Enum.cs index cdff5648..5d2afd06 100644 --- a/MtconnectTranspiler.Sinks.CSharp/Models/Enum.cs +++ b/MtconnectTranspiler.Sinks.CSharp/Models/Enum.cs @@ -1,4 +1,4 @@ -using MtconnectTranspiler.Sinks.CSharp.Attributes; +using MtconnectTranspiler.Sinks.ScribanTemplates; using MtconnectTranspiler.Xmi; using MtconnectTranspiler.Xmi.UML; using System.Collections.Generic; diff --git a/MtconnectTranspiler.Sinks.CSharp/Models/IFileSource.cs b/MtconnectTranspiler.Sinks.CSharp/Models/IFileSource.cs deleted file mode 100644 index 66e8531b..00000000 --- a/MtconnectTranspiler.Sinks.CSharp/Models/IFileSource.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Xml.Linq; - -namespace MtconnectTranspiler.Sinks.CSharp.Models -{ - /// - /// Represents an object that is intended to directly convert into a file. - /// - public interface IFileSource - { - /// - /// Reference to the expected name for the coverted file. - /// - string Filename { get; set; } - - /// - /// Reference to the expected namespace for the converted file contents. - /// - string Namespace { get; set; } - } -} diff --git a/MtconnectTranspiler.Sinks.CSharp/Models/MTConnectHelperMethods.cs b/MtconnectTranspiler.Sinks.CSharp/Models/MTConnectHelperMethods.cs deleted file mode 100644 index 0a4ff646..00000000 --- a/MtconnectTranspiler.Sinks.CSharp/Models/MTConnectHelperMethods.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Scriban.Runtime; -using MtconnectTranspiler.Xmi.Profile; -using MtconnectTranspiler.Xmi.UML; -using System.Collections.Generic; -using System; -using System.Linq; -using MtconnectTranspiler.Xmi; -using MtconnectTranspiler.Contracts; - -namespace MtconnectTranspiler.Sinks.CSharp.Models -{ - /// - /// Helper methods related to processing MTConnect references. - /// - public class MTConnectHelperMethods : ScriptObject - { - /// - /// Finds the first definition for the type with the provided . - /// - /// Reference to the whole in order to find all references - /// Reference to the xmi:id which is used to compare against the - /// First find of the - public static Normative LookupNormative(XmiDocument model, string id) => MtconnectTranspiler.Contracts.MTConnectHelper.LookupNormative(model, id); - /// - /// Finds the first definition for the type with the provided . - /// - /// Reference to the whole in order to find all references - /// Reference to the xmi:id which is used to compare against the - /// First find of the - public static Deprecated LookupDeprecated(XmiDocument model, string id) => MtconnectTranspiler.Contracts.MTConnectHelper.LookupDeprecated(model, id); - - // TODO: Remove these references to MtconnectVersions and leave that up to MtconnectCore - /// - /// An overridable collection of alternative version numbers, keyed by the version numbers defined within the . - /// - public static Dictionary VersionEnumLookup { get; set; } = new Dictionary() - { - { "1.0", "MtconnectVersions.V_1_0_1" }, - { "1.1", "MtconnectVersions.V_1_1_0" }, - { "1.2", "MtconnectVersions.V_1_2_0" }, - { "1.3", "MtconnectVersions.V_1_3_0" }, - { "1.4", "MtconnectVersions.V_1_4_0" }, - { "1.5", "MtconnectVersions.V_1_5_0" }, - { "1.6", "MtconnectVersions.V_1_6_0" }, - { "1.7", "MtconnectVersions.V_1_7_0" }, - { "1.8", "MtconnectVersions.V_1_8_0" }, - { "2.0", "MtconnectVersions.V_2_0_0" }, - { "2.1", "MtconnectVersions.V_2_1_0" }, - { "2.2", "MtconnectVersions.V_2_2_0" } - }; - /// - /// References to lookup an alternative to the version number referred to within the . - /// - /// Version number as defined within the - /// Alternative version string, see . Returns null if not found. - public static string LookupMtconnectVersions(string version) - { - if (version == null) return null; - if (!VersionEnumLookup.TryGetValue(version, out string versionEnum)) return null; - return versionEnum; - } - } -} diff --git a/MtconnectTranspiler.Sinks.CSharp/Models/ScribanHelperMethods.cs b/MtconnectTranspiler.Sinks.CSharp/Models/ScribanHelperMethods.cs index 03c7914c..b026b9de 100644 --- a/MtconnectTranspiler.Sinks.CSharp/Models/ScribanHelperMethods.cs +++ b/MtconnectTranspiler.Sinks.CSharp/Models/ScribanHelperMethods.cs @@ -1,24 +1,15 @@ -using Scriban.Runtime; -using System.Text.RegularExpressions; -using System.Collections.Generic; +using System.Collections.Generic; using System; -using System.Linq; using MtconnectTranspiler.Xmi.UML; using MtconnectTranspiler.Contracts; -using System.Text; namespace MtconnectTranspiler.Sinks.CSharp.Models { /// /// Helper methods to process content for scriban templates /// - public class ScribanHelperMethods : ScriptObject + public class ScribanHelperMethods : ScribanTemplates.ScribanHelperMethods { - /// - /// The default replacement character for converting invalid code characters. - /// - public const string DEFAULT_CODE_SAFE_REPLACEMENT = "_"; - private static Dictionary umlDataTypeToCSharp = new Dictionary() { { "boolean", typeof(bool) }, @@ -68,193 +59,5 @@ public static Type ToPrimitiveType(Xmi.XmiDocument model, UmlProperty source) return null; return ToPrimitiveType(umlDataType); } - - /// - /// Converts Markdown into C# <summary /> formatted text. - /// - /// Markdown text - /// <summary /> formatted text. - public static string ToSummary(string markdown) - { - if (string.IsNullOrEmpty(markdown)) return markdown; - - Dictionary> rules = new Dictionary>() - { - { new Regex(@"(.*?)(? )(.*?)"), (string s) => $"
" }, - { new Regex(@"(.*?)(?`(?.*?)`)(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\*\*(?.*?)\*\*)(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{block\((?.*?)\)\}\})(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{term\((?.*?)\)\}\})(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{termplural\((?.*?)\)\}\})(.*?)"), (string s) =>$"{s}s" }, - { new Regex(@"(.*?)(?\*(?.*?)\*)(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{url\((?.*?)\)\}\}(.*?))(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{def\((?.*?)\)\}\}(.*?))(.*?)"), (string s) => $"" }, - { new Regex(@"(.*?)(?\{\{property\((?.*?)\)\}\}(.*?))(.*?)"), (string s) => - { - string[] parts = s.Split(','); - if (parts.Length > 1) - return $"{parts[parts.Length - 1]} in {parts[0]}"; - else - return $""; - } - }, - // NOTE: This uses Google's "I'm feeling lucky" URL parameter - { new Regex(@"(.*?)(?\{\{cite\((?.*?)\)\}\})(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{sect\((?.*?)\)\}\})(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{package\((?.*?)\)\}\})(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\$\$(?.*?)\$\$)(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{newpage\(\)\}\}(?.*?))(.*?)"), (string s) => $"" }, - { new Regex(@"(.*?)(?\{\{newacronym\{(?.*?)\}\{(?.*?)\}\{(?.*?)\}\(\)\}\})(.*?)"), (string s) => $"{s}" }, - { new Regex(@"(.*?)(?\{\{appendix\((?.*?)\)\}\})(.*?)"), (string s) => $"" }, - { new Regex(@"(.*?)(?\{\{section\*\((?.*?)\)\}\})(.*?)"), (string s) => $"" }, - { new Regex(@"(.*?)(?\{\{addcontentsline(?.*?)\}\})(.*?)"), (string s) => $"" }, - { new Regex(@"(.*?)(?\{\{input(?.*?)\}\})(.*?)"), (string s) => $"" }, - { new Regex(@"(.*?)(?\{\{renewcommand(?.*?)\}\})(.*?)"), (string s) => $"" }, - }; - - string output = markdown; - - foreach (var rule in rules) - { - var matches = rule.Key.Matches(output); - foreach (Match match in matches) - { - string block = match.Groups["block"].Value; - string contents = match.Groups["contents"].Value; - output = output.Replace(block, rule.Value(contents)); - } - } - - return output; - } - - /// - /// Array of invalid characters for C# types. Initialized with those returned from . - /// - public static char[] InvalidCharacters { get; set; } = System.IO.Path - .GetInvalidFileNameChars() - .Concat(new char[] { ' ' }) - .ToArray(); - /// - /// Regular expression to replace the - /// - public static Regex ReplaceInvalidChars { get; set; } = new Regex(@"\" + String.Join(@"|\", InvalidCharacters), RegexOptions.Compiled); - /// - /// Replaces invalid filename characters with the character - /// - /// Input string - /// Character to replace invalid characters - /// String considered to be code-safe - public static string ToCodeSafe(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ReplaceInvalidChars.Replace(input, replaceBy); - - /// - public static string ToUpperCase(string input) => input.ToUpper(); - - /// - public static string ToLowerCase(string input) => input.ToLower(); - - /// - /// - /// "The Quick Brown Fox" => "TheQuickBrownFox" - public static string ToPascalCase(string input) => CaseExtensions.StringExtensions.ToPascalCase(input); - - /// - /// - public static string ToPascalCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToCodeSafe(ToPascalCase(input), replaceBy); - - /// - /// - /// "The Quick Brown Fox" => "theQuickBrownFox" - public static string ToCamelCase(string input) => CaseExtensions.StringExtensions.ToCamelCase(input); - - /// - /// - public static string ToCamelCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToCodeSafe(ToCamelCase(input), replaceBy); - - /// - /// - /// "The Quick Brown Fox" => "the_quick_brown_fox" - public static string ToSnakeCase(string input) - { - const string MTConnect = "MTConnect"; - if (string.IsNullOrEmpty(input)) return input; - - var sb = new StringBuilder(); - - int startIndex = 1; - if (input.StartsWith(MTConnect, StringComparison.OrdinalIgnoreCase)) - { - startIndex = MTConnect.Length; - sb.Append(MTConnect); - } - else - { - sb.Append(char.ToLower(input[0])); - } - - for (var i = startIndex; i < input.Length; i++) - { - if (char.IsUpper(input[i])) - { - if (i > 1 && !char.IsUpper(input[i - 1])) - { - sb.Append("_"); - } - else if (i < input.Length - 1 && !char.IsUpper(input[i + 1])) - { - sb.Append("_"); - } - } - sb.Append(char.ToLower(input[i])); - } - - return sb.ToString(); - } - - /// - /// - public static string ToSnakeCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToCodeSafe(ToSnakeCase(input), replaceBy); - - /// - /// and - public static string ToUpperSnakeCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToSnakeCode(input, replaceBy).ToUpper(); - - /// - /// and - public static string ToLowerSnakeCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToSnakeCode(input, replaceBy).ToLower(); - - /// - /// - /// "The Quick Brown Fox" => "the-quick-brown-fox" - public static string ToKebabCase(string input) => CaseExtensions.StringExtensions.ToKebabCase(input); - - /// - /// - public static string ToKebabCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToCodeSafe(ToKebabCase(input), replaceBy); - - /// - /// and - public static string ToUpperKebabCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToKebabCode(input, replaceBy).ToUpper(); - - /// - /// and - public static string ToLowerKebabCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToKebabCode(input, replaceBy).ToLower(); - - /// - /// - /// "The Quick Brown Fox" => "The-Quick-Brown-Fox" - public static string ToTrainCase(string input) => CaseExtensions.StringExtensions.ToTrainCase(input); - - /// - /// - public static string ToTrainCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToCodeSafe(ToTrainCase(input), replaceBy); - - /// - /// and - public static string ToUpperTrainCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToTrainCode(input, replaceBy).ToUpper(); - - /// - /// and - public static string ToLowerTrainCode(string input, string replaceBy = DEFAULT_CODE_SAFE_REPLACEMENT) => ToTrainCode(input, replaceBy).ToLower(); } } diff --git a/MtconnectTranspiler.Sinks.CSharp/Models/Summary.cs b/MtconnectTranspiler.Sinks.CSharp/Models/Summary.cs index 57335b79..354348e2 100644 --- a/MtconnectTranspiler.Sinks.CSharp/Models/Summary.cs +++ b/MtconnectTranspiler.Sinks.CSharp/Models/Summary.cs @@ -1,4 +1,4 @@ -using MtconnectTranspiler.Sinks.CSharp.Attributes; +using MtconnectTranspiler.Sinks.ScribanTemplates; using MtconnectTranspiler.Xmi; using System.Linq; using System.Text; diff --git a/MtconnectTranspiler.Sinks.CSharp/MtconnectTranspiler.Sinks.CSharp.csproj b/MtconnectTranspiler.Sinks.CSharp/MtconnectTranspiler.Sinks.CSharp.csproj index 13dea544..bc87a249 100644 --- a/MtconnectTranspiler.Sinks.CSharp/MtconnectTranspiler.Sinks.CSharp.csproj +++ b/MtconnectTranspiler.Sinks.CSharp/MtconnectTranspiler.Sinks.CSharp.csproj @@ -4,7 +4,7 @@ netstandard2.0 True MTConnect Transpiler Sink for C# - 1.0.12 + 1.0.13 mtconnect, tbm0115 MTConnect Institute; TAMS; An implementation of `ITranspilerSink` from the `MtconnectTranspiler` library. This libary makes it possible to transpile the MTConnect Standard SysML model into C# code. @@ -42,6 +42,7 @@ + diff --git a/MtconnectTranspiler.Sinks.CSharp/MtconnectVersionedObject.cs b/MtconnectTranspiler.Sinks.CSharp/MtconnectVersionedObject.cs index 2e10ded4..0f4b5640 100644 --- a/MtconnectTranspiler.Sinks.CSharp/MtconnectVersionedObject.cs +++ b/MtconnectTranspiler.Sinks.CSharp/MtconnectVersionedObject.cs @@ -1,5 +1,6 @@ using MtconnectTranspiler.Sinks.CSharp.Models; using MtconnectTranspiler.Sinks.Models; +using MtconnectTranspiler.Sinks.ScribanTemplates; using MtconnectTranspiler.Xmi; namespace MtconnectTranspiler.Sinks.CSharp