You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

python-sphinx traceability插件:动态替换关联项并消除构建警告

解决Sphinx Traceability插件移除关系时的警告问题

问题场景

我在使用Sphinx的traceability插件,测试文档包含如下RST内容:

.. item:: TST-Example
   :applicable_to: PRD-ALL

我需要把PRD-ALL替换为预定义的产品列表PRD-A PRD-B,于是在插件提供的traceability_callback_per_item回调中添加逻辑:

def traceability_callback_per_item(name, collection):
    item = collection.get_item(name)

    if name.startswith('TST-'):
        applicable_to = list(item.iter_targets('applicable_to'))

        if 'PRD-ALL' in applicable_to:
            collection.add_relation(item.identifier, 'applicable_to', 'PRD-A')
            collection.add_relation(item.identifier, 'applicable_to', 'PRD-B')

            # 移除'applicable_to'关系中的PRD-ALL:
            # 如何实现?

尝试用以下代码移除关系时:

item.remove_targets('PRD-ALL', explicit=True, implicit=True, relations=['applicable_to'])

出现警告:

WARNING: No automatic reverse relation: TST-Example applicable_to PRD-ALL

由于构建时使用-W参数(将警告视为错误),导致构建失败。

解决方案

问题根源在于直接移除正向关系时,插件自动维护的反向关系没有被同步清理,触发了一致性警告。正确的做法是通过collection对象的方法同时处理正向和反向关系:

修改后的回调函数

def traceability_callback_per_item(name, collection):
    item = collection.get_item(name)

    if name.startswith('TST-'):
        applicable_to = list(item.iter_targets('applicable_to'))

        if 'PRD-ALL' in applicable_to:
            # 添加目标产品的关联关系
            collection.add_relation(item.identifier, 'applicable_to', 'PRD-A')
            collection.add_relation(item.identifier, 'applicable_to', 'PRD-B')

            # 移除PRD-ALL的正向关联
            collection.remove_relation(item.identifier, 'applicable_to', 'PRD-ALL')
            
            # 手动移除反向关联(需根据你的插件关系配置调整反向关系名)
            # 示例中假设反向关系为'applies_to',请替换为实际配置的反向关系名
            prd_all_item = collection.get_item('PRD-ALL')
            if prd_all_item:
                collection.remove_relation('PRD-ALL', 'applies_to', item.identifier)

补充说明

  • 如果不确定反向关系的名称,可以调用collection.get_relation_types()查看所有已定义的关系类型及其对应的反向关系配置。
  • 这种方式确保了正向和反向关系的同步清理,避免插件触发一致性警告,同时保证了追溯数据的完整性。

内容的提问来源于stack exchange,提问作者Shlomo Gottlieb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 08:13:12