使用标签路径检查文件位置是否存在



有没有一种简单的方法来获取路径对象,以便我可以检查给定的标签路径是否存在。例如说if path.exists("@external_project_name//:filethatmightexist.txt"):.我可以看到存储库上下文具有此内容。但是我需要有一个包装存储库规则。是否可以在宏或 Skylark 本机调用中执行此操作?

即使有repository_rule,由于您已经指出的内容,我对此也遇到了很多麻烦:

如果使用不存在的路径创建标签,则会导致生成失败

但是,如果您愿意执行存储库规则,这里有一个可能的解决方案...

在此示例中,我的规则允许在配置文件不存在时指定默认配置。该配置可以签入 .gitignore 并为单个开发人员覆盖,但在大多数情况下开箱即用。

我想我明白为什么 ctx.actions 现在有兄弟姐妹的论点,这里的想法是一样的。诀窍是config_file_location是一个真正的标签,然后config_file是一个字符串属性。我任意选择了 BUILD,但由于所有工作区都有一个顶级 BUILD,因此公共似乎是合法的。

WORKSPACE Definition
...
workspace(name="E02_mysql_database")
json_datasource_configuration(name="E02_datasources",
config_file_location="@E02_mysql_database//:BUILD",
config_file="database.json")

json_datasource_configuration的定义如下所示:

json_datasource_configuration = repository_rule(
attrs = {
"config_file_location": attr.label(
doc="""
Path relative to the repository root for a datasource config file.
"""),
"config_file": attr.string(
doc="""
Config file, maybe absent
"""),
"default_config": attr.string(
# better way to do this?
default="None",
doc = """
If no config is at the path, then this will be the default config.
Should look something like:
{
"datasource_name": {
"host": "<host>"
"port": <port>
"password": "<password>"
"username": "<username>"
"jdbc_connection_string": "<optional>"
}
}
There can be more than datasource configured... maybe, eventually.
""",
),
},
local = True,
implementation = _json_config_impl,
)

然后在规则中,我可以测试文件是否存在,如果不存在,则执行其他逻辑。

def _json_config_impl(ctx):
"""
Allows you to specify a file on disk to use for data connection.
If you pass a default
"""
config_path = ctx.path(ctx.attr.config_file_location).dirname.get_child(ctx.attr.config_file)
config = ""
if config_path.exists:
config = ctx.read(config_path)
elif ctx.attr.default_config == "None":
fail("Could not find config at %s, you must supply a default_config if this is intentional" % ctx.attr.config_file)
else:
config = ctx.attr.default_config
...

可能为时已晚,无法提供帮助,但您的问题是我发现唯一提及此目标的内容。如果有人知道更好的方法,我正在寻找其他选择。向其他开发人员解释为什么规则必须按其方式工作很复杂。

另请注意,如果更改配置文件,则必须清理以使工作区重新读取配置。我一直无法找到任何解决此问题的方法。glob(( 在工作区中不起作用。

最新更新