Created
December 10, 2024 05:59
-
-
Save crackcomm/b3b669af0806425acfb28c260c4a45e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
load("@rules_python//python:defs.bzl", "py_library") | |
_PROTOTXT_COMMAND = """ | |
cat <<EOF >>{out} | |
# Autogenerated by bazel. DO NOT EDIT. | |
from google.protobuf import text_format | |
from {pkg} import {message} | |
text = \"\"\" | |
EOF | |
cat {src} >> {out} | |
cat <<EOF >>{out} | |
\"\"\" | |
{varname} = text_format.Parse(text, {message}()) | |
EOF | |
""" | |
def _prototxt_py(ctx): | |
# Source .prototxt file | |
src = ctx.files.src[0] | |
# Output python file | |
out_file = ctx.outputs.out | |
command = _PROTOTXT_COMMAND.format( | |
src = src.path, | |
out = out_file.path, | |
pkg = ctx.attr.pkg, | |
varname = ctx.attr.varname, | |
message = ctx.attr.message, | |
) | |
ctx.actions.run_shell( | |
outputs = [out_file], | |
command = command, | |
inputs = [src], | |
) | |
genprototxt_py = rule( | |
implementation = _prototxt_py, | |
attrs = { | |
"src": attr.label( | |
doc = "The prototxt source file.", | |
mandatory = True, | |
allow_single_file = True, | |
), | |
"out": attr.output( | |
doc = "Where to write the python file.", | |
mandatory = True, | |
), | |
"pkg": attr.string( | |
doc = "Python path to protobuf library.", | |
mandatory = True, | |
), | |
"varname": attr.string( | |
doc = "Variable name.", | |
mandatory = True, | |
), | |
"message": attr.string( | |
doc = "Protocol buffers message name.", | |
mandatory = True, | |
), | |
}, | |
) | |
def prototxt_py(*, name, src, pkg, varname, message, **kwargs): | |
gen_name = name + "_py" | |
gen_out = name + ".py" | |
genprototxt_py( | |
name = gen_name, | |
src = src, | |
out = gen_out, | |
pkg = pkg, | |
varname = varname, | |
message = message, | |
) | |
py_library( | |
name = name, | |
srcs = [gen_out], | |
**kwargs | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment