Traffine I/O

日本語

2023-02-03

PyGithub

PyGithubとは

PyGithubは、開発者がGitHub APIと簡単にやり取りできるようにするPythonライブラリです。PyGithubを使用すると、開発者はGitHubのWebインターフェースを介して通常手動で実行するタスクを自動化できます。例えば、リポジトリの作成や削除、プルリクエストの管理、ユーザーや組織データへのアクセスなどです。

このライブラリは、GitHub APIを扱う際の詳細を抽象化する高水準のインターフェースを提供し、初心者から経験豊富な開発者まで使いやすくなっています。また、PyGithubライブラリはオープンソースです。

PyGitHubの使い方

PyGithubを始めるには、以下の基本的な手順に従います。

PyGitHubのインストール

まず、システムにPyGitHubライブラリをインストールする必要があります。これはPythonパッケージマネージャーのpipを使用して行うことができます。PyGitHubをインストールするには、コマンドプロンプトまたはターミナルウィンドウを開き、次のコマンドを入力します。

bash
$ pip install PyGitHub

これにより、システムに最新バージョンのPyGitHubが必要に応じて依存関係とともにインストールされます。

GitHub APIトークンの作成

次に、GitHubプラットフォームでパーソナルアクセストークンを作成する必要があります。このトークンは、PyGitHubスクリプトを認証し、GitHub APIと対話することを許可します。

新しいパーソナルアクセストークンを作成するには、次の手順を実行してください。

  1. GitHubアカウントにログイン
  2. 画面右上隅にあるプロフィール写真をクリックし、ドロップダウンメニューから「設定」を選択
  3. 左側のサイドバーで「開発者設定」をクリックし、「個人用アクセストークン」を選択
  4. 「新しいトークンを生成」ボタンをクリック
  5. トークンに名前を付け、付与する権限を選択。ほとんどのPyGitHubスクリプトには、「repo」と「user」の権限を選択する必要がありますが、特定の使用例に応じて追加の権限を選択する必要がある場合もあります。
  6. 「トークンを生成」ボタンをクリックして新しいトークンを作成

パーソナルアクセストークンを作成したら、トークン作成画面を離れた後に再度表示できないため、安全な場所にコピーして保管しておくようにしてください。

PyGitHubの基本

PyGitHubは、開発者がGitHub APIと簡単にやり取りできるようにするPythonライブラリです。この記事では、GitHub APIとの認証方法、リポジトリ、イシュー、プルリクエスト、コメントの作成方法、ブランチの操作について説明します。

PyGitHubでの認証

PyGitHubを使用してGitHub APIに認証するには、パーソナルアクセストークンを提供する必要があります。これはGithubクラスのインスタンスを作成し、アクセストークンをパラメータとして渡すことで行います。

python
from github import Github

# Create an instance of the Github class
g = Github("<personal-access-token>")

認証が完了すると、gオブジェクトを使用してGitHub APIとやり取りできます。

リポジトリの作成

PyGitHubを使用してGitHub上で新しいリポジトリを作成するには、Githubオブジェクトのcreate_repoメソッドを使用できます。

python
# Create a new repository
repo = g.get_user().create_repo("new-repo")

これにより、"new-repo"という名前の新しいリポジトリがGitHub上に作成されます。

イシューの作成

PyGitHubを使用してリポジトリに新しいイシューを作成するには、Repositoryオブジェクトのcreate_issueメソッドを使用します。

python
# Create a new issue on the repository
issue = repo.create_issue("Issue title", "Issue body")

これにより、指定されたタイトルと本文を持つ新しいイシューがリポジトリに作成されます。

ファイルの作成

PyGithubを使用してリポジトリに新しいファイルを作成するには、Repositoryオブジェクトのcreate_fileメソッドを使用します。

python
from github import Github

# Authenticate to GitHub using a personal access token
g = Github("<personal-access-token>")

# Get the repository
repo = g.get_repo("<username>/<repository>")

# Create a new file
file_content = "Hello, world!"
file_path = "example.txt"
file_message = "Add example.txt"
repo.create_file(file_path, file_message, file_content)

