让GitPython自己登台

hgncfbus  于 2022-11-20  发布在  Git
关注(0)|答案(1)|浏览(114)

我是GitPython的新手,我正在尝试让一个python程序自己登台到一个新的git仓库(my-new-repo)。
我的main.py如下:

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')

档案树状目录:

├── main.py
├── my-new-repo (directory)
    ├── .git

但当我运行它时,它返回以下错误:

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
yeotifhr

yeotifhr1#

GitPython的repo.index.add函数暂存repo目录中的文件。git.Repo.init('my-new-repo')在(可能是新的)目录my-new-repo中创建一个新的repo。如果main.py不在repo目录中,那么GitPython将无法看到它。
要解决这个问题,可以将www.example.com复制main.py到repo的目录中,如下所示:

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')

相关问题