Esempio n. 1
0
        /// <summary>
        ///     Reads an stream containing a toml file and returns an object.
        /// </summary>
        /// <param name="type">object Type to be deserialized</param>
        /// <param name="data">The stream containing toml</param>
        /// <param name="refPath">The path to file name containing toml data.</param>
        /// <returns>An object deserialized from file content.</returns>
        public object Read(Type type, Stream data, string refPath)
        {
            var tomlTable = Toml.Parse(new StreamReader(data).ReadToEnd());
            var parent    = GetInheritInstanceFromDirective(type, tomlTable, refPath);

            return(ConvertTable(type, tomlTable.ToModel(), parent));
        }
        private int EncryptFile(string file)
        {
            try
            {
                var table   = Toml.Parse(File.ReadAllText(file));
                var changes = 0;
                foreach (var keyValue in GetAllProperties(table))
                {
                    if (keyValue.Value is StringValueSyntax token &&
                        EncryptValue(token.Value, out var cypher))
                    {
                        keyValue.Value = new StringValueSyntax(cypher);
                        changes++;
                    }
                }


                WriteDocument(file, table);
                return(changes);
            }
            catch (Exception ex)
            {
                throw new TomlConfigurationException(
                          $"Error while encrypting '{Path.GetRelativePath(Environment.CurrentDirectory, file)}'\n\t" +
                          ex.Message);
            }
        }
Esempio n. 3
0
        public void ShouldGetAllChildren()
        {
            var doc   = Toml.Parse("A=1\nB=2\n[C]\nD=3");
            var total = doc.GetAllKeys().Sum(x => int.Parse(x.Value.ToString()));

            Check.That(total).IsEqualTo(6);
        }
Esempio n. 4
0
        public static void TestPrimitives()
        {
            var input  = @"a = 1
b = true
c = 1.0
d = 'yo'
e = 1980-01-20
";
            var syntax = Toml.Parse(input);

            Assert.False(syntax.HasErrors, "The document should not have any errors");

            var model = syntax.ToModel();

            Assert.True(model.ContainsKey("a"));
            Assert.True(model.ContainsKey("b"));
            Assert.True(model.ContainsKey("c"));
            Assert.True(model.ContainsKey("d"));
            Assert.True(model.ContainsKey("e"));

            Assert.AreEqual(5, model.Count);
            Assert.AreEqual((long)1, model["a"]);
            Assert.AreEqual(true, model["b"]);
            Assert.AreEqual(1.0, model["c"]);
            Assert.AreEqual("yo", model["d"]);
            Assert.AreEqual(new DateTime(1980, 01, 20), model["e"]);
        }
        private int DecryptFile(string file)
        {
            try
            {
                var table = Toml.Parse(File.ReadAllText(file));
                var found = 0;
                foreach (var keyValue in GetAllProperties(table))
                {
                    if (keyValue.Value is StringValueSyntax token &&
                        DecryptValue(token.Value, out var cypher))
                    {
                        keyValue.Value = new StringValueSyntax(cypher);
                        found++;
                        continue;
                    }

                    Console.Write($"Failed to decrypt {keyValue}");
                }


                WriteDocument(file, table);
                return(found);
            }
            catch (Exception ex)
            {
                throw new TomlConfigurationException(
                          $"Error while decrypting '{Path.GetRelativePath(Environment.CurrentDirectory, file)}'\n\t" +
                          ex.Message);
            }
        }
        private int VerifyFile(string file)
        {
            try
            {
                var table    = Toml.Parse(File.ReadAllText(file));
                var verified = 0;
                foreach (var keyValue in GetAllProperties(table))
                {
                    verified++;

                    if (keyValue.Value is StringValueSyntax token)
                    {
                        VerifyValue(token.Value, keyValue.Key.ToString());
                    }
                }

                if (verified == 0)
                {
                    Console.WriteLine($"No Key matched specified filters : \n {string.Join("\n", configKeyNames)}");
                }

                WriteDocument(file, table);
                return(verified);
            }
            catch (Exception ex)
            {
                throw new TomlConfigurationException(
                          $"Error while verifying '{Path.GetRelativePath(Environment.CurrentDirectory, file)}'\n\t" +
                          ex.Message);
            }
        }
Esempio n. 7
0
        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.
                }
            }
        }
