[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', '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    ],
205)
206def test_comment_filetype(
207    comment_type: str, nums_files: int, create_source_files: Path
208) -> None:
209    src_dir = create_source_files
210
211    config = SourceDiscoverConfig(
212        src_dir=src_dir, comment_type=comment_type, gitignore=False
213    )
214    source_discover = SourceDiscover(config)
215    assert len(source_discover.source_paths) == nums_files
216
217
218def test_jsonc_discover_gate() -> None:
219    """`.jsonc` is always discovered; `.json` only when it opens with a comment."""
220    jsonc_dir = Path(__file__).parent / "data" / "jsonc"
221    config = SourceDiscoverConfig(
222        src_dir=jsonc_dir, comment_type="jsonc", gitignore=False
223    )
224    discovered = {p.name for p in SourceDiscover(config).source_paths}
225    assert "demo.jsonc" in discovered
226    assert "with_modeline.json" in discovered
227    assert "plain.json" not in discovered
228
229
230def _make_generated_output_tree(tmp_path: Path) -> Path:
231    """Lay out a source file alongside checked-in generated output.
232
233    Mirrors a ``tsc``/bundler output tree: ``src/app.ts`` is the real source,
234    while ``dist/``, ``build/``, ``out/``, ``coverage/`` and ``node_modules/``
235    stand in for generated or vendored output that carries the same marker;
236    ``lib/app.js`` and the declaration file ``types/x.d.ts`` are not in the
237    default and stay discovered.
238    """
239    (tmp_path / "src").mkdir()
240    (tmp_path / "src" / "app.ts").write_text(
241        "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
242    )
243    (tmp_path / "lib").mkdir()
244    (tmp_path / "lib" / "app.js").write_text(
245        "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
246    )
247    (tmp_path / "dist").mkdir()
248    (tmp_path / "dist" / "app.js").write_text(
249        "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
250    )
251    for output in ("build", "out", "coverage"):
252        (tmp_path / output).mkdir()
253        (tmp_path / output / "app.js").write_text(
254            "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
255        )
256    (tmp_path / "types").mkdir()
257    (tmp_path / "types" / "x.d.ts").write_text(
258        "/** @Feature A, IMPL_1, impl */\nexport declare function a(): void;\n",
259        encoding="utf-8",
260    )
261    (tmp_path / "node_modules" / "pkg").mkdir(parents=True)
262    (tmp_path / "node_modules" / "pkg" / "index.js").write_text(
263        "// vendored\n", encoding="utf-8"
264    )
265    return tmp_path
266
267
268def test_default_exclude_skips_generated_output(tmp_path: Path) -> None:
269    """The ``ts``-derived default ``exclude`` keeps generated/vendored JS out
270    of discovery, while ``lib/`` — deliberately not in ``TS_DEFAULT_EXCLUDE``
271    — is still discovered (see the constant's docstring for why)."""
272    src_dir = _make_generated_output_tree(tmp_path)
273    config = SourceDiscoverConfig(src_dir=src_dir, comment_type="ts", gitignore=False)
274
275    discover = SourceDiscover(config)
276    discovered = sorted(str(p.relative_to(src_dir)) for p in discover.source_paths)
277    assert discovered == [
278        str(Path("lib") / "app.js"),
279        str(Path("src") / "app.ts"),
280        str(Path("types") / "x.d.ts"),
281    ]
282
283
284def test_cpp_project_default_exclude_is_empty_and_finds_lib_marker(
285    tmp_path: Path,
286) -> None:
287    """The ``ts`` default ``exclude`` is ``ts``'s alone: a ``cpp`` project's is ``[]``, and
288    its hand-written ``lib/`` source is discovered."""
289    lib_dir = tmp_path / "lib"
290    lib_dir.mkdir()
291    (lib_dir / "widget.cpp").write_text(
292        "// @Feature A, IMPL_1, impl\n", encoding="utf-8"
293    )
294
295    config = SourceDiscoverConfig(src_dir=tmp_path, comment_type="cpp", gitignore=False)
296    assert config.exclude == []
297
298    discover = SourceDiscover(config)
299    discovered = sorted(str(p.relative_to(tmp_path)) for p in discover.source_paths)
300    assert discovered == [str(Path("lib") / "widget.cpp")]
301
302
303def test_explicit_exclude_replaces_default(tmp_path: Path) -> None:
304    """An explicit ``exclude`` (even ``[]``) fully replaces the default list."""
305    src_dir = _make_generated_output_tree(tmp_path)
306    config = SourceDiscoverConfig(
307        src_dir=src_dir, comment_type="ts", gitignore=False, exclude=[]
308    )
309    assert config.exclude == []
310
311    discover = SourceDiscover(config)
312    discovered = sorted(str(p.relative_to(src_dir)) for p in discover.source_paths)
313    assert discovered == [
314        str(Path("build") / "app.js"),
315        str(Path("coverage") / "app.js"),
316        str(Path("dist") / "app.js"),
317        str(Path("lib") / "app.js"),
318        str(Path("node_modules") / "pkg" / "index.js"),
319        str(Path("out") / "app.js"),
320        str(Path("src") / "app.ts"),
321        str(Path("types") / "x.d.ts"),
322    ]
323
324
325def test_follow_links(tmp_path: Path) -> None:
326    """Test that follow_links controls whether symbolic links are followed."""
327    # Create a project directory with a real directory the walk excludes, holding a
328    # source file: inside the project, since a file outside it is never discovered
329    # (#2062, ``test_a_link_to_outside_the_root_is_not_listed``)
330    project_dir = tmp_path / "project"
331    real_dir = project_dir / "real"
332    real_dir.mkdir(parents=True)
333    (real_dir / "source.cpp").write_text("// test")
334    (project_dir / "direct.cpp").write_text("// direct")
335    # and a symlink to the real directory
336    link = project_dir / "linked"
337    link.symlink_to(real_dir)
338
339    # Without follow_links, symlinked files should not be discovered
340    config_no_follow = SourceDiscoverConfig(
341        src_dir=project_dir, gitignore=False, exclude=["real/**"], follow_links=False
342    )
343    discover_no_follow = SourceDiscover(config_no_follow)
344    discovered_names = {p.name for p in discover_no_follow.source_paths}
345    assert "direct.cpp" in discovered_names
346    assert "source.cpp" not in discovered_names
347
348    # With follow_links, symlinked files should be discovered
349    config_follow = SourceDiscoverConfig(
350        src_dir=project_dir, gitignore=False, exclude=["real/**"], follow_links=True
351    )
352    discover_follow = SourceDiscover(config_follow)
353    discovered_names = {p.name for p in discover_follow.source_paths}
354    assert "direct.cpp" in discovered_names
355    assert "source.cpp" in discovered_names
356
357
358def _load_discover_fixtures() -> list[dict]:
359    with FIXTURES_PATH.open(encoding="utf-8") as f:
360        return json.load(f)
361
362
363@pytest.mark.parametrize(
364    "case",
365    _load_discover_fixtures(),
366    ids=lambda c: c["name"],
367)
368def test_discover_fixture(case: dict, tmp_path: Path) -> None:
369    """Run portable discovery test cases from the shared JSON fixture."""
370    # Create files
371    for rel_path, content in case["files"].items():
372        file_path = tmp_path / rel_path
373        file_path.parent.mkdir(parents=True, exist_ok=True)
374        file_path.write_text(content, encoding="utf-8")
375
376    # Optionally initialise a git repo (required for .gitignore support)
377    if case.get("git_init", False):
378        subprocess.run(
379            ["git", "init"],
380            cwd=str(tmp_path),
381            check=True,
382            capture_output=True,
383        )
384
385    cfg = case["config"]
386    src_dir = tmp_path / cfg["src_dir"]
387
388    config = SourceDiscoverConfig(
389        src_dir=src_dir,
390        include=cfg.get("include", []),
391        exclude=cfg.get("exclude", []),
392        gitignore=cfg.get("gitignore", True),
393        comment_type=cfg.get("comment_type", "cpp"),
394    )
395
396    discover = SourceDiscover(config)
397
398    # Convert discovered paths to paths relative to tmp_path for comparison
399    discovered_relative = sorted(
400        str(p.relative_to(tmp_path)) for p in discover.source_paths
401    )
402
403    # Normalise expected paths to use the OS path separator
404    expected = sorted(str(Path(p)) for p in case["expected"])
405
406    assert discovered_relative == expected, (
407        f"Case '{case['name']}': expected {expected}, got {discovered_relative}"
408    )
409
410
411def _links_tree(tmp_path: Path) -> Path:
412    """``root/{a.cpp, sub/b.cpp}`` with four links: a file and a directory link inside
413    the root (``b_link.cpp`` -> ``sub/b.cpp``, ``dirlink_in`` -> ``sub``), and a file
414    and a directory link to outside it (``ext_link.cpp`` -> ``outside/ext.cpp``,
415    ``dirlink_out`` -> ``outside/odir``). Returns the root."""
416    root = tmp_path / "root"
417    (root / "sub").mkdir(parents=True)
418    (tmp_path / "outside" / "odir").mkdir(parents=True)
419    (root / "a.cpp").write_text("// a\n", encoding="utf-8")
420    (root / "sub" / "b.cpp").write_text("// b\n", encoding="utf-8")
421    (tmp_path / "outside" / "ext.cpp").write_text("// ext\n", encoding="utf-8")
422    (tmp_path / "outside" / "odir" / "o.cpp").write_text("// o\n", encoding="utf-8")
423    (root / "b_link.cpp").symlink_to(root / "sub" / "b.cpp")
424    (root / "dirlink_in").symlink_to(root / "sub", target_is_directory=True)
425    (root / "ext_link.cpp").symlink_to(tmp_path / "outside" / "ext.cpp")
426    (root / "dirlink_out").symlink_to(
427        tmp_path / "outside" / "odir", target_is_directory=True
428    )
429    return root
430
431
432def _listing(root: Path, *, follow_links: bool) -> list[str]:
433    """What discovery lists under ``root``, POSIX and relative to ``root``'s parent
434    (``root.parent`` resolved: the listing is of canonical paths)."""
435    config = SourceDiscoverConfig(
436        src_dir=root, gitignore=False, follow_links=follow_links
437    )
438    base = root.parent.resolve()
439    return [
440        path.relative_to(base).as_posix()
441        for path in SourceDiscover(config).source_paths
442    ]
443
444
445def test_a_file_link_inside_the_root_is_listed_once(tmp_path: Path) -> None:
446    """``b_link.cpp`` is ``sub/b.cpp``: one entry, the target's, not one per path to it.
447
448    A symlinked file is listed even with ``follow_links = false`` (``is_file()``
449    follows the link) -- ubCode skips it; a parity gap kept as it is. A link to a file
450    OUTSIDE the root is not listed (#2062).
451    """
452    assert _listing(_links_tree(tmp_path), follow_links=False) == [
453        "root/a.cpp",
454        "root/sub/b.cpp",
455    ]
456
457
458def test_a_followed_directory_link_inside_the_root_lists_each_file_once(
459    tmp_path: Path,
460) -> None:
461    """With ``follow_links = true`` ``sub/b.cpp`` is reached three ways (``sub/``,
462    ``b_link.cpp`` and ``dirlink_in/``): still one entry. The followed link to outside
463    the root lists nothing (#2062)."""
464    assert _listing(_links_tree(tmp_path), follow_links=True) == [
465        "root/a.cpp",
466        "root/sub/b.cpp",
467    ]
468
469
470def test_a_link_free_listing_is_sorted_by_full_path(tmp_path: Path) -> None:
471    """Without links nothing is deduplicated, and the order is the full path's: ``-``
472    and ``.`` sort before the separator, ``_`` after it (on POSIX and on Windows)."""
473    root = tmp_path / "root"
474    for relative in [
475        "b.cpp",
476        "sub_x.cpp",
477        "z/y/x.cpp",
478        "sub/c.cpp",
479        "a.cpp",
480        "sub.cpp",
481        "sub-x/d.cpp",
482    ]:
483        path = root / relative
484        path.parent.mkdir(parents=True, exist_ok=True)
485        path.write_text("// x\n", encoding="utf-8")
486
487    assert _listing(root, follow_links=False) == [
488        "root/a.cpp",
489        "root/b.cpp",
490        "root/sub-x/d.cpp",
491        "root/sub.cpp",
492        "root/sub/c.cpp",
493        "root/sub_x.cpp",
494        "root/z/y/x.cpp",
495    ]
496    assert _listing(root, follow_links=True) == _listing(root, follow_links=False)
497
498
499@pytest.mark.parametrize("follow_links", [False, True])
500def test_a_link_to_outside_the_root_is_not_listed(
501    tmp_path: Path, follow_links: bool
502) -> None:
503    """Neither a file link to outside the root nor a followed directory link's files
504    are listed, either way (#2062): every record and copy is relative to the root."""
505    listing = _listing(_links_tree(tmp_path), follow_links=follow_links)
506    assert not any(path.startswith("outside/") for path in listing)
507    assert not any("link" in path for path in listing)