decemberrobot
decemberrobot

Reputation: 531

gitpython to check for if there are any changes in files using PYTHON

I am experimenting with gitpython and I am new to it. I am trying to detect if there are any changes staged for commit.

Currently, I have a function that looks like this:

def commit(dir):
r = Repo(dir)
r.git.add(A=True)
r.git.commit(m='commit all')

But this is just the code to commit the directory. I wanna do something like, if there are changes, then display some message, else, display another message.

Anybody have any idea how do I do it in python ?

Upvotes: 4

Views: 10294

Answers (2)

mark sabido
mark sabido

Reputation: 440

To get a definitive list of what's changed (but not yet staged):

# Gives a list of the differing objects
diff_list = repo.head.commit.diff()

for diff in diff_list:
    print(diff.change_type) # Gives the change type. eg. 'A': added, 'M': modified etc.

    # Returns true if it is a new file
    print(diff.new_file) 

    # Print the old file path
    print(diff.a_path)

    # Print the new file path. If the filename (or path) was changed it will differ
    print(diff.b_path) 

# Too many options to show. This gives a comprehensive description of what is available
help(diff_list[0]) 

I found the diff object to be very useful and should give any info you require.

For staged items, use repo.index

From my testing, I found that the previous answer gave a diff output the wrong way round (ie. added files would show up as deleted).

The other option is repo.git.diff(...) which I found less useful as it gives long text strings for output rather than objects that can be easily parsed.

Upvotes: 2

dpwr
dpwr

Reputation: 2812

You can check for all unstaged changes like this:

for x in r.index.diff("HEAD"):
    # Just print
    print(x)

    # Or for each entry you can find out information about it, e.g.
    print(x.new_file)
    print(x.b_path)

Basically you are comparing the staging area (i.e. index) to the active branch.

Upvotes: 6

Related Questions