|
| 1 | +"""Detect and neutralize gitlinks with no matching .gitmodules entry. |
| 2 | +
|
| 3 | +Some repositories contain gitlinks (mode ``160000``) that have no matching |
| 4 | +entry in ``.gitmodules`` -- for example an accidentally committed |
| 5 | +``git worktree`` directory or nested checkout. Both ``git submodule update |
| 6 | +--init --recursive`` and ``git submodule foreach`` abort outright as soon as |
| 7 | +they encounter such a gitlink, even though dfetch has no URL to fetch it |
| 8 | +from and nothing useful to report about it anyway. |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | +import re |
| 13 | + |
| 14 | +from dfetch.log import get_logger |
| 15 | +from dfetch.util.cmdline import SubprocessCommandError, run_on_cmdline |
| 16 | + |
| 17 | +GIT_MODULES_FILE = ".gitmodules" |
| 18 | + |
| 19 | +logger = get_logger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +def gitlink_paths() -> list[str]: |
| 23 | + """List the paths of all gitlinks (mode 160000) in the current index.""" |
| 24 | + result = run_on_cmdline(logger, ["git", "ls-files", "-s", "-z"]) |
| 25 | + paths = [] |
| 26 | + for entry in result.stdout.decode().split("\0"): |
| 27 | + if not entry: |
| 28 | + continue |
| 29 | + meta, _, path = entry.partition("\t") |
| 30 | + if meta.split()[0] == "160000": |
| 31 | + paths.append(path) |
| 32 | + return paths |
| 33 | + |
| 34 | + |
| 35 | +def declared_submodule_paths() -> set[str]: |
| 36 | + """Return the submodule paths declared in .gitmodules, if any.""" |
| 37 | + if not os.path.isfile(GIT_MODULES_FILE): |
| 38 | + return set() |
| 39 | + try: |
| 40 | + result = run_on_cmdline( |
| 41 | + logger, |
| 42 | + ["git", "config", "--file", GIT_MODULES_FILE, "--get-regexp", "path"], |
| 43 | + ) |
| 44 | + except SubprocessCommandError: |
| 45 | + return set() |
| 46 | + return { |
| 47 | + match.group(1) |
| 48 | + for match in re.finditer( |
| 49 | + r"submodule\.(?:.*)\.path\s+(.*)", result.stdout.decode() |
| 50 | + ) |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | +def drop_orphan_gitlinks() -> None: |
| 55 | + """Strip gitlinks with no .gitmodules entry from the index. |
| 56 | +
|
| 57 | + Such a gitlink has no declared URL, so dfetch can neither fetch it nor |
| 58 | + report it as a dependency. Removing it from the index leaves its |
| 59 | + directory (if checked out at all) as an empty placeholder and lets |
| 60 | + ``git submodule update``/``foreach`` proceed over the submodules that |
| 61 | + remain, instead of aborting the whole operation. |
| 62 | + """ |
| 63 | + declared = declared_submodule_paths() |
| 64 | + for path in gitlink_paths(): |
| 65 | + if path not in declared: |
| 66 | + logger.debug( |
| 67 | + "Gitlink '%s' has no '.gitmodules' entry; skipping it as a submodule", |
| 68 | + path, |
| 69 | + ) |
| 70 | + run_on_cmdline(logger, ["git", "update-index", "--force-remove", path]) |
0 commit comments