Score Source Code Linker#

A Sphinx extension for enabling source code and test traceability for requirements. This extension integrates with Bazel and sphinx-needs to automatically generate traceability links between implementation, tests, and documentation.


Overview#

The feature is split into two layers:

  1. Bazel pre-processing (before Sphinx runs) Generates and aggregates JSON caches containing the raw source_code_link findings (and, if available, repository metadata like repo_name/hash/url). Note that “hash” might also be a “version” tag.

  2. Sphinx extension (during the Sphinx build) Reads the aggregated JSON, validates and adapts it, and finally injects the links into Sphinx needs.

This separation makes combo builds faster and more deterministic, because the expensive repository scanning/parsing happens outside the Sphinx process.


How It Works#


Source Code Linker Extension#

All steps run on the Sphinx env-updated event, in this order:

  1. Priority 505: testcases. xml_parser.py parses the test.xml files (no Sphinx needed). testcase_needs.py adds a testcase need per testcase and writes the testlinks to score_xml_parser_cache.json.

  2. Priority 525: links. inject_links_into_needs (__init__.py) reads the JSON produced by Bazel and the testlinks, groups them by need in memory, renders each link with its own repository and writes source_code_link / testlink into the needs.

Test Tagging Options#

# Import the decorator
from attribute_plugin import add_test_properties

# Add the decorator to your test
@add_test_properties(
    partially_verifies=["tool_req__docs_common_attr_title", "tool_req__docs_common_attr_description"],
    test_type="interface-test",
    derivation_technique="boundary-values"
)
def test_feature():
    """
    Mandatory docstring that contains a description of the test
    """
    ...

Note: If you use the decorator, it will check that you have specified a docstring inside the function.

Data Flow#

  1. XML Parsing (xml_parser.py, no Sphinx needed)

    • Scans bazel-testlogs/ or tests-report for test.xml files.

    • Parses test cases and extracts:

      • Name & Classname

      • File path

      • Line

      • Result (e.g. passed, failed, skipped)

      • Result text (if failed/skipped will check if message was attached to it)

      • Verifications (PartiallyVerifies, FullyVerifies)

      • Also parses metadata according to the metadata rules

    • Cases without metadata are logged out as info (not errors).

    • Test cases with metadata are converted into:

      • DataOfTestCase (used for external needs)

      • DataForTestLink (used for linking tests to requirements)

If there is a Classname then it gets combined with the function name for the displayed link as follows: Classname__Functionname

  1. Need Linking (testcase_needs.py and __init__.py)

    • Generates external Sphinx needs from DataOfTestCase.

    • Creates testlink attributes on linked requirements.

    • Warns on missing need IDs.

Example JSON Cache (DataOfTestCase)#

The DataOfTestCase depicts the information gathered about one testcase.

[
  {
    "name": "test_cache_file_with_encoded_comments",
    "file": "src/extensions/score_source_code_linker/tests/test_codelink.py",
    "line": "340",
    "result": "passed",
    "TestType": "interface-test",
    "DerivationTechnique": "boundary-values",
    "result_text": "",
    "PartiallyVerifies": "tool_req__docs_common_attr_title, tool_req__docs_common_attr_description",
    "FullyVerifies": null,
    "repo_name": "score_docs_as_code",
    "hash": "",
    "url": ""
  }
]

Combined JSON Example#

[
  {
    "need": "tool_req__docs_common_attr_title",
    "links": {
      "CodeLinks": [
        {
          "file": "src/extensions/score_metamodel/metamodel.yaml",
          "line": 33,
          "tag": "#--req-Id:",# added `--` to avoid detection
          "need": "tool_req__docs_common_attr_title",
          "full_line": "#--req-Id: tool_req__docs_common_attr_title", # added `--` to avoid detection
          "repo_name": "score_docs_as_code",
          "hash": "",
          "url": "",

        }
      ],
      "TestLinks": [
        {
          "name": "test_cache_file_with_encoded_comments",
          "file": "src/extensions/score_source_code_linker/tests/test_codelink.py",
          "line": 340,
          "need": "tool_req__docs_common_attr_title",
          "verify_type": "partially",
          "result": "passed",
          "result_text": "",
          "repo_name": "score_docs_as_code",
          "hash": "",
          "url": "",
        }
      ]
    }
  }
]

If the repo is the local one, the hash and url come from the local git checkout (see repo metadata rules). All link URLs are decided in one function, get_github_link in src/helper_lib/repo_info.py.



Known Limitations#

General#

  • For GitHub links to dependencies in a combo build, pass known_good = "//:known_good.json" to docs(). The file supplies the repository URL and revision for each dependency.

  • inefficiencies in creating the links

  • Not compatible with Esbonio

  • Live preview: Bazel regenerates the sourcelinks JSON when the preview starts, but unchanged pages can still show old links if Sphinx reuses its previous build. Clean _build and restart the preview to refresh all pages and test results.

Codelinks#

  • GitHub links may 404 if the commit isn’t pushed

  • Tags must match exactly (e.g. # req-Id)

  • source_code_link isn’t visible until the full Sphinx build is completed


High-level Data Flow Summary#

  1. Bazel Script #1: scan + parse → write per-bundle cache (each link names its repository)

  2. Bazel Script #2: merge caches + fill url & hash per link → write single merged JSON

  3. Sphinx Extension: parse test XMLs → add testcase needs → read merged JSON + testlinks → group by need in memory → inject source_code_link and testlink into needs


Clearing Cache Manually#

To clear the build cache, run:

rm -rf _build/

Internal Overview#

The bazel part:

scripts_bazel/
├── BUILD   # Declare libraries and filegroups needed for bazel
├── generate_sourcelinks_cli.py # Bazel step 1 => Parses sourcefiles for tags
├── source_code_link_parser.py # Source-file parser used by the generator
├── merge_sourcelinks.py
└── tests
│   └── ...

The Sphinx extension

score_source_code_linker/
├── __init__.py                   # Main Sphinx extension; combines CodeLinks + TestLinks
├── need_source_links.py         # Data model for combined links
├── testlink.py                  # DataForTestLink definition & logic
├── xml_parser.py                # Parses XML files into test case data (no Sphinx)
├── testcase_needs.py            # Turns parsed test cases into testcase needs
├── testcase_annotations.py      # Adds result annotations to GitHub testcase links
├── tests/                       # Testsuite, containing unit & integration tests
│   └── ...

Shared parts in src/helper_lib/ (also used by the Bazel scripts):

helper_lib/
├── needlinks.py                 # CodeLink (NeedLink) dataclass & JSON encoder/decoder
├── repo_info.py                 # RepoInfo, known_good lookup (resolve_repo), GitHub link URLs (get_github_link)

Examples#

To see working examples for CodeLinks & TestLinks, take a look at the Docs-As-Code documentation.

Example CodeLink Example CodeLink

Example TestLink