Search code examples
pythongitgitpython

Not able to commit file to git using gitpython library


I have a local git repository. I have a python file in it called 'fibo.py'. I edited that file in editor and saved the changes. Then I wrote following code to commit that file to repo.

from git import Repo
import os

repo_dir = 'D:\\Git Repo\\newrepo1'
file_list = []
repo1 = Repo(repo_dir)
print(os.getcwd())
os.chdir('%s' % repo_dir)
dirs = os.listdir()
print(os.getcwd())
# This would print all the files and directories
for file in dirs:
    if file != '.git':
        print(file)
        new_file_path = osp.join(repo1.working_tree_dir, file)
        open(file,'r').close
        filelist.append(new_file_path)

commit_message = 'adding new files'
repo1.index.add(file_list)
repo1.index.commit(commit_message)

It is performing the commit. I checked log but when I check for the commit records

print(repo1.untracked_files)
for commit in list(repo1.iter_commits()):
    print('COMMITS--->',commit.stats.files)

It gives me this output

['fibo.py']
COMMITS---> {}
COMMITS---> {}
COMMITS---> {}
COMMITS---> {}

Can anyone help me suggest changes


Solution

  • Except the error of filelist and file_list misspell. I solved it, just edit the for loop

    for file in dirs:
        if file != '.git':
            print(file)
            new_file_path = osp.join(repo1.working_tree_dir, file)
            print(new_file_path)
            print(repo1.index)
            #open(file,'w').close
            repo1.index.add([new_file_path])
    

    Only put the repo1.commit after the For loop and it works