From 293df5e38bc3215177995e2cffbc33af0f2e7ad7 Mon Sep 17 00:00:00 2001 From: Ross Burton Date: Thu, 13 Feb 2025 15:16:07 +0000 Subject: [PATCH] Clean up _git_toplevel() Instead of asking git what the relative path of the current directory is from the root of the repository and then reverse-engineering the root, simply call git rev-parse --show-toplevel. This option was added in git 1.7.0 back in 2010, so I think it's fair to assume it exists. --- src/setuptools_scm/_file_finders/git.py | 29 ++----------------------- 1 file changed, 2 insertions(+), 27 deletions(-) diff --git a/src/setuptools_scm/_file_finders/git.py b/src/setuptools_scm/_file_finders/git.py index 7b23f886..0368b5d2 100644 --- a/src/setuptools_scm/_file_finders/git.py +++ b/src/setuptools_scm/_file_finders/git.py @@ -19,33 +19,8 @@ def _git_toplevel(path: str) -> str | None: try: - cwd = os.path.abspath(path or ".") - res = _run(["git", "rev-parse", "HEAD"], cwd=cwd) - if res.returncode: - # BAIL if there is no commit - log.error("listing git files failed - pretending there aren't any") - return None - res = _run( - ["git", "rev-parse", "--show-prefix"], - cwd=cwd, - ) - if res.returncode: - return None - out = res.stdout[:-1] # remove the trailing pathsep - if not out: - out = cwd - else: - # Here, ``out`` is a relative path to root of git. - # ``cwd`` is absolute path to current working directory. - # the below method removes the length of ``out`` from - # ``cwd``, which gives the git toplevel - assert cwd.replace("\\", "/").endswith(out), f"cwd={cwd!r}\nout={out!r}" - # In windows cwd contains ``\`` which should be replaced by ``/`` - # for this assertion to work. Length of string isn't changed by replace - # ``\\`` is just and escape for `\` - out = cwd[: -len(out)] - log.debug("find files toplevel %s", out) - return norm_real(out) + res = _run(["git", "rev-parse", "--show-toplevel"], cwd=path, check=True) + return res.stdout except subprocess.CalledProcessError: # git returned error, we are not in a git repo return None