go-yaml / yaml

YAML support for the Go language.
Other
6.85k stars 1.05k forks source link

Octal number marshalling #420

Open ulyssessouza opened 5 years ago

ulyssessouza commented 5 years ago

Hello, I'm still not sure if it's a question or a feature request. Is there is a way of marshalling an octal number? Because when unmarshalling this : number: 0660 I get: number: 432

And if I implement Marshaler I get: number: "0660" (the string "0660") an not: number: 0660 (the octal number)

When implementing jsonNumber I get the same

niemeyer commented 5 years ago

It's a valid feature request. It should be easy to support that via something like an ",octal" field tag.

ulyssessouza commented 5 years ago

@niemeyer The problem with an ",octal" field tag is that it's fixed. At least in my case, the formatting will depend on the input, because my program's life cycle consists in unmarshal -> modify -> marshal. So the output format will depend on the input format. The ideal would be using a "numeric struct" that has an integer and a string to map the value and format. Something like that. WDYT?

niemeyer commented 5 years ago

I'm working on v3 at the moment, which will offer an intermediate state with significantly more control than what the package offers today. There's a quick draft of what it will look like here:

https://twitter.com/gniemeyer/status/1073638853225996288

With that you'll be able to marshal your value easily, with the exact formatting you want.

ulyssessouza commented 5 years ago

Just for curiosity... (No pressure at all) Is the v3 repository public? Do you have any delivery estimation?

niemeyer commented 5 years ago

I'll make it widely available soon. I just want to lock down on the compatibility breakages (MapSlice is coming out and be replaced by nodes, marshaling interfaces will also be based on Node, etc), and then will put it out for early testing.

AvdN commented 5 years ago

Finally another YAML library that recognises that comments warrant preserving in a human readable data format!

shibe2 commented 4 years ago

README.md says:

Octals encode and decode as 0777 per YAML 1.1, rather than 0o777 as specified in YAML 1.2, because most parsers still use the old format.

So, how do I encode integers to octal representation?

shibe2 commented 4 years ago

In the meantime, this is how you can encode with 0o prefix:

type OctalMode os.FileMode

func (self OctalMode) String() string {
    return "0o" + strconv.FormatUint(uint64(self), 8)
}

func (self OctalMode) MarshalYAML() (interface{}, error) {
    return &yaml.Node{
        Kind:  yaml.ScalarNode,
        Tag:   "!!int",
        Value: self.String(),
    }, nil
}

In fact, this way you can encode to any number format supported by decoder. One drawback to this approach is that you'll have to convert between the formatter type (here OctalMode) and the type you need (here os.FileMode). It would be easier if encoder had number format options.