Esempio n. 8
0
        public bool ReadString(string str)
        {
            const string tableName = App.ConfigTable;
            var          doc       = Toml.Parse(str);

            if (doc.HasErrors)
            {
                return(false); //解析错误则返回失败
            }

            //使用Toml库解析
            var table     = doc.ToModel();
            var tomlTable = (TomlTable)table[tableName];

            //反射自动导入所有属性
            Type t = typeof(TomlConfig);

            FieldInfo[] infos = t.GetFields();
            foreach (FieldInfo info in infos)
            {
                if (tomlTable.ContainsKey(info.Name))
                {
                    info.SetValue(this, Convert.ChangeType(((TomlTable)table[tableName])[info.Name], info.FieldType));
                }
                else
                {
                    return(false); //key错误则返回
                }
            }

            return(true);
        }
Esempio n. 9
0
        public void ShouldEncryptFile()
        {
            var file = Guid.NewGuid().ToString();

            File.WriteAllText(file, "MyPassword = \"ABC\"");

            var key = Guid.NewGuid().ToString();

            var subject = new ConfigToolImplementation(new List <string> {
                file
            }, false,
                                                       key, new List <string>
            {
                ".+Password.+"
            });

            subject.Encrypt();

            var table = Toml.Parse(File.ReadAllText(file));

            var keeper = new SecretKeeper(key);

            Check.That(keeper.Decrypt(table.ToModel()["MyPassword"].ToString()))
            .IsEqualTo("ABC");
        }
        public CredentialManager()
        {
            if (File.Exists(upmconfigFile))
            {
                var upmconfig = Toml.Parse(File.ReadAllText(upmconfigFile));
                if (upmconfig.HasErrors)
                {
                    Debug.LogError("Cannot load upmconfig, invalid format");
                    return;
                }


                TomlTable table = upmconfig.ToModel();

                TomlTable auth = (TomlTable)table["npmAuth"];
                if (auth != null)
                {
                    foreach (var registry in auth)
                    {
                        NPMCredential cred = new NPMCredential();
                        cred.url = registry.Key;
                        TomlTable value = (TomlTable)registry.Value;
                        cred.token      = (string)value["token"];
                        cred.alwaysAuth = (bool)value["alwaysAuth"];

                        credentials.Add(cred.url, cred);
                    }
                }
            }
        }
Esempio n. 11
0
        public static void TestTable()
        {
            var input  = @"a = 1
[b]
c = 1
d = true
";
            var syntax = Toml.Parse(input);

            Assert.False(syntax.HasErrors, "The document should not have any errors");

            var model = syntax.ToModel();

            Assert.True(model.ContainsKey("a"));
            Assert.True(model.ContainsKey("b"));
            Assert.AreEqual(2, model.Count);
            Assert.AreEqual((long)1, model["a"]);
            Assert.IsInstanceOf <TomlTable>(model["b"]);
            var subTable = ((TomlTable)model["b"]);

            Assert.True(subTable.ContainsKey("c"));
            Assert.True(subTable.ContainsKey("d"));
            Assert.AreEqual(2, subTable.Count);
            Assert.AreEqual((long)1, subTable["c"]);
            Assert.AreEqual((bool)true, subTable["d"]);
        }
Esempio n. 12
0
        public void Parse()
        {
            var confdir = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "tcli"
                );
            var confpath = Path.Combine(
                confdir, "auth.conf"
                );

            Directory.CreateDirectory(confdir);

            string configText;

            if (!File.Exists(confpath))
            {
                configText = GetDefaultToml();
                File.WriteAllText(confpath, configText);
            }
            else
            {
                configText = File.ReadAllText(confpath);
            }

            var configDoc = Toml.Parse(configText).ToModel();
            //authConfig = new AuthConfig()
            //{
            //    DefaultToken = (string)((TomlTable)configDoc["auth"])["defaultToken2222"],
            //    AuthorTokens = new()
            //};
        }
Esempio n. 13
0
        /// <summary>
        /// We will configure the database here.
        /// Server apps will get to configure themselves in PrivateConfig.
        /// </summary>
        public void Configure()
        {
            // Set up the logger first.
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.Console()
                         .WriteTo.File("logs/log-.log", rollingInterval: RollingInterval.Day)
                         .CreateLogger();

            Console.Title = GetServerName();
            Log.Information(GetServerName()
                            + Environment.NewLine
                            + new string('-', GetServerName().Length + 24));

            var db    = Toml.Parse(File.ReadAllText("db.toml")).ToModel();
            var table = (TomlTable)db["db"];

            Configuration.Database.Host     = (string)table["host"];
            Configuration.Database.Database = (string)table["database"];
            Configuration.Database.Username = (string)table["username"];
            Configuration.Database.Password = (string)table["password"];

            // We can initialize the database first in Preconfigure if needed.
            Preconfigure();

            if (!Database.Setup(DatabaseType.MySql, Configuration.Database))
            {
                // We've failed and already sent the stack trace to the logs.
                // We can just wait for a keypress and exit.
                Console.ReadKey();
                Environment.Exit(1);
            }

            PopulatePacketHandlers();
        }
