Search code examples
pythongithub-api

Get member last commit date using the PyGitHub library


I am developing a python script which requires me to get a list of all GitHub organization members who did not perform commits for a long time for any organization repository. By that we would like to find non active members and remove them from the organization

Any ideas on how to get member last commit date using the PyGitHub library?


Solution

  • Use the Search commit API and filter with repo of your organization using the org parameter :

    GET https://api.github.com/search/commits?q=[SEARCH REQUEST]
    

    You need to use the header Accept: application/vnd.github.cloak-preview to use this API. The following gives all the commits made in a repository owned by a specific organization for a specific user, and sorted by most recent first :

    curl -s -H "Accept: application/vnd.github.cloak-preview" \
        https://api.github.com/search/commits?q=author:fgette%20org:BboxLab%20sort:author-date-desc
    

    You can then filter the date of most recent commit in that organization :

    curl -s -H "Accept: application/vnd.github.cloak-preview" \
        https://api.github.com/search/commits?q=author:fgette%20org:BboxLab%20sort:author-date-desc | \
        jq -r '.items[0].commit.author.date'
    

    Using you would use the following to check if the most recent commit is inferior to a deadline (here < 12 months from now) :

    from github import Github
    from datetime import date
    from datetime import datetime
    from dateutil.relativedelta import relativedelta
    
    deadline = datetime.combine(
        date.today() + relativedelta(months=-12), 
        datetime.min.time()
    )
    
    g = Github("YOUR_TOKEN", per_page = 1)
    
    commits = g.search_commits(
        query = 'author:fgette org:BboxLab sort:author-date-desc'
    )
    
    data = commits.get_page(0)
    
    if (len(data) > 0):
        last_commit = data[0].commit.author.date
        print(f'last commit : {last_commit}')
        if (last_commit < deadline):
            print("too old :(")
        else:
            print("ok :)")
    

    Output :

    last commit : 2019-03-06 15:29:26

    too old :(