2

I have a script that is placed in a folder structure as such:

~/wofc/folder1/folder2/script.py

script.py uses the git module to go some tasks. However when I run the script from outside of folder2 i.e. when I have cd into folder1 i run python folder2/script.py arg1 arg2 I get the raise InvalidGitRepositoryError(epath) error. The script runs fine when I run it from inside folder2 i.e. cd into folder2 and run python script.py arg1 arg2. Below is the relevant code snippet. Can You please let me know what is the issue?

    git = Repo('{}/..'.format(os.getcwd())).git
    git.checkout('master')
    git.pull()

4 Answers 4

2

To run git commands, the current folder should be a git repo.

.git repo should be present to execute git commands.

That is the reason for the error.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of Repo('{}/..'.format(os.getcwd())).git, use os.path.abspath:

git = Repo(os.path.abspath('{}/..'.format(os.getcwd())).git
git.checkout('master')
git.pull()

1 Comment

gives the same issue I am currently facing
1

The problem is that you use os.getcwd() which returns the current working directory. If you stand just outside folder2 this function will return ~/wofc/folder1.

You should swap it for something like:

import os
os.path.dirname(os.path.abspath(__file__))

For example like this:

import os
path = os.path.dirname(os.path.abspath(__file__))
git = Repo('{}/..'.format(path)).git
git.checkout('master')
git.pull()

1 Comment

wrong answer, the repo directory is not in the same path!
0

As user1846747 said, gitPython requires a Repo object to run a git command.

This is a classic bootstrap issue (chicken and egg problem): "how can I run a git command running gitPython to find where the Repo root is, when I need to know where the root is to create a Repo object to run a git command?"

@MaxNoe solved this in Find the root of the git repository where the file lives with his python-gitpath project httpsgithub.com/MaxNoe/python-gitpath

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.