pelletier / go-toml

Go library for the TOML file format
https://github.com/pelletier/go-toml
Other
1.69k stars 206 forks source link

parse incorrect #817

Closed 60ke closed 1 year ago

60ke commented 1 year ago

Describe the bug parse result incorrect

To Reproduce

package main

import (
    "fmt"
    "os"

    "github.com/pelletier/go-toml"
)

var tomlStrFalse = `
[[tm]]
  ip = "192.168.1.1"

tm-server = "127.0.0.1"
`
var tomlStrTrue = `
tm-server = "127.0.0.1"
[[tm]]
  ip = "192.168.1.1"
`

type TMConf struct {
    IP string `toml:"ip"`
}

type Config struct {
        TM     []TMConf `toml:"tm"`
    Server string   `toml:"tm-server"`

}

func main() {
    var conf1 Config
    var conf2 Config
    toml.Unmarshal([]byte(tomlStrTrue), &conf1)
    toml.Unmarshal([]byte(tomlStrFalse), &conf2)
    fmt.Println(conf1.Server, conf2.Server)
    f, _ := os.Create("./test.toml")
        defer f.Close()
    enc := toml.NewEncoder(f)
        enc.Order(toml.OrderPreserve)
    enc.Encode(conf1)

}

Expected behavior conf1 should same as conf2,or may test.toml should include like tm-server's value,but now test.toml is:

[[tm]]
  ip = "192.168.1.1"
tm-server = "127.0.0.1"

Versions

pelletier commented 1 year ago

I don't think those two documents are equivalent. Indentation doesn't matter in TOML. The first document has tm-server as part of the first element of the tm array. The second document has it as an element at the root of the document.

60ke commented 1 year ago
enc.Order(toml.OrderPreserve)

You are right,but if you use enc.Order(toml.OrderPreserve) to sort the second-element,and save to file, you will see that the key : tm-server be blank

moorereason commented 1 year ago

tm-server is blank because the tomlStrFalse TOML document doesn't match your data model. Try using the Decoder in Strict mode, and you should see the problem.

60ke commented 1 year ago
  f, _ := os.Create("./test.toml")
        defer f.Close()

Maybe I didn't express it clearly enough, I mean if encode order,may casue the root key move down,like

tm-server = "127.0.0.1"
[[tm]]
  ip = "192.168.1.1"

if order,toml-server will move down,And then it doesn't mean what it meant。

pelletier commented 1 year ago

Just realized that you are using go-toml v1, which is not supported since April. go-toml v2 outputs this data structure correctly:

https://go.dev/play/p/MyG9A2t-HGc

60ke commented 1 year ago

Just realized that you are using go-toml v1, which is not supported since April. go-toml v2 outputs this data structure correctly:

https://go.dev/play/p/MyG9A2t-HGc

yes, go-toml v2 is ok, thanks for you reply