[docs]  1# @Test suite for source file discovery with gitignore support, TEST_DISC_1, test, [IMPL_DISC_1]
  2import json
  3import subprocess
  4from pathlib import Path
  5
  6import pytest
  7
  8from sphinx_codelinks.source_discover.config import (
  9    COMMENT_FILETYPE,
 10    SourceDiscoverConfig,
 11    SourceDiscoverConfigType,
 12)
 13from sphinx_codelinks.source_discover.source_discover import SourceDiscover
 14
 15FIXTURES_PATH = Path(__file__).parent / "data" / "discover_fixtures.json"
 16
 17
 18def test_source_directory_is_worker_local(
 19    source_directory: Path, tmp_path_factory: pytest.TempPathFactory
 20) -> None:
 21    assert source_directory.is_relative_to(tmp_path_factory.getbasetemp())
 22    assert (source_directory / "charge" / "demo_1.cpp").is_file()
 23    assert (source_directory / ".gitignore").read_text(
 24        encoding="utf-8"
 25    ) == "demo_1.cpp\n"
 26
 27
 28@pytest.mark.parametrize(
 29    ("config", "msgs"),
 30    [
 31        (
 32            {
 33                "src_dir": 123,
 34                "exclude": ["exclude1", "exclude2"],
 35                "include": ["include1", "include2"],
 36                "gitignore": True,
 37                "comment_type": "cpp",
 38            },
 39            ["Schema validation error in field 'src_dir': 123 is not of type 'string'"],
 40        ),
 41        (
 42            {
 43                "src_dir": "/path/to/root",
 44                "exclude": ["exclude1", "exclude2"],
 45                "include": ["include1", "include2"],
 46                "gitignore": "TrueAsString",
 47                "comment_type": "cpp",
 48            },
 49            [
 50                "Schema validation error in field 'gitignore': 'TrueAsString' is not of type 'boolean'"
 51            ],
 52        ),
 53        (
 54            {
 55                "src_dir": "/path/to/root",
 56                "exclude": ["exclude1", "exclude2"],
 57                "include": ["include1", "include2"],
 58                "gitignore": True,
 59                "comment_type": "java",
 60            },
 61            [
 62                "Schema validation error in field 'comment_type': 'java' is not one of ['bash', 'cpp', 'cs', 'go', 'jsonc', 'python', 'rust', 'ts', 'vhdl', 'yaml']"
 63            ],
 64        ),
 65        (
 66            {
 67                "src_dir": "/path/to/root",
 68                "exclude": ["exclude1", "exclude2"],
 69                "include": ["include1", "include2"],
 70                "gitignore": True,
 71                "comment_type": ["cpp", "hpp"],
 72            },
 73            [
 74                "Schema validation error in field 'comment_type': ['cpp', 'hpp'] is not of type 'string'"
 75            ],
 76        ),
 77        (
 78            {
 79                "src_dir": "/path/to/root",
 80                "follow_links": "not_a_bool",
 81            },
 82            [
 83                "Schema validation error in field 'follow_links': 'not_a_bool' is not of type 'boolean'"
 84            ],
 85        ),
 86    ],
 87)
 88def test_schema_negative(config, msgs):
 89    source_discover_config = SourceDiscoverConfig(**config)
 90    errors = source_discover_config.check_schema()
 91    assert sorted(errors) == sorted(msgs)
 92
 93
 94@pytest.mark.parametrize(
 95    "config",
 96    [
 97        {},
 98        {
 99            "src_dir": "/path/to/root",
100            "exclude": ["exclude1", "exclude2"],
101            "include": ["include1", "include2"],
102            "gitignore": True,
103            "comment_type": "cpp",
104        },
105        {
106            "src_dir": "/path/to/root",
107            "exclude": ["exclude1", "exclude2"],
108            "include": ["include1", "include2"],
109            "gitignore": True,
110            "comment_type": "python",
111        },
112        {
113            "src_dir": "/path/to/root",
114            "exclude": ["exclude1", "exclude2"],
115            "include": ["include1", "include2"],
116            "gitignore": True,
117            "comment_type": "ts",
118        },
119        {
120            "src_dir": "/path/to/root",
121            "follow_links": True,
122        },
123    ],
124)
125def test_schema_positive(config):
126    source_discover_config = SourceDiscoverConfig(**config)
127    errors = source_discover_config.check_schema()
128    assert len(errors) == 0
129
130
131@pytest.mark.parametrize(
132    ("config", "num_files", "suffix"),
133    [
134        (
135            {
136                "gitignore": False,
137            },
138            4,
139            "",
140        ),
141        (
142            {
143                "gitignore": True,
144            },
145            3,
146            "",
147        ),
148        (
149            {
150                "gitignore": True,
151                "exclude": ["charge/*.cpp"],
152                "include": ["**/*.cpp"],
153            },
154            # With ignore-python, include patterns whitelist files (overriding
155            # gitignore) and exclude patterns are applied after, so both
156            # charge/*.cpp files are excluded resulting in 2 instead of 4.
157            2,
158            "",
159        ),
160        (
161            {
162                "gitignore": True,
163                "exclude": ["charge/*.cpp"],
164            },
165            2,
166            "",
167        ),
168        (
169            {"gitignore": False, "comment_type": "cpp"},
170            4,
171            "cpp",
172        ),
173    ],
174)
175def test_source_discover(
176    config: SourceDiscoverConfigType,
177    num_files: int,
178    suffix: str,
179    source_directory: Path,
180) -> None:
181    config["src_dir"] = source_directory
182    src_discover_config = SourceDiscoverConfig(**config)
183    source_discover = SourceDiscover(src_discover_config)
184    assert len(source_discover.source_paths) == num_files
185    if suffix:
186        assert all(path.suffix == ".cpp" for path in source_discover.source_paths)
187
188
189@pytest.fixture(scope="function")
190def create_source_files(tmp_path: Path) -> Path:
191    for file_types in COMMENT_FILETYPE.values():
192        for ext in file_types:
193            (tmp_path / f"file.{ext}").touch()
194    return tmp_path
195
196
197@pytest.mark.parametrize(
198    ("comment_type", "nums_files"),
199    [
200        ("cpp", len(COMMENT_FILETYPE["cpp"])),
201        ("python", len(COMMENT_FILETYPE["python"])),
202        ("ts", len(COMMENT_FILETYPE["ts"])),
203        ("bash", len(COMMENT_FILETYPE["bash"])),
204        ("vhdl", len(COMMENT_FILETYPE["vhdl"])),
205    ],
206)
207def test_comment_filetype(
208    comment_type: str, nums_files: int, create_source_files: Path
209) -> None:
210    src_dir = create_source_files
211
212    config = SourceDiscoverConfig(
213        src_dir=src_dir, comment_type=comment_type, gitignore=False
214    )
215    source_discover = SourceDiscover(config)
216    assert len(source_discover.source_paths) == nums_files
217
218
219def test_jsonc_discover_gate() -> None:
220    """`.jsonc` is always discovered; `.json` only when it opens with a comment."""
221    jsonc_dir = Path(__file__).parent / "data" / "jsonc"
222    config = SourceDiscoverConfig(
223        src_dir=jsonc_dir, comment_type="jsonc", gitignore=False
224    )
225    discovered = {p.name for p in SourceDiscover(config).source_paths}
226    assert "demo.jsonc" in discovered
227    assert "with_modeline.json" in discovered
228    assert "plain.json" not in discovered
229
230
231def _make_generated_output_tree(tmp_path: Path) -> Path:
232    """Lay out a source file alongside checked-in generated output.
233
234    Mirrors a ``tsc``/bundler output tree: ``src/app.ts`` is the real source,
235    while ``dist/``, ``build/``, ``out/``, ``coverage/`` and ``node_modules/``
236    stand in for generated or vendored output that carries the same marker;
237    ``lib/app.js`` and the declaration file ``types/x.d.ts`` are not in the
238    default and stay discovered.
239    """
240    (tmp_path / "src").mkdir()
241    (tmp_path / "src" / "app.ts").write_text(
242        "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
243    )
244    (tmp_path / "lib").mkdir()
245    (tmp_path / "lib" / "app.js").write_text(
246        "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
247    )
248    (tmp_path / "dist").mkdir()
249    (tmp_path / "dist" / "app.js").write_text(
250        "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
251    )
252    for output in ("build", "out", "coverage"):
253        (tmp_path / output).mkdir()
254        (tmp_path / output / "app.js").write_text(
255            "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
256        )
257    (tmp_path / "types").mkdir()
258    (tmp_path / "types" / "x.d.ts").write_text(
259        "/** @Feature A, IMPL_1, impl */\nexport declare function a(): void;\n",
260        encoding="utf-8",
261    )
262    (tmp_path / "node_modules" / "pkg").mkdir(parents=True)
263    (tmp_path / "node_modules" / "pkg" / "index.js").write_text(
264        "// vendored\n", encoding="utf-8"
265    )
266    return tmp_path
267
268
269def test_default_exclude_skips_generated_output(tmp_path: Path) -> None:
270    """The ``ts``-derived default ``exclude`` keeps generated/vendored JS out
271    of discovery, while ``lib/`` — deliberately not in ``TS_DEFAULT_EXCLUDE``
272    — is still discovered (see the constant's docstring for why)."""
273    src_dir = _make_generated_output_tree(tmp_path)
274    config = SourceDiscoverConfig(src_dir=src_dir, comment_type="ts", gitignore=False)
275
276    discover = SourceDiscover(config)
277    discovered = sorted(str(p.relative_to(src_dir)) for p in discover.source_paths)
278    assert discovered == [
279        str(Path("lib") / "app.js"),
280        str(Path("src") / "app.ts"),
281        str(Path("types") / "x.d.ts"),
282    ]
283
284
285def test_cpp_project_default_exclude_is_empty_and_finds_lib_marker(
286    tmp_path: Path,
287) -> None:
288    """The ``ts`` default ``exclude`` is ``ts``'s alone: a ``cpp`` project's is ``[]``, and
289    its hand-written ``lib/`` source is discovered."""
290    lib_dir = tmp_path / "lib"
291    lib_dir.mkdir()
292    (lib_dir / "widget.cpp").write_text(
293        "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
294    )
295
296    config = SourceDiscoverConfig(src_dir=tmp_path, comment_type="cpp", gitignore=False)
297    assert config.exclude == []
298
299    discover = SourceDiscover(config)
300    discovered = sorted(str(p.relative_to(tmp_path)) for p in discover.source_paths)
301    assert discovered == [str(Path("lib") / "widget.cpp")]
302
303
304def test_explicit_exclude_replaces_default(tmp_path: Path) -> None:
305    """An explicit ``exclude`` (even ``[]``) fully replaces the default list."""
306    src_dir = _make_generated_output_tree(tmp_path)
307    config = SourceDiscoverConfig(
308        src_dir=src_dir, comment_type="ts", gitignore=False, exclude=[]
309    )
310    assert config.exclude == []
311
312    discover = SourceDiscover(config)
313    discovered = sorted(str(p.relative_to(src_dir)) for p in discover.source_paths)
314    assert discovered == [
315        str(Path("build") / "app.js"),
316        str(Path("coverage") / "app.js"),
317        str(Path("dist") / "app.js"),
318        str(Path("lib") / "app.js"),
319        str(Path("node_modules") / "pkg" / "index.js"),
320        str(Path("out") / "app.js"),
321        str(Path("src") / "app.ts"),
322        str(Path("types") / "x.d.ts"),
323    ]
324
325
326def test_follow_links(tmp_path: Path) -> None:
327    """Test that follow_links controls whether symbolic links are followed."""
328    # Create a project directory with a real directory the walk excludes, holding a
329    # source file: inside the project, since a file outside it is never discovered
330    # (#2062, ``test_a_link_to_outside_the_root_is_not_listed``)
331    project_dir = tmp_path / "project"
332    real_dir = project_dir / "real"
333    real_dir.mkdir(parents=True)
334    (real_dir / "source.cpp").write_text("// test")
335    (project_dir / "direct.cpp").write_text("// direct")
336    # and a symlink to the real directory
337    link = project_dir / "linked"
338    link.symlink_to(real_dir)
339
340    # Without follow_links, symlinked files should not be discovered
341    config_no_follow = SourceDiscoverConfig(
342        src_dir=project_dir, gitignore=False, exclude=["real/**"], follow_links=False
343    )
344    discover_no_follow = SourceDiscover(config_no_follow)
345    discovered_names = {p.name for p in discover_no_follow.source_paths}
346    assert "direct.cpp" in discovered_names
347    assert "source.cpp" not in discovered_names
348
349    # With follow_links, symlinked files should be discovered
350    config_follow = SourceDiscoverConfig(
351        src_dir=project_dir, gitignore=False, exclude=["real/**"], follow_links=True
352    )
353    discover_follow = SourceDiscover(config_follow)
354    discovered_names = {p.name for p in discover_follow.source_paths}
355    assert "direct.cpp" in discovered_names
356    assert "source.cpp" in discovered_names
357
358
359def _load_discover_fixtures() -> list[dict]:
360    with FIXTURES_PATH.open(encoding="utf-8") as f:
361        return json.load(f)
362
363
364@pytest.mark.parametrize(
365    "case",
366    _load_discover_fixtures(),
367    ids=lambda c: c["name"],
368)
369def test_discover_fixture(case: dict, tmp_path: Path) -> None:
370    """Run portable discovery test cases from the shared JSON fixture."""
371    # Create files
372    for rel_path, content in case["files"].items():
373        file_path = tmp_path / rel_path
374        file_path.parent.mkdir(parents=True, exist_ok=True)
375        file_path.write_text(content, encoding="utf-8")
376
377    # Optionally initialise a git repo (required for .gitignore support)
378    if case.get("git_init", False):
379        subprocess.run(
380            ["git", "init"],
381            cwd=str(tmp_path),
382            check=True,
383            capture_output=True,
384        )
385
386    cfg = case["config"]
387    src_dir = tmp_path / cfg["src_dir"]
388
389    config = SourceDiscoverConfig(
390        src_dir=src_dir,
391        include=cfg.get("include", []),
392        exclude=cfg.get("exclude", []),
393        gitignore=cfg.get("gitignore", True),
394        comment_type=cfg.get("comment_type", "cpp"),
395    )
396
397    discover = SourceDiscover(config)
398
399    # Convert discovered paths to paths relative to tmp_path for comparison
400    discovered_relative = sorted(
401        str(p.relative_to(tmp_path)) for p in discover.source_paths
402    )
403
404    # Normalise expected paths to use the OS path separator
405    expected = sorted(str(Path(p)) for p in case["expected"])
406
407    assert discovered_relative == expected, (
408        f"Case '{case['name']}': expected {expected}, got {discovered_relative}"
409    )
410
411
412def _links_tree(tmp_path: Path) -> Path:
413    """``root/{a.cpp, sub/b.cpp}`` with four links: a file and a directory link inside
414    the root (``b_link.cpp`` -> ``sub/b.cpp``, ``dirlink_in`` -> ``sub``), and a file
415    and a directory link to outside it (``ext_link.cpp`` -> ``outside/ext.cpp``,
416    ``dirlink_out`` -> ``outside/odir``). Returns the root."""
417    root = tmp_path / "root"
418    (root / "sub").mkdir(parents=True)
419    (tmp_path / "outside" / "odir").mkdir(parents=True)
420    (root / "a.cpp").write_text("// a\n", encoding="utf-8")
421    (root / "sub" / "b.cpp").write_text("// b\n", encoding="utf-8")
422    (tmp_path / "outside" / "ext.cpp").write_text("// ext\n", encoding="utf-8")
423    (tmp_path / "outside" / "odir" / "o.cpp").write_text("// o\n", encoding="utf-8")
424    (root / "b_link.cpp").symlink_to(root / "sub" / "b.cpp")
425    (root / "dirlink_in").symlink_to(root / "sub", target_is_directory=True)
426    (root / "ext_link.cpp").symlink_to(tmp_path / "outside" / "ext.cpp")
427    (root / "dirlink_out").symlink_to(
428        tmp_path / "outside" / "odir", target_is_directory=True
429    )
430    return root
431
432
433def _listing(root: Path, *, follow_links: bool) -> list[str]:
434    """What discovery lists under ``root``, POSIX and relative to ``root``'s parent
435    (``root.parent`` resolved: the listing is of canonical paths)."""
436    config = SourceDiscoverConfig(
437        src_dir=root, gitignore=False, follow_links=follow_links
438    )
439    base = root.parent.resolve()
440    return [
441        path.relative_to(base).as_posix()
442        for path in SourceDiscover(config).source_paths
443    ]
444
445
446def test_a_file_link_inside_the_root_is_listed_once(tmp_path: Path) -> None:
447    """``b_link.cpp`` is ``sub/b.cpp``: one entry, the target's, not one per path to it.
448
449    A symlinked file is listed even with ``follow_links = false`` (``is_file()``
450    follows the link) -- ubCode skips it; a parity gap kept as it is. A link to a file
451    OUTSIDE the root is not listed (#2062).
452    """
453    assert _listing(_links_tree(tmp_path), follow_links=False) == [
454        "root/a.cpp",
455        "root/sub/b.cpp",
456    ]
457
458
459def test_a_followed_directory_link_inside_the_root_lists_each_file_once(
460    tmp_path: Path,
461) -> None:
462    """With ``follow_links = true`` ``sub/b.cpp`` is reached three ways (``sub/``,
463    ``b_link.cpp`` and ``dirlink_in/``): still one entry. The followed link to outside
464    the root lists nothing (#2062)."""
465    assert _listing(_links_tree(tmp_path), follow_links=True) == [
466        "root/a.cpp",
467        "root/sub/b.cpp",
468    ]
469
470
471def test_a_link_free_listing_is_sorted_by_full_path(tmp_path: Path) -> None:
472    """Without links nothing is deduplicated, and the order is the full path's: ``-``
473    and ``.`` sort before the separator, ``_`` after it (on POSIX and on Windows)."""
474    root = tmp_path / "root"
475    for relative in [
476        "b.cpp",
477        "sub_x.cpp",
478        "z/y/x.cpp",
479        "sub/c.cpp",
480        "a.cpp",
481        "sub.cpp",
482        "sub-x/d.cpp",
483    ]:
484        path = root / relative
485        path.parent.mkdir(parents=True, exist_ok=True)
486        path.write_text("// x\n", encoding="utf-8")
487
488    assert _listing(root, follow_links=False) == [
489        "root/a.cpp",
490        "root/b.cpp",
491        "root/sub-x/d.cpp",
492        "root/sub.cpp",
493        "root/sub/c.cpp",
494        "root/sub_x.cpp",
495        "root/z/y/x.cpp",
496    ]
497    assert _listing(root, follow_links=True) == _listing(root, follow_links=False)
498
499
500@pytest.mark.parametrize("follow_links", [False, True])
501def test_a_link_to_outside_the_root_is_not_listed(
502    tmp_path: Path, follow_links: bool
503) -> None:
504    """Neither a file link to outside the root nor a followed directory link's files
505    are listed, either way (#2062): every record and copy is relative to the root."""
506    listing = _listing(_links_tree(tmp_path), follow_links=follow_links)
507    assert not any(path.startswith("outside/") for path in listing)
508    assert not any("link" in path for path in listing)