LoginSignup
0
3

More than 3 years have passed since last update.

PyGithubを使って、GitHubの情報を取得する

Posted at

こんにちは、@yshr10icです。

最近、アウトプットの目標として、GitHubに1日1コミット以上することを心掛けています。(もちろん、コミットすることが目的ではいけないことは重々承知しています。)

せっかく毎日コミットするのだから、どれくらいコミットしたのか可視化したいと思いました。そこで、GitHubのコミットログを取得する方法を調べていたところ、PyGithubの存在を知りました。

本記事では、PyGithubの使い方を簡単にまとめたいと思います。

PyGithubとは

PyGitHub is a Python library to access the GitHub API v3 and Github Enterprise API v3. This library enables you to manage GitHub resources such as repositories, user profiles, and organizations in your Python applications.

GitHub API v3およびGithub Enterprise API v3にアクセスするためのライブラリ。リポジトリやユーザプロファイル、組織のようなGitHubのリソースをあなたのPythonアプリケーションで管理することができるようになります。

PyGithubのインストール

$ pip install PyGithub

私の環境では、バージョンは1.47です。

PyGithubの使い方

PyGithub - Examplesから一部抜粋。

GitHubインスタンスの作成

create_instance.py
from github import Github

# ユーザ名、パスワードによるインスタンス生成
g = GitHub('username', 'password')

# アクセストークンによるインスタンス生成
g = Github('access_token')

# カスタムホストによるGitHubエンタープライズのインスタンス生成
g = Github(base_url='https://{hostname}/api/v3', login_or_token='access_token')

リポジトリ一覧の取得

get_repos.py
for repo in g.get_user().get_repos():
    print(repo)

出力

Repository(full_name="yshr10ic/deep-learning-from-scratch")
Repository(full_name="yshr10ic/deep-learning-from-scratch-2")
...

スター数の取得

get_count_of_stars.py
repo = g.get_repo('yshr10ic/deep-learning-from-scratch-2')
print(repo.stargazers_count)

出力

1

ブランチ一覧の取得

get_branches.py
repo = g.get_repo('yshr10ic/deep-learning-from-scratch-2')
for branch in repo.get_branches():
    print(branch)

出力

Branch(name="images")
Branch(name="master")

コミットしたファイル一覧の取得

get_committed_files.py
repo = g.get_repo('yshr10ic/sample')
for commit in repo.get_commits():
    print(commit.files)

出力

[File(sha="xxx", filename="django/djangorestframework/tutorial/tutorial/urls.py")]
[File(sha="yyy", filename="django/djangorestframework/tutorial/tutorial/quickstart/views.py")]
[File(sha="zzz", filename="django/djangorestframework/tutorial/tutorial/quickstart/serializers.py")]
...

まとめ

今回は、既にあるGitHubリポジトリの情報を取得するだけでしたが、実際にはファイルの作成や、プルリク、イシューの作成などもできます。

GitHubインスタンスの生成から各種情報の取得までをやってみましたが、非常に簡単に情報を取得できて良かったですね。ただ、「どれくらいコミットしたのか可視化したい」という当初の目的を達成するには、コミットログを時間で検索できないといけません。PyGithubだと時間による検索ができそうもないので、他の手段も検討してみます。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3