Roger-luo / Configurations.jl

Options & Configurations made easy.

Home Page:https://configurations.rogerluo.dev/stable

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Alternative to `toml_convert(::Type, x)` from v0.11?

chenspc opened this issue · comments

In v0.11, I was overloading toml_convert to customise printing for Enum types so that it prints to Int when exporting and back to Enum when loading from file. This doesn't seem to work anymore since 0.12. Do you have any suggestions for how to do it in the new version? Thanks!

(@v1.5) pkg> st Configurations
Status `~/.julia/environments/v1.5/Project.toml`
  [5218b696] Configurations v0.11.0
julia> using Configurations

julia> @enum Fruit begin
           Apple = 1
           Orange = 2
       end

julia> @option struct Box
           item::Fruit = Apple
           number::Int = 5
       end

julia> import Configurations: toml_convert

julia> toml_convert(::Type, x::Fruit) = Int(x)
toml_convert (generic function with 4 methods)

julia> to_toml(Box(; item=Orange))
"item = 2\n"

julia> to_toml("box.toml", Box(; item=Orange))

julia> import Base: convert

julia> convert(::Type{Fruit}, x::Int) = Fruit(x)
convert (generic function with 186 methods)

julia> from_toml(Box, "box.toml")
Box(;
    item = Orange::Fruit = 2,
)

yes, from 0.12 the lowering conversion is unified to overload to_dict, checkout the example here: https://github.com/Roger-luo/Configurations.jl/blob/master/src/serialize.jl#L33

you can also keep using 0.11, but note since this package is not yet 1.0 there won't be a compatibility guarantee at the moment (that means if we find this new design has flaws we may change it back, or use something else)


PS. unfortunately, this interface change can't be made compatible using @deprecate

I'll explain a bit the logic of this underlying change here in case someone else see it and want to join the discussion:

previously toml_convert is a very specific conversion rule for TOML, thus as a result when one wants to write a schema using this package, e.g for REST API, and hope to be able to convert to both TOML and JSON,
the conversion rule will need to be written twice.

however, the to_toml function actually have an interface to let you define TOML specific conversion rule, which is to_toml(f, io, d) where the first function is the TOML specific conversion, which is the same as TOML.print, thus these two interfaces are duplicated. So I removed toml_convert and make to_dict overloadable.

To be simple, for general lowering (which means converting option types to other format), overload to_dict, for TOML specific conversion, use your own conversion function and the to_toml(f, io, d) interface.

Thanks very much for the explanation, I'll give it a try :)