このコードは、リポジトリのルートディレクトリに「example.txt」という名前の新しいファイルを作成し、「Hello, world!」という内容を書き込みます。

ファイルの更新

PyGithubでリポジトリ上の既存のファイルを更新するには、 Repositoryオブジェクトのupdate_fileメソッドを使用できます。

python
from github import Github

# Authenticate to GitHub using a personal access token
g = Github("<personal-access-token>")

# Get the repository
repo = g.get_repo("<username>/<repository>")

# Get the existing file
file = repo.get_contents("example.txt")

# Update the file
file_content = "Hello, PyGithub!"
file_path = "example.txt"
file_message = "Update example.txt"
repo.update_file(file_path, file_message, file_content, file.sha)

このコードは、既存のファイル「example.txt」を「Hello, PyGithub!」に更新します。

ファイルの削除

PyGithubでリポジトリ上の既存のファイルを削除するには、 Repositoryオブジェクトのdelete_fileメソッドを使用できます。

python
from github import Github

# Authenticate to GitHub using a personal access token
g = Github("<personal-access-token>")

# Get the repository
repo = g.get_repo("<username>/<repository>")

# Get the existing file
file = repo.get_contents("example.txt")

# Delete the file
file_message = "Delete example.txt"
repo.delete_file(file.path, file_message, file.sha)

このコードは、リポジトリから既存のファイルexample.txtを削除します。

変更をコミット

PyGithubを使用してリポジトリに変更をコミットするには、 GitAuthorオブジェクトのcommitメソッドを使用できます。以下は、ファイルを削除するコードの例です。この例では、mainブランチからファイルを削除しています。

python
from github import Github
from github import InputGitAuthor

# Authenticate to GitHub using a personal access token
g = Github("<personal-access-token>")

# Get the repository
repo = g.get_repo("<username>/<repository>")

# Create a new file
file_content = "Hello, world!"
file_path = "example.txt"
file_message = "Add example.txt"
repo.create_file(file_path, file_message, file_content)

# Commit the changes
author = InputGitAuthor("<Your Name>", "<your.email@example.com>")
repo.get_git_ref("heads/master").commit(
    "New commit",
    repo.get_contents(file_path).sha,
    author=author,
    committer=author,
    tree=repo.get_git_tree("master").sha
)

このコードは、メッセージが「New commit」、著者とコミッター情報が<Your Name><your.email@example.com>に設定され、example.txtファイルに加えられた変更がこのコミットに含まれるように、新しいコミットを作成します。

プルリクエストの作成

PyGitHubを使用して、リポジトリに新しいプルリクエストを作成するには、Repositoryオブジェクトのcreate_pullメソッドを使用します。

python
# Create a new pull request
pull_request = repo.create_pull(
    title="Pull Request Title",
    body="Pull Request Body",
    head="my-feature-branch",
    base="master"
)

これにより、指定したタイトル、本文、およびブランチ情報を持つリポジトリに新しいプルリクエストが作成されます。

コメントの作成

PyGitHubを使用して、問題やプルリクエストに新しいコメントを作成するには、IssueまたはPullRequestオブジェクトのcreate_commentメソッドを使用します。

python
# Create a new comment on an issue
comment = issue.create_comment("Comment text")

# Create a new comment on a pull request
comment = pull_request.create_comment("Comment text")

このコードは、指定されたテキストで与えられたissueやpull requestに新しいコメントを作成します。

ブランチを操作

PyGitHubでブランチを操作するには、Repositoryオブジェクトのcreate_git_refメソッドを使用します。

python
# Create a new branch
ref = repo.create_git_ref("refs/heads/my-feature-branch", "master")

これにより、指定したテキストで、問題またはプルリクエストに新しいコメントが作成されます。

ブランチでの作業

PyGitHubでブランチを操作するには、Repositoryオブジェクトのcreate_git_refメソッドを使用します。

python
# Merge the pull request
pull_request.merge()

This will merge the pull request into the target branch.

複数のファイルを編集する

