Reputation: 19
I am new to GitPython and I am trying to have a python program stage itself to a new git repository (my-new-repo).
My main.py is as follows:
import git
repo = git.Repo.init('my-new-repo')
# List all branches
for branch in repo.branches:
print(branch)
# Provide a list of the files to stage
repo.index.add(['main.py'])
# Provide a commit message
repo.index.commit('Initial commit')
File tree:
├── main.py
├── my-new-repo (directory)
├── .git
But when I run it, it returns this error:
No such file or directory: 'main.py'
Traceback (most recent call last):
File "/home/aaron/Downloads/GitPython/main.py", line 17, in <module>
repo.index.add(['main.py'])
File "/home/aaron/Downloads/GitPython/git/index/base.py", line 815, in add
entries_added.extend(self._entries_for_paths(paths, path_rewriter, fprogress, entries))
File "/home/aaron/Downloads/GitPython/git/util.py", line 144, in wrapper
return func(self, *args, **kwargs)
File "/home/aaron/Downloads/GitPython/git/index/util.py", line 109, in set_git_working_dir
return func(self, *args, **kwargs)
File "/home/aaron/Downloads/GitPython/git/index/base.py", line 694, in _entries_for_paths
entries_added.append(self._store_path(filepath, fprogress))
File "/home/aaron/Downloads/GitPython/git/index/base.py", line 639, in _store_path
st = os.lstat(filepath) # handles non-symlinks as well
FileNotFoundError: [Errno 2] No such file or directory: 'main.py'
Process finished with exit code 1
Upvotes: 1
Views: 175
Reputation: 11080
GitPython's repo.index.add
function stages files from the directory of the repo. git.Repo.init('my-new-repo')
creates a new repo in the (possibly new) directory my-new-repo. If main.py is not in the repo directory, then GitPython won't be able to see it.
To fix this, you can copy main.py into the repo's directory. Like this:
import git
import shutil
repo = git.Repo.init('my-new-repo')
# List all branches
for branch in repo.branches:
print(branch)
# copy main.py into my-new-repo
shutil.copy('main.py', 'my-new-repo/main.py')
# Provide a list of the files to stage
repo.index.add(['main.py'])
# Provide a commit message
repo.index.commit('Initial commit')
Upvotes: 1