Skip to content
This repository has been archived by the owner on Oct 19, 2020. It is now read-only.

How to preserve sections/values structure when using Toml.WriteFile? #77

Open
Krakean opened this issue Jun 1, 2019 · 1 comment
Open

Comments

@Krakean
Copy link

Krakean commented Jun 1, 2019

@paiden
Hello
Not sure that I specified issue title correctly in context of describing my problem, but anyway
I would like to use Nett for configuration purposes, currently my config file is using such structure:

[Temp]
IntVal = 1
StrVal = "qwe"
BoolVal = true

[System]
LoggerIncludeTime = 3
LoggerVerbosity = 5
LoggerSpamDelay = 0

This is how I load it:
TomlTable _cfg = Toml.ReadFile(filepath)

And this is how I would like to work with it:
var value = ReadInt("Temp.IntVal", 5);

And this is how my ReadInt looks like:

   public int ReadInt(in string str, int defVal, bool createIfNone = true)
   {
       if (!_cfg.ContainsKey(str))
       {
           if (createIfNone)
               _cfg.Add(str, defVal);
           return defVal;
       }

       return _cfg.Get<int>(str);
   }

But once I do Toml.WriteFile(_cfg, filepath) on program quit (to save changes made to config file), I get config file with such content:

'Temp.IntVal' = 5
'Temp.StrVal' = "bla"
'Temp.BoolVal' = false
'Temp.NonExistsVal' = "yoyo"
'System.LoggerIncludeTime' = 3
'System.LoggerVerbosity' = 4
'System.LoggerSpamDelay' = 0

[Temp]
IntVal = 1
StrVal = "qwe"
BoolVal = true

[System]
LoggerIncludeTime = 3
LoggerVerbosity = 5
LoggerSpamDelay = 0`

And this is what I expected to see:

[Temp]
IntVal = 5
StrVal = "bla"
BoolVal = false
NonExistsVal = "yoyo"

[System]
LoggerIncludeTime = 3
LoggerVerbosity = 4
LoggerSpamDelay = 0`

Tell me please what I do wrong? And how can I see preserve section/keys structure?
Currently I do not use any writes to config file, but was thinking to have WriteInt() like this:
public void WriteInt(in string str, int value) => _cfg.Update(str, value);
and it like: WriteInt("Temp.IntVal", 5)
I guess, this is also wrong way to write values?

@paiden
Copy link
Owner

paiden commented Jun 2, 2019

Your ReadInt method does not read the configuration values correctly. It never finds a config value and therefore adds it as a new row to the root table with an escaped key.

The Get methods of a toml table does only work for entries of that table, it will not return values of any sub tables. Therefore it is not valid to use 'dotted' keys as key parameters for this method.

To e.g. get the value of IntValue you would have to do:

var intValue = _cfg.Get<TomlTable>("Temp").Get<int>("IntVal")

not

var intValue = _cfg.Get<int>("Temp.IntVal")

HTH

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants