如何在Bazel中判断两个文件所属目标的依赖关系
首先得先定位这两个文件对应的Bazel目标——毕竟一个文件可能被多个py_library、py_binary类目标引用,先把目标找出来再说:
- 找file.py对应的目标:
bazel query '//...:* where srcs contains "file.py"' - 找other_file.py对应的目标:
bazel query '//...:* where srcs contains "other_file.py"'
假设得到的目标分别是//path/to:file_target和//path/to:other_target,接下来就可以查依赖关系了:
检查单向依赖
要判断file_target是否依赖other_target,直接跑:bazel query 'deps(//path/to:file_target) intersect //path/to:other_target'
如果有输出结果,说明前者确实依赖后者;反过来查other_target是否依赖file_target,把两个目标位置调换就行。
找共同关联目标
如果要找两个目标共同依赖的底层目标,用:bazel query 'deps(//path/to:file_target) intersect deps(//path/to:other_target)'
输出的就是两个目标都依赖的节点。
如果要找同时依赖这两个目标的上层祖先目标(也就是它们的共同父级依赖节点),可以用反向依赖查询:bazel query 'rdeps(//my:target, //path/to:file_target) intersect rdeps(//my:target, //path/to:other_target)'
这个命令会从my:target出发,找出同时依赖两个目标的上层节点。
可视化依赖图(可选)
如果想更直观地看整个依赖链,用cquery生成依赖图:bazel cquery --output=graph 'deps(//my:target)' > deps.graph
然后用dot工具转成图片(需要安装graphviz):dot -Tpng deps.graph -o deps.png
打开图片就能清楚看到两个目标在依赖树里的位置关系了。
内容的提问来源于stack exchange,提问作者y.selivonchyk

