如何在自定义Bazel规则或genrule中打包生成的python文件? [英] How to package generated python files in custom Bazel rule or genrule?

查看:121
本文介绍了如何在自定义Bazel规则或genrule中打包生成的python文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个生成Java和Python代码的脚本.它生成的文件取决于输入配置,它可以根据配置而有所不同.现在,对于Java,我可以编写一个简单的规则,指向调用脚本,然后调用 jar 命令来生成生成的Python文件的单个源包.

Let's say I have a scripts which generates Java and Python code. The files it generates depends on the input config, it can vary based on the config. Now, in the case of Java, I can write a simple genrule, point to invoke the script and then call jar command to generate a single source package of the generated Python files.

例如:

genrule(
    name = "generated_java_srcjar",
    srcs = glob([
        ":input-files"
    ]),
    outs = [
        "xsd.srcjar"
    ],
    cmd = """
        mkdir -p $(GENDIR)/generated-code
        $(location path/to/custom/script) --output-directory $(GENDIR)/generated-code --input $(locations :input-files)
        $(JAVABASE)/bin/jar cMf $@ -C $(GENDIR)/generated-code .
    """,
)

java_library(
    name = "generated_java_jar",
    srcs = [
        ":generated_java_srcjar"
    ],
)

在Java示例中,要声明genrule的输出,我可以生成一个输出(所生成文件的源包),然后使用相同的规则作为 java_library中的源规则.

In the Java example, to declare an output for the genrule, I'm able to generate a single output (source package of the generated files) and then use the same rule as a source in the java_library rule.

现在,我想在Python中实现类似的功能.调用自定义脚本后如何打包生成的Python文件,以便随后将其作为 py_library 规则的源传递?

Now, I want to achieve something similar in Python. How can I package the generated Python files after invoking the custom script so that I can then pass it as a source to py_library rule?

推荐答案

一种方法是编写自己的Starlark规则,该规则返回

One way to do this is to write your own Starlark rule that returns a PyInfo provider with your generated files in the transitive_sources. You'd then add the rule to the deps attribute of your py_library rule.

缺点是,您必须在加载阶段中知道(因此,在代码生成之前),您的工具将生成哪些文件,而不会与zips/jars作弊.

The drawback is that you have to know at loading phase (so before the code generation has happened) what files will be generated by your tool, no cheating with zips/jars.

如果这不是一种选择,那么我可以想到一个变通的解决方法,在该方法中,您可以生成依赖py_libarary数据部门的zip文件.然后,在实际导入文件之前,请在运行时将其解压缩.

If that's not an option I could think of a hacky workaround where you produce a zip that you depend on in your py_libarary's data deps. You then unpack the file at runtime before you actually import it.

取决于您如何设置python规则,您也许还可以在代码生成器中构建python wheel并以此为依托.

Depending on how you've set up your python rules you might also be able to build a python wheel in your code generator and depend on that.

这篇关于如何在自定义Bazel规则或genrule中打包生成的python文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