Esempio n. 14
0
        public void TestEmptyComment()
        {
            var input    = "#\n";
            var doc      = Toml.Parse(input);
            var docAsStr = doc.ToString();

            Assert.AreEqual(input, docAsStr);
        }
Esempio n. 15
0
 public CompilationContext(string compilerflagsToml = "CompilerFlags.toml", bool logToConsole = true)
 {
     _compilerFlags = Toml.Parse(File.ReadAllText(compilerflagsToml)).ToModel();
     _callStack     = new Stack <CallSite>();
     if (logToConsole)
     {
         this.StartLoggingToConsole();
     }
 }
Esempio n. 16
0
        public override void PrivateConfigure()
        {
            var login = Toml.Parse(File.ReadAllText("login.toml")).ToModel();
            var table = (TomlTable)login["loginserver"];

            port = (int)(long)table["port"]; // Tomlyn reads ints as longs, so cast to long and then int.

            WorldState.StartRefreshWorker();
        }
Esempio n. 17
0
        public void TestNoErrors()
        {
            var input = @"a = 1";
            var doc   = Toml.Parse(input);

            Assert.False(doc.HasErrors, "The document should not have any errors");
            var docAsStr = doc.ToString();

            Assert.AreEqual(input, docAsStr);
        }
Esempio n. 18
0
        public static OneOf <AppConfig, DiagnosticsBag> FromConfigPath(string configPath)
        {
            var syntaxTree = Toml.Parse(File.ReadAllText(configPath));

            if (syntaxTree.HasErrors)
            {
                return(syntaxTree.Diagnostics);
            }

            return(new AppConfig(syntaxTree));
        }
Esempio n. 19
0
        public void TestRedefineKey()
        {
            var input     = @"a = 1
a = true
";
            var doc       = Toml.Parse(input);
            var roundTrip = doc.ToString();

            StandardTests.Dump(input, doc, roundTrip);
            Assert.True(doc.HasErrors, "The document should have errors");
        }
Esempio n. 20
0
 internal static bool Load(MemoryStream stream)
 {
     try {
         string ConfigText = System.Text.Encoding.UTF8.GetString(stream.ToArray());
         var    Data       = Toml.Parse(ConfigText);
         return(Parse(Data));
     }
     catch (Exception ex) {
         ex.PrintWarning();
         return(false);
     }
 }
Esempio n. 21
0
        public void TestShortDateKey()
        {
            var input = "2018-01-01=123";

            var syntax = Toml.Parse(input);

            Assert.False(syntax.HasErrors, "The document should not have any errors");

            var model = syntax.ToModel();

            Assert.True(model.ContainsKey("2018-01-01"));
        }
