Skip to content

Instantly share code, notes, and snippets.

@elfsternberg
Created February 10, 2023 22:53
Show Gist options
  • Save elfsternberg/ebfd7b9fdc4e124b04f84f89cf336cdb to your computer and use it in GitHub Desktop.
Save elfsternberg/ebfd7b9fdc4e124b04f84f89cf336cdb to your computer and use it in GitHub Desktop.
Python `get git root` function, for build scripts
import subprocess
def get_root() -> str:
"""Return the current project root.
A lot of scripts written for build system need to know where they are
relative to a project's root. This function returns the root folder, giving
developers a concrete starting location for all file manipulation.
"""
root = subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
if not root:
raise OSError(2, "file not found (no git root detected)")
return root.splitlines().pop().decode("utf-8")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment