简体   繁体   中英

How to get the directory git detail from repo in GitPython?

I would like to get the number of commit of a directory(called module) from a repo(project) in GitPython.

> print("before",modulePath) 
> repo = Repo(modulePath)                    
> print(len(list(repo.iter_commits())))

When I'm trying to print the directory amount of commits, It says the repo is not a valid git Repo.

  • before /home/user/project/module
  • git.exc.InvalidGitRepositoryError: /home/user/project/ module

Any help or idea would be welcome :) Thanks

This is an example code from one of my old projects (not open, so no repository links):

def parse_commit_log(repo, *params):
    commit = {}
    try:
        log = repo.git.log(*params).split("\n")
    except git.GitCommandError:
        return

    for line in log:
        if line.startswith("    "):
            if not 'message' in commit:
                commit['message'] = ""
            else:
                commit['message'] += "\n"
            commit['message'] += line[4:]
        elif line:
            if 'message' in commit:
                yield commit
                commit = {}
            else:
                field, value = line.split(None, 1)
                commit[field.strip(":")] = value
    if commit:
        yield commit

Explanation:

The function expects instance of Repo and same parameters you would pass to git log command. So, usage in your case could look like this:

repo = git.Repo('project_path')
commits = list(parse_commit_log(repo, 'module_dir'))

Internally, repo.git.log is calling git log command. Its output looks sort of like this:

commit <commit1 sha>
Author: User <username@email.tld>
Date:   Sun Apr 7 17:08:31 2019 -0400

    Commit1 message

commit <commit2 sha>
Author: User2 <username2@email.tld>
Date:   Sun Apr 7 17:08:31 2019 -0400

    Commit2 message

parse_commit_log parses this output and yields commit messages. You need to add few more lines to get commit sha, author and date, but it should not be too hard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM