public Parser(Stream s, TomlSettings settings) { Assert(settings != null); this.stream = s; this.settings = settings; }
public void RadToml_WithGenricConverters_CanFindCorrectConverter() { // Arrange var config = TomlSettings.Create(cfg => cfg .ConfigureType <IGeneric <string> >(ct => ct .WithConversionFor <TomlString>(conv => conv .FromToml((m, ts) => new GenericImpl <string>(ts.Value)) ) ) .ConfigureType <IGeneric <int> >(ct => ct .WithConversionFor <TomlString>(conv => conv .FromToml((m, ts) => new GenericImpl <int>(int.Parse(ts.Value))) ) ) ); string toml = @" Foo = ""Hello"" Foo2 = ""10"" Foo3 = [""A""]"; // Act var co = Toml.ReadString <GenericHost>(toml, config); // Assert Assert.NotNull(co); Assert.NotNull(co.Foo); Assert.Equal("Hello", co.Foo.Value); Assert.NotNull(co.Foo2); Assert.Equal(10, co.Foo2.Value); }
private static async Task <int> run() { TomlSettings parseSettings = TomlSettings.Create(s => s.ConfigurePropertyMapping(m => m.UseTargetPropertySelector(new SnakeCasePropertySelector())) ); FeedSource feedSource = Toml.ReadFile <FeedSource>(settings.ConfigFilepath, parseSettings); if (feedSource == null) { Console.Error.WriteLine("Error: Somethine went wrong when parsing your settings file :-("); return(1); } if (!string.IsNullOrWhiteSpace(feedSource.Feed.Output)) { settings.OutputFilepath = feedSource.Feed.Output; } FeedBuilder feedBuilder = new FeedBuilder(); try { await feedBuilder.AddSource(feedSource); } catch (ApplicationException error) { Console.Error.WriteLine(error.Message); return(2); } await Console.Error.WriteLineAsync($"[Output] Writing feed to {settings.OutputFilepath}"); File.WriteAllText(settings.OutputFilepath, await feedBuilder.Render()); return(0); }
/// <summary> /// Initializes a new instance of the <see cref="AppSettings"/> class. /// </summary> public AppSettings() { _tomlSettings = TomlSettings.Create(cfg => { cfg.ConfigureType <Color>(type => type.WithConversionFor <TomlString>(convert => convert .ToToml(ColorTranslator.ToHtml) .FromToml(tomlString => ColorTranslator.FromHtml(tomlString.Value)))); cfg.ConfigureType <CustomLabel.TextAlignment>(type => type.WithConversionFor <TomlString>(convert => convert .ToToml(SerializationConversions.EnumToString) .FromToml(str => SerializationConversions.StringToEnum <CustomLabel.TextAlignment>(str.Value)))); }); if (!Directory.Exists(SettingsDirectory)) { Directory.CreateDirectory(SettingsDirectory); } if (!File.Exists(SettingsFilePath)) { CreateDefault(); Toml.WriteFile(_settings, SettingsFilePath, _tomlSettings); } else { LoadSettings(); } GetModels(); }
private static void LoadConfig() { string configPath = Path.Combine(Paths.ConfigPath, "Config.toml"); var tomlSettings = TomlSettings.Create(builder => builder .ConfigureType <Version>(type => type .WithConversionFor <TomlString>(convert => convert .ToToml(tt => tt.ToString()) .FromToml(ft => Version.Parse(ft.Value))))); var oldConfig = File.Exists(configPath) ? Toml.ReadFile <EnvironmentConfig>(configPath, tomlSettings) : null; var version = oldConfig?.Version ?? new Version(0, 0, 0); var cache = oldConfig?.Cache ?? CreateDefaultCacheConfig(); var tor = oldConfig?.Tor ?? (version <= new Version(5, 0, 28) ? CreateDefaultTorConfig() : null); Toml.WriteFile(new EnvironmentConfig(AmoebaEnvironment.Version, cache, tor), configPath, tomlSettings); Config = new EnvironmentConfig(version, cache, tor); EnvironmentConfig.CacheConfig CreateDefaultCacheConfig() { return(new EnvironmentConfig.CacheConfig("../Config/Cache.blocks")); } EnvironmentConfig.TorConfig CreateDefaultTorConfig() { return(new EnvironmentConfig.TorConfig(@"Assemblies/Tor/tor.exe", "-f tor.config DataDirectory " + @"../../../Work/Tor", @"Assemblies/Tor")); } }
/// <summary> /// Initializes a new instance of the <see cref="AppSettings"/> class. /// </summary> public AppSettings() { _tomlSettings = TomlSettings.Create(cfg => { cfg.ConfigureType <Color>(type => type.WithConversionFor <TomlString>(convert => convert .ToToml(SerializationConversions.ColorToString) .FromToml(tomlString => SerializationConversions.StringToColor(tomlString.Value)))); cfg.ConfigureType <CustomLabel.TextAlignment>(type => type.WithConversionFor <TomlString>(convert => convert .ToToml(SerializationConversions.EnumToString) .FromToml(str => SerializationConversions.StringToEnum <CustomLabel.TextAlignment>(str.Value)))); cfg.ConfigureType <double>(type => type.WithConversionFor <TomlInt>(c => c .FromToml(tml => tml.Value))); }); if (!Directory.Exists(SettingsDirectory)) { Directory.CreateDirectory(SettingsDirectory); } if (!File.Exists(SettingsFilePath)) { CreateDefaultSettingsFile(); } else { LoadSettingsFromPath(SettingsFilePath); } if (_settings.AudioSourceSettings == null) { _settings.AudioSourceSettings = new List <AudioSourceSettings>(); } SelectProfile(_settings.CurrentProfileName); }
public SettingsManager() { if (!Directory.Exists(SettingsDirectory)) { Directory.CreateDirectory(SettingsDirectory); } if (!File.Exists(SettingsFile)) { File.CreateText(SettingsFile).Close(); } _tomlSettings = TomlSettings.Create(cfg => { cfg.ConfigureType <Color>(type => type.WithConversionFor <TomlString>(convert => convert .ToToml(ColorTranslator.ToHtml) .FromToml(tomlInt => ColorTranslator.FromHtml(tomlInt.Value)))); cfg.ConfigureType <Font>(type => type.WithConversionFor <TomlString>(convert => convert .ToToml(Converters.FontToString) .FromToml(tomlString => Converters.StringToFont(tomlString.Value)))); }); _root = Toml.ReadFile(SettingsFile, _tomlSettings); try { AudioBandSettings = _root.Get <AudioBandSettings>(SettingsKey); } catch (KeyNotFoundException) { AudioBandSettings = new AudioBandSettings(); _root[SettingsKey] = Toml.Create(AudioBandSettings, _tomlSettings); } }
public void ReadConfigPropertyAfterInit_WhenMultiLevelTypeHasConverterInSpecializedScope_ReadsItemFromSpecScope() { using (var main = TestFileName.Create("main", Toml.FileExtension)) using (var spec = TestFileName.Create("spec", Toml.FileExtension)) { // Arrange var tmlCfg = TomlSettings.Create(c => c .ConfigureType <MultiTableConverterObject>(tc => tc .WithConversionFor <TomlString>(conv => conv .ToToml(o => o.ToString()) .FromToml(s => MultiTableConverterObject.Parse(s.Value))))); Toml.WriteFile(Toml.Create(), main, tmlCfg);; Toml.WriteFile(Toml.Create(CreateWithUnitItem(2.0, "X")), spec, tmlCfg); var cfg = Config.CreateAs() .MappedToType(() => new Root()) .UseTomlConfiguration(tmlCfg) .StoredAs(s => s.File(main).AccessedBySource("main", out var _).MergeWith( s.File(spec).AccessedBySource("spec", out var _))) .Initialize(); // Act var val = cfg.Get(c => c.ConvertedItem.UnitItem.Unit); var src = cfg.GetSource(c => c.ConvertedItem.UnitItem.Unit); // Assert val.Should().Be("X"); src.Name.Should().Be("spec"); } }
public Parser(Stream s, TomlSettings settings) { Assert(settings != null); this.tokenizer = new Tokenizer(s); this.settings = settings; }
public void SetProperty_InSpecializedScopeForConvertedMultiLevelType_WritesItBackToSpecScope() { using (var main = TestFileName.Create("main", Toml.FileExtension)) using (var spec = TestFileName.Create("spec", Toml.FileExtension)) { // Arrange var tmlCfg = TomlSettings.Create(c => c .ConfigureType <MultiTableConverterObject>(tc => tc .WithConversionFor <TomlString>(conv => conv .ToToml(o => o.ToString()) .FromToml(s => MultiTableConverterObject.Parse(s.Value))))); Toml.WriteFile(Toml.Create(), main, tmlCfg);; Toml.WriteFile(Toml.Create(CreateWithUnitItem(2.0, "X")), spec, tmlCfg); var cfg = Config.CreateAs() .MappedToType(() => new Root()) .UseTomlConfiguration(tmlCfg) .StoredAs(s => s .File(main).MergeWith( s.File(spec))) .Initialize(); // Act cfg.Set(c => c.ConvertedItem.UnitItem.Unit, "EX"); // Assert var root = Toml.ReadFile <Root>(spec, tmlCfg); root.ConvertedItem.UnitItem.Unit.Should().Be("EX"); } }
public void SetConfigProperty_WhenMultiLevelTypeHasConverter_WritesTheSubPropertyCorrectly() { using (var fn = TestFileName.Create("file", Toml.FileExtension)) { // Arrange var tmlCfg = TomlSettings.Create(c => c .ConfigureType <MultiTableConverterObject>(tc => tc .WithConversionFor <TomlString>(conv => conv .ToToml(o => o.ToString()) .FromToml(s => MultiTableConverterObject.Parse(s.Value))))); var cfg = Config.CreateAs() .MappedToType(() => new Root()) .UseTomlConfiguration(tmlCfg) .StoredAs(s => s.File(fn)) .Initialize(); // Act cfg.Set(c => c.ConvertedItem.UnitItem.Unit, "B"); // Assert var tbl = Toml.ReadFile <Root>(fn, tmlCfg); tbl.ConvertedItem.UnitItem.Unit.Should().Be("B"); } }
private static void LoadConfig() { string configPath = Path.Combine(Paths.ConfigPath, "Config.toml"); var tomlSettings = TomlSettings.Create(builder => builder .ConfigureType <Version>(type => type .WithConversionFor <TomlString>(convert => convert .ToToml(tt => tt.ToString()) .FromToml(ft => Version.Parse(ft.Value))))); var oldConfig = File.Exists(configPath) ? Toml.ReadFile <EnvironmentConfig>(configPath, tomlSettings) : null; var version = oldConfig?.Version ?? new Version(0, 0, 0); var daemon = oldConfig?.Daemon ?? CreateDefaultDaemonConfig(); var cache = oldConfig?.Cache ?? CreateDefaultCacheConfig(); Toml.WriteFile(new EnvironmentConfig(AmoebaEnvironment.Version, daemon, cache), configPath, tomlSettings); Config = new EnvironmentConfig(version, daemon, cache); EnvironmentConfig.CacheConfig CreateDefaultCacheConfig() { return(new EnvironmentConfig.CacheConfig("../Config/Cache.blocks")); } EnvironmentConfig.DaemonConfig CreateDefaultDaemonConfig() { return(new EnvironmentConfig.DaemonConfig("tcp:127.0.0.1:4040")); } }
public void WriteGuidToml() { var obj = new TableContainingMoney() { NotSupported = new Money() { Ammount = 9.99m, Currency = "EUR" } }; //var config = TomlConfig.Create(cfg => cfg // .ConfigureType<decimal>(type => type // .WithConversionFor<TomlFloat>(convert => convert // .ToToml(dec => (double)dec) // .FromToml(tf => (decimal)tf.Value)))); var config = TomlSettings.Create(cfg => cfg .ConfigureType <Money>(type => type .WithConversionFor <TomlString>(convert => convert .ToToml(custom => custom.ToString()) .FromToml(tmlString => Money.Parse(tmlString.Value))))); //var config = TomlConfig.Create(); var s = Toml.WriteString(obj, config); var read = Toml.ReadString <TableContainingMoney>(s, config); }
public void WriteToml_WhenConfigHasConverter_ConverterGetsUsed() { // Arrange var config = TomlSettings.Create(cfg => cfg .ConfigureType <TestStruct>(ct => ct .WithConversionFor <TomlInt>(conv => conv .FromToml((m, ti) => new TestStruct() { Value = (int)ti.Value }) .ToToml(ts => ts.Value) ) .CreateInstance(() => new TestStruct()) .TreatAsInlineTable() ) ); var obj = new ConfigObject() { S = new TestStruct() { Value = 222 } }; // Act var ser = Toml.WriteString(obj, config); // Assert Assert.Equal("S = 222\r\n", ser); }
private TomlSettings CreateTomlSettings() { var settings = TomlSettings.Create(s => s .ConfigurePropertyMapping(m => m .UseTargetPropertySelector(standardSelectors => standardSelectors.IgnoreCase)) .ConfigureType <DateOnlyDefinition>(type => type .WithConversionFor <TomlString>(convert => convert .FromToml(ConvertShorthandDateOnlySyntax))) .ConfigureType <TimeOnlyDefinition>(type => type .WithConversionFor <TomlString>(convert => convert .FromToml(ConvertShorthandTimeOnlySyntax))) .ConfigureType <TimestampDefinition>(type => type .WithConversionFor <TomlString>(convert => convert .FromToml(ConvertShorthandTimestampSyntax))) .ConfigureType <List <TimestampDefinition> >(type => type .WithConversionFor <TomlTableArray>(convert => convert .FromToml(ConvertTimeStampList))) .ConfigureType <PropertyDefinition>(type => type .WithConversionFor <TomlString>(convert => convert .FromToml(ConvertShorthandPropertySyntax))) .ConfigureType <PropertyDefinition>(type => type .WithConversionFor <TomlInt>(convert => convert .FromToml(ConvertShorthandColumnIndex))) .ConfigureType <Regex>(type => type .WithConversionFor <TomlString>(convert => convert .FromToml(ConvertRegexFromString))) .ConfigurePropertyMapping(m => m .OnTargetPropertyNotFound(WhenTargetPropertyNotFound)) ); return(settings); }
/// <summary> /// Loads the lower case toml settings. /// </summary> /// <returns></returns> public static TomlSettings LoadLowerCaseTomlSettings() { var fieldNamesToLowerCaseSettings = TomlSettings.Create(config => config .ConfigurePropertyMapping(mapping => mapping .UseKeyGenerator(standardGenerators => standardGenerators.LowerCase))); return(fieldNamesToLowerCaseSettings); }
public void ActivateAll() { var config = TomlSettings.Create(cfg => cfg.AllowImplicitConversions(TomlSettings.ConversionSets.All)); var tbl = Toml.ReadString("f = 0.99", config); var i = tbl.Get <int>("f"); i.Should().Be(1); }
public void WriteStream_SetsStreamPositionTo0AfterWritingSoThatItIsReadoToBeReadAgain() { using (var s = new MemoryStream()) { Toml.WriteStream(CreateFoo(), s, TomlSettings.Create()); s.Position.Should().Be(0); } }
public void ActivateNone() { var config = TomlSettings.Create(cfg => cfg.AllowImplicitConversions(TomlSettings.ConversionSets.None)); var tbl = Toml.ReadString("i = 1", config); // var i = tbl.Get<int>("i"); // Would throw InvalidOperationException as event cast from TomlInt to int is not allowed var i = tbl.Get <long>("i"); // Only this will work i.Should().Be(1); }
private static TomlTable SetupConversionSetTest(TomlSettings.ConversionSets set, string tomlInput) { var config = TomlSettings.Create(cfg => cfg .AllowImplicitConversions(set) ); TomlTable table = Toml.ReadString(tomlInput, config); return(table); }
public void Write_WhenTblArrayValueTypeIsConfiguredAsInlineTable_ThatTypeIsWrittenAsAnInlineTable() { var config = TomlSettings.Create(cfg => cfg.ConfigureType <Item>(type => type.TreatAsInlineTable())); var s = Toml.WriteString(InlineArray.TwoItems, config); s.Should().Be(InlineArray.ExpectedTwoItems); }
public void Write_WhenDictionaryValueTypeIsConfiguredAsInlineTable_ThatTypeIsWrittenAsAnInlineTable() { var config = TomlSettings.Create(cfg => cfg.ConfigureType <Item>(type => type.TreatAsInlineTable())); var s = Toml.WriteString(ItemDict.TwoItems, config); s.Should().Be(ItemDict.TwoItemsInlineSerialzed); }
public void HandleComputedType() { var c = new Computed(); var config = TomlSettings.Create(cfg => cfg .ConfigureType <Computed>(type => type .IgnoreProperty(o => o.Z))); var w = Toml.WriteString(c, config); var r = Toml.ReadString <Computed>(w, config); }
private MoneyScenario(string test) { this.FilePath = TestFileName.Create("money", Toml.FileExtension, test); this.TmlConfig = TomlSettings.Create(cfg => cfg .ConfigureType <Money>(typeConfig => typeConfig .WithConversionFor <TomlString>(conversion => conversion .ToToml(m => m.ToString()) .FromToml(s => Money.Parse(s.Value))))); }
public void Write_WithEmptyInlineTableArray_WritesNothingToTheFile() { var config = TomlSettings.Create(cfg => cfg.ConfigureType <Item>(type => type.TreatAsInlineTable())); var s = Toml.WriteString(InlineArray.Empty, config); s.Should().Be(InlineArray.ExpectedEmpty); }
public void Write_WhenDictIsMarkedAsInline_WritesDictAsInlineAndItemsAutomaticallyAsNestedInlineTables() { var config = TomlSettings.Create(cfg => cfg.ConfigureType <Dictionary <string, Item> >(type => type.TreatAsInlineTable())); var s = Toml.WriteString(ItemDict.TwoItems, config); s.Should().Be(ItemDict.TwoItemsDictInlineSerialized); }
public void WriteStream_WithConfig_WritesToStream() { using (var s = new MemoryStream()) { Toml.WriteStream(CreateFoo(), s, TomlSettings.Create()); var read = Toml.ReadStream <Foo>(s); read.X.Should().Be(1); } }
private static TomlObjectType GetTargetType(Type memberType, TomlSettings settings) { TomlObjectType GetTargetTypeFromArrayType() { var et = memberType.GetElementType(); if (et != null) { return(GetTargetTypeFromElementType(et)); } return(TomlObjectType.Array); } TomlObjectType GetTargetTypeFromEnumerableType() { if (memberType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(memberType)) { var ga = memberType.GetGenericArguments(); if (ga.Length == 1) { return(GetTargetTypeFromElementType(ga[0])); } } return(TomlObjectType.Array); } TomlObjectType GetTargetTypeFromElementType(Type eleType) { var tt = GetTargetType(eleType, settings); return(tt == TomlObjectType.Table ? TomlObjectType.ArrayOfTables : TomlObjectType.Array); } var converter = settings.TryGetToTomlConverter(memberType); if (converter != null) { return(converter.TomlTargetType.Value); } if (memberType.IsArray) { return(GetTargetTypeFromArrayType()); } else if (typeof(IEnumerable).IsAssignableFrom(memberType)) { return(GetTargetTypeFromEnumerableType()); } return(TomlObjectType.Table); }
public void Write_WithClassProperty_WritesObjectCorrectly() { // Arrange var tc = new WithClassProperty() { StringProp = "sp", IntProp = 10, ClassProp = new ClassProperty() { StringProp = "isp", IntProp = 100, IntList = new List <int>() { 1, 2 }, StringArray = new string[] { "A", "B" }, ConvProp = new ConvProp() { Prop = "cp" }, }, Acp = new List <ArrayClassProp>() { new ArrayClassProp() { V = 666 } }, }; var cfg = TomlSettings.Create(config => config .ConfigureType <ConvProp>(ct => ct .WithConversionFor <TomlString>(conv => conv .ToToml(cp => cp.Prop)))); // Act var exp = @"IntProp = 10 StringProp = ""sp"" [ClassProp] StringProp = ""isp"" IntProp = 100 IntList = [1, 2] StringArray = [""A"", ""B""] ConvProp = ""cp"" [[Acp]] V = 666 "; var s = Toml.WriteString(tc, cfg); // Assert Assert.Equal(exp.Trim(), s.Trim()); }
public Task RunAsync <T>(T input) { var settings = TomlSettings.Create(cfg => cfg .ConfigureType <decimal>(ct => ct .WithConversionFor <TomlString>(conv => conv .ToToml(s => s.ToString("C"))))); Console.WriteLine(Nett.Toml.WriteString(input, settings)); return(Task.CompletedTask); }