private string GetDefaultToml() { var doc = new DocumentSyntax() { Tables = { new TableSyntax(new KeySyntax("config")) { Items = { { "schemaVersion", "0.0.1" } } }, new TableSyntax(new KeySyntax("auth")) { Items = { { "defaultToken", "" } } }, new TableSyntax(new KeySyntax("auth", "authorTokens")) { Items = { { "ExampleAuthor", "" } } }, } }; return(doc.ToString()); }
private object GetInheritInstanceFromDirective(Type type, DocumentSyntax doc, string refPath) { var include = GetFileTrivia(doc) .Where(trivia => trivia.Kind == TokenKind.Comment) .Where(comment => comment.Text.StartsWith("#include")) .Select(x => Regex.Split(x.Text, @"\s").LastOrDefault()) .ToArray(); if (include.Length > 1) { throw new TomlConfigurationException("Only one include directive is allowed in config."); } if (include.Length == 1) { var basePath = Path.GetDirectoryName(refPath) ?? "."; var parentPath = Path.Combine(basePath, include[0]); if (!File.Exists(parentPath)) { throw new TomlConfigurationException( $"Missing include file {parentPath} included in '{refPath}'"); } using (var parentStream = File.Open(parentPath, FileMode.Open)) { return(Read(type, parentStream, parentPath)); } } return(null); }
public static void WriteDocument(string file, DocumentSyntax doc) { using (var writer = File.CreateText(file)) { doc.WriteTo(writer); } }
private void LoadFromToml(string path) { LoadDefaultConfiguration(); string doc = System.IO.File.ReadAllText(path); DocumentSyntax docSyn = Toml.Parse(doc); TomlTable table = docSyn.ToModel(); foreach (var prop in this.GetType().GetProperties()) { string _table = prop.Name.Split("_")[0]; string _prop = prop.Name.Split("_")[1]; try { if (prop.GetType() == typeof(bool)) { bool val = (bool)((TomlTable)table[_table])[_prop]; prop.SetValue(this, val); } else { string val = (string)((TomlTable)table[_table])[_prop]; prop.SetValue(this, val); } } catch (Exception e) { // Do nothing. } } }
/// <summary> /// Converts a <see cref="DocumentSyntax"/> to a <see cref="TomlTable"/> /// </summary> /// <param name="syntax">A TOML document</param> /// <returns>A <see cref="TomlTable"/>, a runtime representation of the TOML document</returns> public static TomlTable ToModel(this DocumentSyntax syntax) { if (syntax == null) { throw new ArgumentNullException(nameof(syntax)); } return(TomlTable.From(syntax)); }
/// <summary> /// Save the document syntax to the root file /// </summary> public static async Task SerializeAsync(DocumentSyntax documentSyntax, System.IO.Stream stream) { // Write out the entire root table var content = documentSyntax.ToString(); using (var writer = new System.IO.StreamWriter(stream)) { await writer.WriteAsync(content); } }
private IEnumerable <KeyValueSyntax> GetAllProperties(DocumentSyntax table) { foreach (var prop in table.GetAllKeys()) { if (configKeyNames.Any(c => c.IsMatch(prop.Key.ToString()))) { yield return(prop); } } }
public static IEnumerable <KeyValueSyntax> GetAllKeys(this DocumentSyntax document) { foreach (var value in document.KeyValues) { yield return(value); } foreach (var value in document.Tables.SelectMany(GetAllKeys)) { yield return(value); } }
public OptionsFile(string fileName) { _path = Path.Combine(PathHelpers.GetConfigsDir(), fileName); if (!File.Exists(_path)) { _toml = new DocumentSyntax(); return; } var bytes = File.ReadAllBytes(_path); _toml = Toml.Parse(bytes, _path); }
static XDocument Convert(DocumentSyntax syntax, Func <string, XNamespace> prefixToNamespace) { var xdoc = new XDocument(); //xdoc.GetType() // .GetMethod("SetBaseUri", BindingFlags.NonPublic | BindingFlags.Instance) // .Invoke(xdoc, new object[] { DefaultFuseNamespace.NamespaceName }); foreach (var nodeSyntax in syntax.Nodes) { ConvertAndAddNode(nodeSyntax, prefixToNamespace, xdoc); } return(xdoc); }
protected OptionsFile(string fileName, bool initDeclaredOptionMembers = true) : base(initDeclaredOptionMembers) { _name = Path.GetFileNameWithoutExtension(fileName); _path = Path.Combine(Utilities.GetConfigsPath(), fileName); if (!File.Exists(_path)) { _toml = new DocumentSyntax(); return; } var bytes = File.ReadAllBytes(_path); _toml = Toml.Parse(bytes, _path); }
public DocumentSyntax Run() { var doc = new DocumentSyntax(); _diagnostics = doc.Diagnostics; _currentTable = null; _hideNewLine = true; NextToken(); while (TryParseTableEntry(out var itemEntry)) { if (itemEntry == null) { continue; } if (itemEntry is TableSyntaxBase table) { _currentTable = table; AddToListAndUpdateSpan(doc.Tables, table); } else if (_currentTable == null) { AddToListAndUpdateSpan(doc.KeyValues, (KeyValueSyntax)itemEntry); } else { // Otherwise, we know that we can only have a key-value AddToListAndUpdateSpan(_currentTable.Items, (KeyValueSyntax)itemEntry); } } if (_currentTable != null) { Close(_currentTable); _currentTable = null; } Close(doc); if (_lexer.HasErrors) { foreach (var lexerError in _lexer.Errors) { Log(lexerError); } } return(doc); }
/// <summary> /// Validates the specified TOML document. /// </summary> /// <param name="doc">The TOML document to validate</param> /// <returns>The same instance as the parameter. Check <see cref="DocumentSyntax.HasErrors"/> and <see cref="DocumentSyntax.Diagnostics"/> for details.</returns> public static DocumentSyntax Validate(DocumentSyntax doc) { if (doc == null) { throw new ArgumentNullException(nameof(doc)); } if (doc.HasErrors) { return(doc); } var validator = new SyntaxValidator(doc.Diagnostics); validator.Visit(doc); return(doc); }
internal static bool Save(string ConfigPath) { try { var Document = new DocumentSyntax(); SaveClass(typeof(Config), Document); using var writer = File.CreateText(ConfigPath); Document.WriteTo(writer); writer.Flush(); } catch (Exception ex) { ex.PrintWarning(); return(false); } return(true); }
internal static bool Save(MemoryStream stream) { try { var Document = new DocumentSyntax(); SaveClass(typeof(Config), Document); using var writer = new StreamWriter(stream); Document.WriteTo(writer); writer.Flush(); } catch (Exception ex) { ex.PrintWarning(); return(false); } return(true); }
IEnumerable <SyntaxTrivia> GetFileTrivia(DocumentSyntax doc) { if (doc.LeadingTrivia != null) { foreach (var trivia in doc.LeadingTrivia) { yield return(trivia); } } foreach (var kv in doc.KeyValues.Where(x => x.LeadingTrivia != null)) { foreach (var trivia in kv.LeadingTrivia) { yield return(trivia); } } }
public void TestDocument() { var doc = new DocumentSyntax() { Tables = { new TableSyntax("test") { Items = { { "a", 1 }, { "b", true }, { "c", "Check" }, { "d", "ToEscape\nWithAnotherChar\t" }, { "e", 12.5 }, { "f", new int[] { 1, 2, 3, 4 } }, { "g", new string[] { "0", "1", "2" } }, { "key with space", 2 } } } } }; var docStr = doc.ToString(); var expected = @"[test] a = 1 b = true c = ""Check"" d = ""ToEscape\nWithAnotherChar\t"" e = 12.5 f = [1, 2, 3, 4] g = [""0"", ""1"", ""2""] ""key with space"" = 2 "; AssertHelper.AreEqualNormalizeNewLine(expected, docStr); // Reparse the result and compare it again var newDoc = Toml.Parse(docStr); AssertHelper.AreEqualNormalizeNewLine(expected, newDoc.ToString()); }
public static void Dump(string input, DocumentSyntax doc, string roundtrip) { Console.WriteLine(); DisplayHeader("input"); Console.WriteLine(input); Console.WriteLine(); DisplayHeader("round-trip"); Console.WriteLine(roundtrip); if (doc.Diagnostics.Count > 0) { Console.WriteLine(); DisplayHeader("messages"); foreach (var syntaxMessage in doc.Diagnostics) { Console.WriteLine(syntaxMessage); } } }
internal static void Save() { DocumentSyntax doc = new DocumentSyntax() { Tables = { new TableSyntax("AssemblyGenerator") { Items = { { "UnityVersion", (UnityVersion == null) ? "" : UnityVersion }, { "Cpp2IL", (Cpp2ILVersion == null) ? "" : Cpp2ILVersion }, { "Il2CppAssemblyUnhollower", (Il2CppAssemblyUnhollowerVersion == null) ? "" : Il2CppAssemblyUnhollowerVersion }, { "GameAssemblyHash", (GameAssemblyHash == null) ? "" : GameAssemblyHash }, { "OldFiles", OldFiles.ToArray() } } } } }; File.WriteAllText(FilePath, doc.ToString()); }
public void Save(string path) { var doc = new DocumentSyntax() { Tables = { new TableSyntax("AssemblyGenerator") { Items = { { "UnityVersion", (UnityVersion == null) ? "" : UnityVersion }, { "GameAssemblyHash", (GameAssemblyHash == null) ? "" : GameAssemblyHash }, { "DumperVersion", (DumperVersion == null) ? "" : DumperVersion }, { "UnhollowerVersion", (UnhollowerVersion == null) ? "" : UnhollowerVersion }, { "OldFiles", OldFiles.ToArray() } } } } }; File.WriteAllText(path, doc.ToString()); }
internal void Load(DocumentSyntax doc, string filePath, DiagnosticsBag diagnostics) { var table = doc.Tables.FindByName("package"); if (table == null) { diagnostics.Error(new SourceSpan(filePath, new TextPosition(), new TextPosition()), $"Unable to find [package] section"); return; } if (table.Kind != SyntaxKind.Table) { diagnostics.Error(new SourceSpan(filePath, new TextPosition(), new TextPosition()), $"Unable to find [package] section must be a table and not a table array [[package]]"); return; } foreach (var item in table.Items) { var key = item.Key.AsText(); switch (key) { case "name": Name = item.Value.AsObject()?.ToString(); break; case "version": Name = item.Value.AsObject()?.ToString(); break; case "authors": break; default: // log error break; } } }
public static T ToModel <T>(this DocumentSyntax documentSyntax) where T : new() { T instance = new T(); TomlTable model = documentSyntax.ToModel(); foreach (PropertyInfo property in instance.GetType().GetProperties()) { TomlPropertyAttribute?attribute = property.GetCustomAttribute <TomlPropertyAttribute>(); if (attribute is null) { continue; } if (attribute.Header is null) { if (attribute.Required && !model.ContainsKey(property.Name)) { throw new Exception($"Toml file does not have required property '{property.Name}'."); } property.SetValue(instance, Convert.ChangeType(model[property.Name], property.PropertyType)); } else { if ((attribute.Required && !model.ContainsKey(attribute.Header)) || !((TomlTable)model[attribute.Header]).ContainsKey(property.Name)) { throw new Exception($"Toml file does not have required property '{property.Name}'."); } property.SetValue(instance, Convert.ChangeType(((TomlTable)model[attribute.Header])[property.Name], property.PropertyType)); } } return(instance); }
internal void Write() { var doc = new DocumentSyntax(); foreach (var credential in credentials.Values) { if (string.IsNullOrEmpty(credential.token)) { credential.token = ""; } doc.Tables.Add(new TableSyntax(new KeySyntax("npmAuth", credential.url)) { Items = { { "token", credential.token }, { "alwaysAuth", credential.alwaysAuth } } }); } File.WriteAllText(upmconfigFile, doc.ToString()); }
public static XDocument ToXml(this DocumentSyntax syntax, bool annotateWithSyntax = false) { if (annotateWithSyntax) { throw new NotImplementedException(); } var xDocument = Convert( syntax, prefix => { if (string.IsNullOrEmpty(prefix)) { return(DefaultFuseNamespace); } if (!DefaultPrefixToNamespaceMap.TryGetValue(prefix, out var ns)) { throw new InvalidOperationException("Unrecognized namespace prefix"); } return(ns); }); return(xDocument); }
private static bool Parse(DocumentSyntax Data) { try { foreach (var table in Data.Tables) { string tableName = ""; try { tableName = table.Name.ToString(); var elements = tableName.Split('.'); if (elements.Length != 0) { elements[0] = null; } var configClass = typeof(Config); string summedClass = configClass.Name.Trim(); foreach (var element in elements) { if (element == null) { continue; } var trimmedElement = element.Trim(); summedClass += $".{trimmedElement}"; var child = configClass.GetNestedType(trimmedElement, StaticFlags); if (child == null || child.IsNestedPrivate || child.GetCustomAttribute <Config.ConfigIgnoreAttribute>() != null) { throw new InvalidDataException($"Configuration Child Class '{summedClass}' does not exist"); } configClass = child; } foreach (var value in table.Items) { try { var keyString = value.Key.ToString().Trim(); var field = configClass.GetField(keyString, StaticFlags); if (field == null || field.IsPrivate || field.IsInitOnly || !field.IsStatic || field.IsLiteral) { throw new InvalidDataException($"Configuration Value '{summedClass}.{keyString}' does not exist"); } object fieldValue = field.GetValue(null); switch (fieldValue) { case string v: field.SetValue(null, (string)((StringValueSyntax)value.Value).Value.Trim()); break; case sbyte v: field.SetValue(null, (sbyte)((IntegerValueSyntax)value.Value).Value); break; case byte v: field.SetValue(null, (byte)((IntegerValueSyntax)value.Value).Value); break; case short v: field.SetValue(null, (short)((IntegerValueSyntax)value.Value).Value); break; case ushort v: field.SetValue(null, (ushort)((IntegerValueSyntax)value.Value).Value); break; case int v: field.SetValue(null, (int)((IntegerValueSyntax)value.Value).Value); break; case uint v: field.SetValue(null, (uint)((IntegerValueSyntax)value.Value).Value); break; case ulong v: field.SetValue(null, unchecked ((ulong)((IntegerValueSyntax)value.Value).Value)); break; case float v: field.SetValue(null, (float)((FloatValueSyntax)value.Value).Value); break; case double v: field.SetValue(null, (double)((FloatValueSyntax)value.Value).Value); break; case bool v: field.SetValue(null, (bool)((BooleanValueSyntax)value.Value).Value); break; default: if (fieldValue is List <string> slist) { var arrayValue = ((ArraySyntax)value.Value).Items; var list = new List <string>(arrayValue.ChildrenCount); foreach (var obj in arrayValue) { var ovalue = obj.Value; if (ovalue is StringValueSyntax svalue) { list.Add(svalue.Value); } else if (ovalue is IntegerValueSyntax ivalue) { list.Add(ivalue.Value.ToString()); } } field.SetValue(null, list); } else if (fieldValue is List <int> ilist) { var arrayValue = ((ArraySyntax)value.Value).Items; var list = new List <int>(arrayValue.ChildrenCount); foreach (var obj in arrayValue) { var ovalue = obj.Value; if (ovalue is StringValueSyntax svalue) { list.Add(Int32.Parse(svalue.Value)); } else if (ovalue is IntegerValueSyntax ivalue) { list.Add((int)ivalue.Value); } } field.SetValue(null, list); } else if (fieldValue.GetType().IsEnum) { var enumNames = fieldValue.GetType().GetEnumNames(); var values = fieldValue.GetType().GetEnumValues(); var configValue = ((StringValueSyntax)value.Value).Value.Trim(); bool found = false; foreach (int index in 0..enumNames.Length) { if (enumNames[index] == configValue) { field.SetValue(null, values.GetValue(index)); found = true; break; } } if (!found) { throw new InvalidDataException($"Unknown Enumeration Value Type '{summedClass}.{keyString}' = '{value.Value.ToString()}'"); } } else { throw new InvalidDataException($"Unknown Configuration Value Type '{summedClass}.{keyString}' = '{value.Value.ToString()}'"); } break; } } catch (Exception ex) { ex.PrintWarning(); } } } catch (Exception) { throw new InvalidDataException($"Unknown Configuration Table '{tableName}'"); } } } catch (Exception ex) { ex.PrintWarning(); return(false); } return(true); }
private static void SaveClass(Type type, DocumentSyntax document, KeySyntax key = null) { key ??= new KeySyntax(type.Name); var fields = type.GetFields(StaticFlags); var children = type.GetNestedTypes(StaticFlags); var table = new TableSyntax(key); var tableItems = table.Items; foreach (var field in fields) { if (field.IsPrivate || field.IsInitOnly || !field.IsStatic || field.IsLiteral) { continue; } if (field.GetCustomAttribute <Config.ConfigIgnoreAttribute>() != null) { continue; } ValueSyntax value = null; object fieldValue = field.GetValue(null); switch (fieldValue) { case string v: value = new StringValueSyntax(v); break; case sbyte v: value = new IntegerValueSyntax(v); break; case byte v: value = new IntegerValueSyntax(v); break; case short v: value = new IntegerValueSyntax(v); break; case ushort v: value = new IntegerValueSyntax(v); break; case int v: value = new IntegerValueSyntax(v); break; case uint v: value = new IntegerValueSyntax(v); break; case ulong v: value = new IntegerValueSyntax(unchecked ((long)v)); break; case float v: value = new FloatValueSyntax(v); break; case double v: value = new FloatValueSyntax(v); break; case bool v: value = new BooleanValueSyntax(v); break; default: if (fieldValue is List <string> slist) { value = new ArraySyntax(slist.ToArray()); } else if (fieldValue is List <int> ilist) { value = new ArraySyntax(ilist.ToArray()); } else if (fieldValue.GetType().IsEnum) { value = new StringValueSyntax(fieldValue.GetType().GetEnumName(fieldValue)); } break; } if (value == null) { continue; } var keyValue = new KeyValueSyntax( field.Name, value ); //if (field.GetAttribute<Config.CommentAttribute>(out var attribute)) { //keyValue.GetChildren(Math.Max(0, keyValue.ChildrenCount - 2)).AddComment(attribute.Message); //} tableItems.Add(keyValue); } if (table.Items.ChildrenCount != 0) { document.Tables.Add(table); } foreach (var child in children) { if (child.IsNestedPrivate) { continue; } if (child.GetCustomAttribute <Config.ConfigIgnoreAttribute>() != null) { continue; } var childKey = new KeySyntax(typeof(Config).Name); var parentKey = key.ToString().Split('.'); if (parentKey.Length != 0) { parentKey[0] = null; } foreach (var subKey in parentKey) { if (subKey == null) { continue; } childKey.DotKeys.Add(new DottedKeyItemSyntax(subKey)); } childKey.DotKeys.Add(new DottedKeyItemSyntax(child.Name)); SaveClass(child, document, childKey); } }
/// <summary> /// Set the current output syntax of the specified document settings, and returns the document settings itself. /// </summary> /// <param name="self"> /// The input <see cref="DocumentOutputSettings"/>, /// which acts as the <b>this</b> instance for the extension method. /// </param> /// <param name="syntax">the new syntax to use</param> /// <returns>The input <see cref="DocumentOutputSettings"/>, for method chaining.</returns> /// <seealso cref="DocumentOutputSettings.Syntax">DocumentOutputSettings.Syntax</seealso> public static DocumentOutputSettings Syntax(this DocumentOutputSettings self, DocumentSyntax syntax) { self.Syntax = syntax; return self; }
public static void WriteDefault() { var path = GetFilepath(); if (File.Exists(path)) { Console.WriteLine($"Project configuration already exists at {path}, skipping creation"); } else { var doc = new DocumentSyntax() { Tables = { new TableSyntax("config") { Items = { { "schemaVersion", "0.0.1" } } }, new TableSyntax("package") { Items = { { "author", "AuthorName" }, { "name", "PackageName" }, { "versionNumber", "1.0.0" }, { "description", "" }, { "websiteUrl", "" }, } }, new TableSyntax(new KeySyntax("package", "dependencies")) { Items = { { "Example-Dependency", "1.0.0" }, }, }, new TableSyntax("build") { Items = { { "icon", "./icon.png" }, { "readme", "./README.md" }, { "outdir", "./build" }, } }, new TableSyntax(new KeySyntax("build", "copy")) { Items = { { "./dist", "./" } } }, new TableSyntax(new KeySyntax("publish")) { Items = { { "repository", "thunderstore.io" } } } } }; File.WriteAllText(path, doc.ToString()); Console.WriteLine($"Wrote project configuration to {path}"); } }
public void TestDocument() { var table = new TableSyntax("test") { Items = { { "a", 1 }, { "b", true }, { "c", "Check" }, { "d", "ToEscape\nWithAnotherChar\t" }, { "e", 12.5 }, { "f", new int[] { 1, 2, 3, 4 } }, { "g", new string[] { "0", "1", "2" } }, { "key with space", 2 } } }; var doc = new DocumentSyntax() { Tables = { table } }; table.AddLeadingComment("This is a comment"); table.AddLeadingTriviaNewLine(); var firstElement = table.Items.GetChildren(0); firstElement.AddTrailingComment("This is an item comment"); var secondElement = table.Items.GetChildren(2); secondElement.AddLeadingTriviaNewLine(); secondElement.AddLeadingComment("This is a comment in a middle of a table"); secondElement.AddLeadingTriviaNewLine(); secondElement.AddLeadingTriviaNewLine(); var docStr = doc.ToString(); var expected = @"# This is a comment [test] a = 1 # This is an item comment b = true # This is a comment in a middle of a table c = ""Check"" d = ""ToEscape\nWithAnotherChar\t"" e = 12.5 f = [1, 2, 3, 4] g = [""0"", ""1"", ""2""] ""key with space"" = 2 "; AssertHelper.AreEqualNormalizeNewLine(expected, docStr); // Reparse the result and compare it again var newDoc = Toml.Parse(docStr); AssertHelper.AreEqualNormalizeNewLine(expected, newDoc.ToString()); }
public void CreateConfig(DocumentSyntax initialConfig = null) { File.WriteAllText(ConfigPath, (initialConfig?.ToString() ?? "") + "\n"); }
private AppConfig(DocumentSyntax validatedSyntaxTree) { _config = validatedSyntaxTree.ToModel(); }