ソフトウェア開発プロジェクトでは、Githubリポジトリ内の複数のファイルを編集します。PyGithubは、Github APIとやり取りするために使用できるPythonライブラリであり、これらのタスクを簡単に実行することができます。この記事では、PyGithubを使用して複数のファイルを編集し、変更をGithubリポジトリの新しいブランチにコミットする方法について説明します。

PyGithubを使用してGithubリポジトリ内の複数のファイルを編集するには、次の手順を実行する必要があります。

  1. Githubクラスのインスタンスを作成し、Github APIで認証
  2. Githubインスタンスとリポジトリ名を使用してリポジトリオブジェクトを取得
  3. Repositoryオブジェクトのget_branchメソッドを使用して、ブランチオブジェクトを取得
  4. Repositoryオブジェクトのget_git_treeメソッドを使用して、ブランチのSHAを渡すことでツリーオブジェクトを取得
  5. Repositoryオブジェクトのget_contentsメソッドを使用して、ファイルパスを渡すことでファイルのblobオブジェクトを取得
  6. ファイルの内容を編集
  7. Repositoryオブジェクトのcreate_git_blobメソッドを使用して、新しいファイルの内容を渡して新しいblobオブジェクトを作成
  8. ツリーオブジェクト内のファイルパスとblob SHAを更新
  9. Repositoryオブジェクトのcreate_git_treeメソッドを使用して、更新されたファイルパスとblob SHAを渡すことで新しいツリーオブジェクトを作成
  10. Repositoryオブジェクトのcreate_git_commitメソッドを使用して、コミットメッセージ、更新されたツリーSHA、および親コミットSHAを渡して新しいコミットオブジェクトを作成
  11. Repositoryオブジェクトのcreate_git_refメソッドを使用して、新しいブランチ名と新しいコミットSHAを渡して新しいブランチを作成

以下は、リポジトリ内の複数のファイルを編集するためのコード例です。

python
from github import Github
import base64

# authenticate with Github API
g = Github('<GITHUB_ACCESS_TOKEN>')

# retrieve the repository object
repo = g.get_repo('<OWNER>/<REPO>')

# retrieve the branch object
branch = repo.get_branch('master')

# retrieve the tree object
tree = repo.get_git_tree(branch.commit.sha)

# retrieve the blob objects of the files
file1 = repo.get_contents('file1.txt')
file2 = repo.get_contents('file2.txt')

# edit the file contents
file1_content = "This is a new content for file1"
file2_content = "This is a new content for file2"

# create new blob objects
blob1 = repo.create_git_blob(file1_content, 'utf-8')
blob2 = repo.create_git_blob(file2_content, 'utf-8')

# update the file paths and blob SHAs in the tree object
tree_new = []
for item in tree.tree:
    if item.path == 'file1.txt':
        tree_new.append({'path': 'file1.txt', 'mode': item.mode, 'type': item.type, 'sha': blob1.sha})
    elif item.path == 'file2.txt':
        tree_new.append({'path': 'file2.txt', 'mode': item.mode, 'type': item.type, 'sha': blob2.sha})
    else:
        tree_new.append({'path': item.path, 'mode': item.mode, 'type': item.type, 'sha': item.sha})

# create new tree object
new_tree = repo.create_git_tree(tree_new)

# create new commit object
commit_message = 'Updated multiple files'
commit = repo.create_git_commit(commit_message, new_tree.sha, [branch.commit.sha])

# create new branch
new_branch = repo.create_git_ref(f'refs/heads/new-branch', commit.sha)

このコードスニペットでは、2つのファイル(「file1.txt」と「file2.txt」)の内容を更新し、「new-branch」という新しいブランチに更新されたファイルで新しいコミットを作成します。更新されたファイルは、create_git_blobメソッドを使用して新しいBlobオブジェクトとして保存され、Treeオブジェクトは新しいBlob SHAで更新されます。最後に、新しいTreeオブジェクトとCommitオブジェクトが作成され、create_git_refメソッドを使用して新しいブランチが作成されます。

参考

https://github.com/PyGithub/PyGithub

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!