# Parsing ProtoBuf Text Format

**URL:** <https://discourse.julialang.org/t/parsing-protobuf-text-format/84721>\
**Category:** General Usage\
**Tags:** question, io, serialization, protobuf\
**Created:** [July 24, 2022, 6:24pm UTC](https://discourse.julialang.org/t/parsing-protobuf-text-format/84721 "2022-07-24T18:24:13Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![FireCrumb](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/firecrumb/32/35370_2.png) [@FireCrumb](https://discourse.julialang.org/u/FireCrumb)\
**Post date:** [July 27, 2022, 2:20am UTC](https://discourse.julialang.org/t/parsing-protobuf-text-format/84721/3 "2022-07-27T02:20:05Z")

</div>

Thanks!

I was able to build this solution:

```julia
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

```

---

_[View the full topic](https://discourse.julialang.org/t/parsing-protobuf-text-format/84721)._
