Parsing ProtoBuf Text Format

Thanks!

I was able to build this solution:

using ProtoBuf
using protoc_jll

export protobuf_from_text, protobuf_to_text

# important: .proto files are required in runtime!

const _proj_path = normpath(joinpath(@__FILE__, "..", ".."))
const _proto_path = joinpath(_proj_path, "common")    
const _plugin_dir = abspath(joinpath(dirname(pathof(ProtoBuf)), "..", "plugin"))
const _plugin = joinpath(_plugin_dir, Sys.iswindows() ? "protoc-gen-julia_win.bat" : "protoc-gen-julia")
const ENV_ = copy(ENV)
ENV_["PATH"] = string(_plugin_dir, Sys.iswindows() ? ";" : ":", ENV_["PATH"])
ENV_["JULIA"] = joinpath(Sys.BINDIR, Base.julia_exename())

function protobuf_from_text(input::String, proto_type::Type{T}, proto_file="default.proto") where {T <: ProtoType}
    args = `--proto_path=$_proto_path --encode=mynamespace.$proto_type $proto_file`
    protoc_jll.protoc() do protoc_path
        inbuf = PipeBuffer()
        write(inbuf, input)
        outbuf = PipeBuffer()
        run(pipeline(setenv(`$protoc_path --plugin=protoc-gen-julia=$_plugin $args`, ENV_); stdin=inbuf, stdout=outbuf))
        return readproto(outbuf, proto_type())::T
    end
end

function protobuf_to_text(input::T, proto_file="default.proto") where {T <: ProtoType}
    proto_type = typeof(input)
    args = `--proto_path=$_proto_path --decode=mynamespace.$proto_type $proto_file`
    protoc_jll.protoc() do protoc_path
        inbuf = PipeBuffer()
        writeproto(inbuf, input)
        outbuf = PipeBuffer()
        run(pipeline(setenv(`$protoc_path --plugin=protoc-gen-julia=$_plugin $args`, ENV_); stdin=inbuf, stdout=outbuf))
        return read(outbuf, String)
    end
end
1 Like