Esempio n. 22
0
        public void TestFullDateKey()
        {
            var input = "\"1987-07-05T17:45:00Z\"=123";

            var syntax = Toml.Parse(input);

            Assert.False(syntax.HasErrors, "The document should not have any errors");

            var model = syntax.ToModel();

            Assert.True(model.ContainsKey("1987-07-05T17:45:00Z"));
        }
        public async Task CreateTelegraf()
        {
            var name = GenerateName("Telegraf");

            var output = NewOutputPlugin();
            var cpu    = NewCpuPlugin();

            var telegrafConfig = await _telegrafsApi
                                 .CreateTelegrafAsync(name, "test-config", _organization,
                                                      new List <TelegrafPlugin> {
                output, cpu
            });

            Assert.IsNotNull(telegrafConfig);
            Assert.AreEqual(name, telegrafConfig.Name);
            Assert.AreEqual("test-config", telegrafConfig.Description);
            Assert.AreEqual(_organization.Id, telegrafConfig.OrgID);

            Assert.IsNotNull(telegrafConfig.Metadata);
            Assert.IsNotNull(telegrafConfig.Metadata.Buckets);
            Assert.AreEqual(1, telegrafConfig.Metadata.Buckets.Count);

            var toml  = Toml.Parse(telegrafConfig.Config).ToModel();
            var agent = (TomlTable)toml["agent"];

            Assert.IsNotNull(agent);
            Assert.AreEqual("10s", agent["interval"]);
            Assert.IsTrue((bool)agent["round_interval"]);
            Assert.AreEqual(1000, agent["metric_batch_size"]);
            Assert.AreEqual(10000, agent["metric_buffer_limit"]);
            Assert.AreEqual("0s", agent["collection_jitter"]);
            Assert.AreEqual("0s", agent["flush_jitter"]);
            Assert.AreEqual("", agent["precision"]);
            Assert.IsFalse((bool)agent["omit_hostname"]);

            var tomlInflux = (TomlTableArray)((TomlTable)toml["outputs"])["influxdb_v2"];

            Assert.AreEqual(1, tomlInflux.Count);
            Assert.AreEqual("my-bucket", tomlInflux[0]["bucket"]);
            Assert.AreEqual("my-org", tomlInflux[0]["organization"]);
            Assert.AreEqual("$INFLUX_TOKEN", tomlInflux[0]["token"]);
            Assert.AreEqual(1, ((TomlArray)tomlInflux[0]["urls"]).Count);
            Assert.AreEqual("http://localhost:9999", ((TomlArray)tomlInflux[0]["urls"])[0]);

            var tomlCpu = (TomlTableArray)((TomlTable)toml["inputs"])["cpu"];

            Assert.AreEqual(1, tomlCpu.Count);
            Assert.IsTrue((bool)tomlCpu[0]["totalcpu"]);
            Assert.IsFalse((bool)tomlCpu[0]["collect_cpu_time"]);
            Assert.IsFalse((bool)tomlCpu[0]["report_active"]);
            Assert.IsTrue((bool)tomlCpu[0]["percpu"]);
        }
Esempio n. 24
0
        public void TestTableArrayNested()
        {
            var input     = @"[[a]]
b = 1
[[a.c]]
b = true
";
            var doc       = Toml.Parse(input);
            var roundTrip = doc.ToString();

            StandardTests.Dump(input, doc, roundTrip);
            Assert.False(doc.HasErrors, "The document should not have any errors");
        }
        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);
        }
Esempio n. 26
0
    private static DocumentSyntax GetTomlSyntax(string content)
    {
        var responseToml = Toml.Parse(content);

        _ = responseToml ?? throw new ResponseContentException("Empty response from Bindle server");

        if (responseToml.HasErrors)
        {
            var errors = String.Join(", ", responseToml.Diagnostics.Select(d => d.Message));
            throw new ResponseContentException($"Invalid response from Bindle server: {errors}");
        }
        return(responseToml);
    }
        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);
        }
Esempio n. 28
0
        public void TestTableArrayAndInvalidTable()
        {
            var input     = @"[[a]]
b = 1
[[a.b]]
c = true
[a.b]
d = true
";
            var doc       = Toml.Parse(input);
            var roundTrip = doc.ToString();

            StandardTests.Dump(input, doc, roundTrip);
            Assert.True(doc.HasErrors, "The document should have errors");
        }
        public void Import(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("Can't import missing file.", path);
            }

            var bytes    = File.ReadAllBytes(path);
            var imported = Toml.Parse(bytes, path);

            foreach (var kv in imported.KeyValues)
            {
                var targetKv = _toml.KeyValues.FirstOrDefault(x => x.Key == kv.Key);
                if (targetKv == null)
                {
                    _toml.KeyValues.Add(kv);
                }
                else
                {
                    targetKv.Value = kv.Value;
                }
            }

            foreach (var t in imported.Tables)
            {
                var targetT = _toml.Tables.FirstOrDefault(x => x.Name == t.Name);
                if (targetT != null)
                {
                    _toml.Tables.Add(t);
                }
                else
                {
                    foreach (var kv in t.Items)
                    {
                        var targetKv = _toml.KeyValues.FirstOrDefault(x => x.Key != kv.Key);
                        if (targetKv == null)
                        {
                            _toml.KeyValues.Add(kv);
                        }
                        else
                        {
                            targetKv.Value = kv.Value;
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        internal static bool Load(string ConfigPath)
        {
            if (!File.Exists(ConfigPath))
            {
                return(false);
            }

            try {
                string ConfigText = File.ReadAllText(ConfigPath);
                var    Data       = Toml.Parse(ConfigText, ConfigPath);
                return(Parse(Data));
            }
            catch (Exception ex) {
                ex.PrintWarning();
                return(false);
            }
        }