I have been using git for repo path, something lik...
# general
k
I have been using git for repo path, something like:
Copy code
from pathlib import Path

from git import Repo


def get_repo_path() -> Path:
    repo = Repo(".", search_parent_directories=True)
    return Path(repo.git.rev_parse("--show-toplevel"))
I have not gotten this to work in pants (probably missing .git/HEAD) and have not been able to fix it. Is there a recommended way of getting repo path when using pants?
h
Hi, this is very short on details. Are you writing a Pants plugin? Or if not what does it mean to “work in pants”?
What exactly are you doing with Pants in relation to this code that is failing?
k
Just normal pants test, let say you where to have a test like this:
Copy code
from somewhere import get_repo_path

def test_readme_exist_at_root() -> None:
    assert (
        get_repo_path() / "README.md"
    ).exists(), "README.md not found at root of repository"
Which is part of a python_test target. I then run:
pants test ::
This fails, and I believe since the git files are not included in the sandbox, it cannot find root. I have tried to fix this but I realized that this is probably a common thing to do, there might be a better way to do this?
h
Yes, tests run in a sandbox, so they don’t have access to the real git root
In the past I’ve dealt with this problem by having the test set up a temporary git repository
So that the test is truly hermetic
Would that work in this case?
a
Or alternatively make a resource target to the
.git
folder and add it as a manual dependency on
get_repo_path()
module if the code expects some notion of the real history beside the file path
h
The trouble is, by default pants ignores everything that .gitignore ignores
That can be overridden, but there might be unintended consequences
For example, now Pants has to filewatch the entire .git dir, which can get large
k
I have tried to add the .git as dependency. I ended up in having to try to change pants_ignore to not ignore .git/HEAD, but I did not get this to work. I can continue down that path if there are no existing solutions. https://www.pantsbuild.org/dev/reference/global-options#pants_ignore
h
It might help to understand the underlying thing you’re trying to do. For example, is this code intended to run on git repos in general, or specifically the git repo it lives in?
k
On it's own repo, or that is what I currently use it for. But I have solved this by using
Path(__file__)
for now.
h
Yes, exactly what I was getting at. If this is intended to run only on the same repo, then using git data to find your way around the repo seems like massive overkill