0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【完全保存版】GitHubを完全にマスターする学習ガイド - 初心者から上級者まで全32章

Last updated at Posted at 2025-11-13

License: MIT
GitHub

この記事について

この記事は、GitHubの全機能を体系的に学べる完全ガイドです。

📚 こんな人におすすめ

  • Gitは使えるけどGitHubの機能をもっと知りたい
  • チーム開発でGitHubを使い始める
  • CI/CDやGitHub Actionsを学びたい
  • オープンソースに貢献したい

✨ この記事の特徴

  • 全32章、2,000行超の大ボリューム
  • コマンド一覧が表形式で見やすい
  • コピペで使えるコード例が豊富
  • 実践的なベストプラクティス付き
  • Issue、PR、Actions、Wiki、Discussions等全機能を網羅

⏱️ 想定読了時間

  • 全体:約60分
  • 基礎編のみ:約15分
  • 必要な部分だけ:辞書として使用可能

📑 目次

  1. Gitコマンド完全リファレンス
  2. 環境準備
  3. 基礎編:Gitの基本操作
  4. リポジトリ管理
  5. ブランチ戦略とワークフロー
  6. Issue管理
  7. Pull Request(PR)
  8. コードレビュー
  9. GitHub Actions(CI/CD)
  10. プロジェクト管理
  11. セキュリティ機能
  12. 高度な機能
  13. トラブルシューティング
  14. ベストプラクティス
  15. 実践プロジェクト

1. Gitコマンド完全リファレンス

1.1 初期設定

コマンド 説明 使用例
git config --global user.name "名前" ユーザー名を設定 git config --global user.name "Taro Yamada"
git config --global user.email "email" メールアドレスを設定 git config --global user.email "taro@example.com"
git config --global init.defaultBranch main デフォルトブランチ名を設定 -
git config --global core.editor "editor" デフォルトエディタを設定 git config --global core.editor "code --wait"
git config --list すべての設定を表示 -

1.2 リポジトリの作成・クローン

コマンド 説明 使用例
git init 新規リポジトリを初期化 git init
git clone <URL> リモートリポジトリをクローン git clone https://github.com/user/repo.git
git clone -b <branch> <URL> 特定のブランチをクローン git clone -b develop https://github.com/user/repo.git

1.3 ファイルの追加・コミット

コマンド 説明 使用例
git add <file> ファイルをステージング git add index.html
git add . すべての変更をステージング git add .
git commit -m "message" コミットを作成 git commit -m "機能を追加"
git commit -am "message" ステージング+コミット git commit -am "バグ修正"
git commit --amend 最新のコミットを修正 git commit --amend

1.4 状態確認・差分表示

コマンド 説明 使用例
git status 作業ツリーの状態を確認 git status
git diff 未ステージングの変更を表示 git diff
git diff --staged ステージング済みの変更を表示 git diff --staged
git log コミット履歴を表示 git log
git log --oneline 1行で表示 git log --oneline

1.5 ブランチ操作

コマンド 説明 使用例
git branch ブランチ一覧を表示 git branch
git branch <name> 新しいブランチを作成 git branch feature/login
git checkout <branch> ブランチを切り替え git checkout develop
git checkout -b <branch> ブランチを作成して切り替え git checkout -b feature/signup
git branch -d <name> ブランチを削除 git branch -d feature/login
git merge <branch> ブランチをマージ git merge feature/login

1.6 リモート操作

コマンド 説明 使用例
git remote -v リモートリポジトリを表示 git remote -v
git remote add <name> <URL> リモートリポジトリを追加 git remote add origin https://github.com/user/repo.git
git fetch リモートの変更を取得 git fetch
git pull リモートから取得してマージ git pull
git push リモートにプッシュ git push
git push -u origin <branch> ブランチを追跡してプッシュ git push -u origin feature/login

1.7 変更の取り消し

コマンド 説明 使用例
git reset <file> ステージングを取り消し git reset index.html
git reset --soft HEAD~1 コミットを取り消し(変更は保持) git reset --soft HEAD~1
git reset --hard HEAD~1 コミットを完全に取り消し git reset --hard HEAD~1
git revert <commit> コミットを打ち消す git revert abc1234
git restore <file> ファイルの変更を破棄 git restore index.html

1.8 一時保存(Stash)

コマンド 説明 使用例
git stash 変更を一時保存 git stash
git stash list stash一覧を表示 git stash list
git stash apply 最新のstashを適用 git stash apply
git stash pop stashを適用して削除 git stash pop
git stash drop stashを削除 git stash drop stash@{0}

1.9 タグ操作

コマンド 説明 使用例
git tag タグ一覧を表示 git tag
git tag <name> 軽量タグを作成 git tag v1.0.0
git tag -a <name> -m "msg" 注釈付きタグを作成 git tag -a v1.0.0 -m "Version 1.0.0"
git push --tags すべてのタグをプッシュ git push --tags
git tag -d <name> タグを削除 git tag -d v1.0.0

2. 環境準備

2.1 Gitのインストール

Windows

  1. Git for Windowsをダウンロード
  2. インストーラーを実行
  3. デフォルト設定で進めてOK

macOS

# Homebrewを使用
brew install git

# またはXcode Command Line Tools
xcode-select --install

Linux (Ubuntu/Debian)

sudo apt update
sudo apt install git

2.2 Gitの初期設定

# ユーザー名を設定
git config --global user.name "あなたの名前"

# メールアドレスを設定
git config --global user.email "your.email@example.com"

# デフォルトブランチ名をmainに設定
git config --global init.defaultBranch main

# デフォルトエディタを設定
git config --global core.editor "code --wait"

# 設定を確認
git config --list

2.3 GitHubアカウントの作成

  1. GitHubにアクセス
  2. 「Sign up」をクリック
  3. メールアドレス、パスワード、ユーザー名を入力
  4. メール認証を完了

2.4 SSH鍵の設定(推奨)

# SSH鍵を生成
ssh-keygen -t ed25519 -C "your.email@example.com"

# SSH agentを起動
eval "$(ssh-agent -s)"

# SSH鍵をagentに追加
ssh-add ~/.ssh/id_ed25519

# 公開鍵の内容を表示
cat ~/.ssh/id_ed25519.pub

GitHubにSSH鍵を登録

  1. GitHubにログイン
  2. Settings → SSH and GPG keys
  3. 「New SSH key」をクリック
  4. 公開鍵の内容を貼り付け
  5. 「Add SSH key」をクリック
# 接続テスト
ssh -T git@github.com

3. 基礎編:Gitの基本操作

3.1 最初のリポジトリを作成

GitHubでリポジトリを作成

  1. GitHubにログイン
  2. 右上の「+」→「New repository」
  3. リポジトリ名:github-practice
  4. 「Add a README file」にチェック
  5. 「Create repository」をクリック

ローカルにクローン

# SSHの場合
git clone git@github.com:your-username/github-practice.git

# HTTPSの場合
git clone https://github.com/your-username/github-practice.git

# ディレクトリに移動
cd github-practice

# リポジトリの状態を確認
git status

3.2 ファイルの追加とコミット

# 新しいファイルを作成
echo "# 学習メモ" > memo.md
echo "今日からGitHubの学習を始めます" >> memo.md

# ファイルの状態を確認
git status

# ファイルをステージング
git add memo.md

# コミット
git commit -m "学習メモファイルを追加"

# リモートにプッシュ
git push

3.3 ファイルの編集とコミット

# ファイルに追記
echo "" >> memo.md
echo "## 1日目の学習内容" >> memo.md
echo "- Gitの基本コマンドを学習" >> memo.md

# 変更内容を確認
git diff

# ステージングしてコミット
git add memo.md
git commit -m "1日目の学習内容を追加"

# プッシュ
git push

4. リポジトリ管理

4.1 .gitignoreの設定

.gitignoreファイルは、Gitで追跡したくないファイルを指定します。

Python プロジェクトの例

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*.so

# Virtual environments
venv/
env/
ENV/

# IDEs
.vscode/
.idea/
*.swp

# OS
.DS_Store
Thumbs.db

# Environment variables
.env
.env.local

# Logs
*.log

# Database
*.db
*.sqlite3

4.2 READMEの書き方

# プロジェクト名

プロジェクトの簡単な説明

## 機能

- 機能1
- 機能2
- 機能3

## インストール

\`\`\`bash
git clone https://github.com/username/repo.git
cd repo
pip install -r requirements.txt
\`\`\`

## 使い方

\`\`\`bash
python main.py
\`\`\`

## ライセンス

MIT License

5. ブランチ戦略とワークフロー

5.1 ブランチの基本操作

# 新しいブランチを作成
git branch feature/calculator

# ブランチを切り替え
git checkout feature/calculator

# または、作成と切り替えを同時に
git checkout -b feature/calculator

# ブランチ一覧を確認
git branch

# ファイルを作成・編集
echo "def add(a, b): return a + b" > calculator.py

# コミット
git add calculator.py
git commit -m "feat: 計算機機能を追加"

# リモートにプッシュ
git push -u origin feature/calculator

5.2 ブランチのマージ

# mainブランチに切り替え
git checkout main

# 最新の状態を取得
git pull

# featureブランチをマージ
git merge feature/calculator

# リモートにプッシュ
git push

# 不要なブランチを削除
git branch -d feature/calculator
git push origin --delete feature/calculator

5.3 Git Flow戦略

main (production)
├── develop (development)
│   ├── feature/user-auth
│   ├── feature/payment
│   └── feature/notification
├── release/v1.0
└── hotfix/critical-bug

ブランチの種類

ブランチ 役割
main 本番環境のコード
develop 開発の中心ブランチ
feature/ 新機能開発
release/ リリース準備
hotfix/ 緊急修正

6. Issue管理

6.1 Issueの作成

  1. GitHubリポジトリの「Issues」タブ
  2. 「New issue」をクリック
  3. 内容を入力
タイトル: 計算機に平方根機能を追加

## 概要
計算機に平方根を計算する機能を追加したい

## 詳細
- sqrt(x) 関数を実装
- 負の数の場合はエラーを返す
- テストケースを追加

## 受け入れ条件
- [ ] sqrt関数が実装されている
- [ ] 負の数でエラーが発生する
- [ ] テストが通る

6.2 Issueテンプレートの作成

# ディレクトリを作成
mkdir -p .github/ISSUE_TEMPLATE

# バグ報告テンプレート
cat > .github/ISSUE_TEMPLATE/bug_report.md << 'EOF'
---
name: バグ報告
about: バグを報告する
title: '[BUG] '
labels: bug
---

## バグの説明
バグの内容を説明してください

## 再現手順
1. '...'に移動
2. '...'をクリック
3. エラーを確認

## 期待される動作
本来の動作を説明してください

## 環境
- OS: [e.g. Windows 10]
- ブラウザ: [e.g. Chrome 96]
- バージョン: [e.g. 1.0.0]
EOF

7. Pull Request(PR)

7.1 Pull Requestの作成

# 機能ブランチで開発
git checkout -b feature/sqrt-function

# ファイルを編集
# ...

# コミット
git add .
git commit -m "feat: 平方根機能を追加

- sqrt()関数を実装
- 負の数のバリデーションを追加
- ユニットテストを追加

Closes #5"

# プッシュ
git push -u origin feature/sqrt-function

GitHubでPRを作成

  1. GitHubリポジトリに移動
  2. 「Compare & pull request」をクリック
  3. PRの内容を記入
## 変更内容
計算機に平方根機能を追加しました

## 変更点
- sqrt()関数を実装
- 負の数の場合にValueErrorを発生
- ユニットテストを追加

## テスト
すべてのテストが通過しました

## 関連Issue
Closes #5

7.2 Pull Requestテンプレート

cat > .github/pull_request_template.md << 'EOF'
## 変更内容
<!-- この PRで何を変更したか説明してください -->

## 変更の種類
- [ ] バグ修正
- [ ] 新機能
- [ ] ドキュメント更新
- [ ] リファクタリング

## チェックリスト
- [ ] コードが動作することを確認
- [ ] テストを追加/更新
- [ ] ドキュメントを更新

## 関連Issue
Closes #
EOF

8. コードレビュー

8.1 レビューの実施

レビュアーとして

  1. PRページの「Files changed」タブ
  2. コードの行にカーソルを合わせて「+」をクリック
  3. コメントを追加
**提案:**
この関数にdocstringを追加することを提案します

\`\`\`python
def sqrt(x):
    """
    平方根を計算する
    
    Args:
        x (float): 平方根を求める数値
        
    Returns:
        float: xの平方根
    """
\`\`\`
  1. 「Review changes」をクリック
  2. レビュー結果を選択
    • Comment(コメントのみ)
    • Approve(承認)
    • Request changes(変更要求)

8.2 レビュー指摘への対応

# 指摘に対応
# ... ファイルを編集 ...

git add .
git commit -m "docs: docstringを追加"
git push

9. GitHub Actions(CI/CD)

9.1 最初のワークフローを作成

mkdir -p .github/workflows

cat > .github/workflows/python-tests.yml << 'EOF'
name: Python Tests

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main, develop ]

jobs:
  test:
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        python-version: ['3.8', '3.9', '3.10', '3.11']
    
    steps:
    - name: チェックアウト
      uses: actions/checkout@v4
    
    - name: Pythonのセットアップ
      uses: actions/setup-python@v5
      with:
        python-version: ${{ matrix.python-version }}
    
    - name: 依存関係のインストール
      run: |
        python -m pip install --upgrade pip
        pip install pytest
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
    
    - name: テストの実行
      run: |
        python -m pytest tests/ -v
EOF

git add .github/workflows/
git commit -m "ci: Pythonテストワークフローを追加"
git push

9.2 よく使うワークフロー

Node.jsプロジェクト

name: Node.js CI

on:
  push:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-node@v4
      with:
        node-version: '20'
    - run: npm ci
    - run: npm test

10. プロジェクト管理

10.1 GitHub Projectsの作成

  1. リポジトリの「Projects」タブ
  2. 「New project」をクリック
  3. 「Board」を選択
  4. プロジェクト名を入力

10.2 マイルストーンの設定

  1. Issues → Milestones
  2. 「New milestone」をクリック
  3. 情報を入力
タイトル: v1.0.0 リリース
期限: 2024-12-31
説明: 最初の安定版リリース

11. セキュリティ機能

11.1 Dependabotの設定

mkdir -p .github
cat > .github/dependabot.yml << 'EOF'
version: 2
updates:
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
    labels:
      - "dependencies"
EOF

11.2 Branch Protection Rules

  1. Settings → Branches
  2. 「Add rule」をクリック
  3. Branch name pattern: main
  4. 保護設定を有効化
    • Require a pull request before merging
    • Require approvals (1)
    • Require status checks to pass

12. 高度な機能

12.1 Git Hooks(pre-commit)

# pre-commitツールをインストール
pip install pre-commit

# 設定ファイルを作成
cat > .pre-commit-config.yaml << 'EOF'
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
EOF

# Hooksをインストール
pre-commit install

12.2 GitHub Pages

# gh-pagesブランチを作成
git checkout --orphan gh-pages
git rm -rf .

# index.htmlを作成
cat > index.html << 'EOF'
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>GitHub Practice</title>
</head>
<body>
    <h1>GitHub学習プロジェクト</h1>
    <p>このサイトはGitHub Pagesで公開されています</p>
</body>
</html>
EOF

git add index.html
git commit -m "feat: GitHub Pagesサイトを作成"
git push origin gh-pages

Settings → Pages → Source: gh-pagesブランチを選択


13. トラブルシューティング

13.1 コンフリクトの解決

# コンフリクト発生
git merge feature-branch

# コンフリクトファイルを編集
# <<<<<<< HEAD
# =======
# >>>>>>> feature-branch
# これらのマーカーを削除して正しい内容に編集

# 解決したファイルをステージング
git add file.txt

# マージを完了
git commit -m "merge: コンフリクトを解決"

13.2 間違ったコミットの取り消し

# まだプッシュしていない場合
git reset --soft HEAD~1

# プッシュ済みの場合(安全)
git revert HEAD

# プッシュ済みの場合(危険)
git reset --hard HEAD~1
git push --force-with-lease

13.3 .gitignoreが効かない

# キャッシュをクリア
git rm -r --cached .
git add .
git commit -m "fix: .gitignoreを適用"

14. ベストプラクティス

14.1 コミットメッセージ

Conventional Commits形式

<type>(<scope>): <subject>

例:
feat(auth): ユーザー認証を追加
fix(api): タイムアウトエラーを修正
docs: READMEを更新
style: コードをフォーマット
refactor: データベースロジックを改善
test: ユニットテストを追加
chore: 依存関係を更新

14.2 ブランチ命名規則

<type>/<short-description>

例:
feature/user-authentication
bugfix/login-error
hotfix/security-patch
release/v1.2.0
docs/api-documentation

14.3 PRのサイズ

サイズ 行数 推奨度
XS <10 ✅ 理想的
S 10-100 ✅ 良い
M 100-300 ✅ 許容範囲
L 300-500 ⚠️ 大きい
XL >500 ❌ 分割すべき

15. 実践プロジェクト

15.1 Todoアプリの開発

すべての学習内容を実践する最終プロジェクトです。

プロジェクトの準備

# GitHubで新しいリポジトリを作成
# Repository name: todo-app

# クローン
git clone git@github.com:your-username/todo-app.git
cd todo-app

# developブランチを作成
git checkout -b develop
git push -u origin develop

基本構造の作成

# ディレクトリを作成
mkdir -p src tests docs .github/workflows

# README.mdを作成
cat > README.md << 'EOF'
# Todo アプリ

Pythonで作成したシンプルなTodoアプリケーション

## 機能
- Todoの追加
- Todo一覧の表示
- Todoの完了/未完了切り替え
- Todoの削除

## インストール
\`\`\`bash
pip install -r requirements.txt
\`\`\`

## 使い方
\`\`\`bash
python src/main.py
\`\`\`
EOF

git add .
git commit -m "chore: プロジェクト構造を初期化"
git push

アプリケーションの実装

  1. Issue駆動開発

    • 各機能ごとにIssueを作成
    • Issueにラベルとマイルストーンを設定
  2. ブランチ戦略

    • developブランチから機能ブランチを作成
    • 各機能を実装
  3. Pull Request

    • 機能ごとにPRを作成
    • レビューを依頼
  4. CI/CD

    • GitHub Actionsでテストを自動化
    • コードカバレッジを測定
  5. リリース

    • タグを作成
    • リリースノートを作成

📚 継続的学習

学習リソース

公式ドキュメント

書籍

  • 「Pro Git」(無料)
  • 「GitHub実践入門」
  • 「Team Geek」

オンラインコース

  • GitHub Learning Lab
  • Udemy / Coursera
  • freeCodeCamp

コミュニティ

  • GitHub Community Forum
  • Stack Overflow
  • Dev.to

🎯 まとめ

学んだこと

Gitの基本コマンド - init, add, commit, push, pull
リポジトリ管理 - .gitignore, README, LICENSE
ブランチ戦略 - Git Flow, GitHub Flow
Issue管理 - テンプレート、ラベル
Pull Request - 作成、レビュー、マージ
GitHub Actions - CI/CDの自動化
プロジェクト管理 - Projects、マイルストーン
セキュリティ - Dependabot、Branch Protection

重要ポイント

  1. 小さく頻繁にコミット
  2. 明確なコミットメッセージ
  3. 適切なブランチ戦略
  4. コードレビューの文化
  5. 自動化の推進

Happy Coding! 🚀

GitHubを使いこなして、素晴らしいプロジェクトを作りましょう!


16. GitHub Discussions

16.1 Discussionsとは

Discussionsは、コミュニティとの対話やQ&Aに使用する機能です。

DiscussionsとIssueの違い

特徴 Issue Discussions
用途 タスク管理、バグ報告 質問、アイデア、雑談
状態 Open/Closed なし(継続的)
形式 リスト形式 スレッド形式
返信 フラット ネスト可能

16.2 Discussionsの有効化

  1. Settings → Features
  2. 「Discussions」にチェック
  3. カテゴリを設定

推奨カテゴリ

📣 Announcements - お知らせ(メンテナーのみ投稿可)
💡 Ideas - アイデア・機能要望
🙏 Q&A - 質問と回答
📖 Show and tell - 作品紹介
💬 General - 雑談

17. GitHub Wiki

17.1 Wikiの作成

# Wikiリポジトリをクローン
git clone https://github.com/username/repo.wiki.git
cd repo.wiki

# ホームページを作成
cat > Home.md << 'EOF'
# プロジェクトWiki

## 目次
- [インストールガイド](Installation)
- [使い方](Usage)
- [API リファレンス](API-Reference)
- [FAQ](FAQ)
- [トラブルシューティング](Troubleshooting)

## クイックスタート
```bash
git clone https://github.com/username/repo.git
cd repo
python setup.py install

EOF

git add Home.md
git commit -m "docs: Wikiホームページを作成"
git push


### 17.2 Wikiページの追加

```bash
# インストールガイドを作成
cat > Installation.md << 'EOF'
# インストールガイド

## 必要要件
- Python 3.8以上
- pip

## インストール手順

### 1. リポジトリをクローン
```bash
git clone https://github.com/username/repo.git
cd repo

2. 依存関係をインストール

pip install -r requirements.txt

3. 動作確認

python -m pytest

EOF

git add Installation.md
git commit -m "docs: インストールガイドを追加"
git push


---

## 18. CODEOWNERS

### 18.1 CODEOWNERSファイルの作成

CODEOWNERSは、ファイルやディレクトリの責任者を定義します。

```bash
cat > .github/CODEOWNERS << 'EOF'
# これはCODEOWNERSファイルです
# 各行は、ファイルパターンとその所有者を指定します

# デフォルトの所有者
* @username

# ドキュメント
/docs/ @username @doc-team

# フロントエンド
/src/frontend/ @frontend-team
*.js @frontend-team
*.jsx @frontend-team
*.css @frontend-team

# バックエンド
/src/backend/ @backend-team
*.py @backend-team

# インフラ
/infrastructure/ @devops-team
Dockerfile @devops-team
docker-compose.yml @devops-team
.github/workflows/ @devops-team

# セキュリティ
/security/ @security-team
SECURITY.md @security-team
EOF

git add .github/CODEOWNERS
git commit -m "docs: CODEOWNERSを追加"
git push

18.2 CODEOWNERSの効果

  • 指定されたファイルが変更されたPRには、自動的にレビュアーが追加される
  • Branch Protectionと組み合わせて、特定の人の承認を必須にできる

19. GitHub CLI(gh コマンド)

19.1 GitHub CLIのインストール

# macOS
brew install gh

# Windows
winget install --id GitHub.cli

# Ubuntu/Debian
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
sudo apt update
sudo apt install gh

19.2 認証

# 認証
gh auth login

# 状態確認
gh auth status

19.3 便利なコマンド

リポジトリ操作

# リポジトリを作成
gh repo create my-new-repo --public --clone

# リポジトリを表示
gh repo view

# リポジトリをブラウザで開く
gh repo view --web

# リポジトリをフォーク
gh repo fork

# リポジトリをクローン
gh repo clone username/repo

Issue操作

# Issue一覧を表示
gh issue list

# Issueを作成
gh issue create --title "バグ報告" --body "説明..."

# Issueを表示
gh issue view 123

# Issueをブラウザで開く
gh issue view 123 --web

# Issueを閉じる
gh issue close 123

# Issueを再開
gh issue reopen 123

Pull Request操作

# PR一覧を表示
gh pr list

# PRを作成
gh pr create --title "新機能" --body "説明..."

# PRを作成(インタラクティブ)
gh pr create

# PRを表示
gh pr view 123

# PRをチェックアウト
gh pr checkout 123

# PRをマージ
gh pr merge 123 --squash

# PRのステータスを確認
gh pr status

# PRにコメント
gh pr comment 123 --body "LGTMです!"

# PRをレビュー
gh pr review 123 --approve
gh pr review 123 --request-changes --body "修正が必要です"

ワークフロー操作

# ワークフロー一覧を表示
gh workflow list

# ワークフローを実行
gh workflow run "Python Tests"

# ワークフロー実行履歴を表示
gh run list

# 実行ログを表示
gh run view 123456

リリース操作

# リリース一覧を表示
gh release list

# リリースを作成
gh release create v1.0.0 --title "Version 1.0.0" --notes "リリースノート"

# リリースにファイルを添付
gh release create v1.0.0 dist/*.tar.gz

# リリースを表示
gh release view v1.0.0

Gist操作

# Gistを作成
gh gist create file.txt

# Gistを一覧表示
gh gist list

# Gistを表示
gh gist view 123abc

20. GitHub Packages

20.1 GitHub Packagesとは

GitHub Packagesは、パッケージホスティングサービスです。

対応するパッケージタイプ:

  • npm(JavaScript)
  • Docker
  • Maven(Java)
  • NuGet(.NET)
  • RubyGems
  • PyPI(Python)

20.2 Dockerイメージの公開

# Dockerfileを作成
cat > Dockerfile << 'EOF'
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]
EOF

# ビルド
docker build -t ghcr.io/username/myapp:latest .

# GitHub Container Registryにログイン
echo $GITHUB_TOKEN | docker login ghcr.io -u username --password-stdin

# プッシュ
docker push ghcr.io/username/myapp:latest

20.3 GitHub Actionsで自動公開

name: Publish Docker Image

on:
  push:
    tags: ['v*']

jobs:
  push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Log in to GitHub Container Registry
      uses: docker/login-action@v3
      with:
        registry: ghcr.io
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}
    
    - name: Extract metadata
      id: meta
      uses: docker/metadata-action@v5
      with:
        images: ghcr.io/${{ github.repository }}
    
    - name: Build and push
      uses: docker/build-push-action@v5
      with:
        context: .
        push: true
        tags: ${{ steps.meta.outputs.tags }}
        labels: ${{ steps.meta.outputs.labels }}

21. チーム・組織管理

21.1 Organizationの作成

  1. 右上のアイコン → Settings
  2. Organizations → New organization
  3. プランを選択(Free/Team/Enterprise)
  4. 組織名とメールアドレスを入力

21.2 チームの作成

  1. Organization → Teams
  2. New team
  3. チーム名と説明を入力
  4. メンバーを追加

チームの階層構造

@organization/engineering
├── @organization/frontend
├── @organization/backend
└── @organization/devops

21.3 リポジトリの権限管理

権限レベル

役割 権限
Read クローン、読み取りのみ
Triage Issueとラベルの管理
Write プッシュ、PR作成
Maintain リポジトリ設定の一部管理
Admin すべての権限

チームに権限を付与

  1. Repository → Settings → Collaborators and teams
  2. Add teams
  3. チームを選択し、権限レベルを設定

22. GitHub Environments

22.1 環境の設定

環境(Environments)は、デプロイ先を定義し、保護ルールを設定できます。

name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy-staging:
    runs-on: ubuntu-latest
    environment:
      name: staging
      url: https://staging.example.com
    steps:
      - uses: actions/checkout@v4
      - name: Deploy to Staging
        run: ./deploy.sh staging

  deploy-production:
    runs-on: ubuntu-latest
    needs: deploy-staging
    environment:
      name: production
      url: https://example.com
    steps:
      - uses: actions/checkout@v4
      - name: Deploy to Production
        run: ./deploy.sh production

22.2 環境保護ルール

Settings → Environments → production

設定項目:

  • ✅ Required reviewers(承認者必須)
  • ✅ Wait timer(待機時間)
  • ✅ Deployment branches(特定ブランチのみ)

23. セキュリティポリシー

23.1 SECURITY.mdの作成

cat > SECURITY.md << 'EOF'
# セキュリティポリシー

## サポートされているバージョン

現在サポートされているバージョンは以下の通りです:

| バージョン | サポート状況 |
| ------- | ---------- |
| 1.x.x   | ✅ |
| < 1.0   | ❌ |

## 脆弱性の報告

セキュリティ脆弱性を発見した場合は、以下の方法で報告してください:

### 報告方法

1. **GitHub Security Advisories**を使用(推奨)
   - Security タブ → Advisories → New draft security advisory

2. **メール**
   - security@example.com に報告
   - PGP公開鍵: [リンク]

### 報告に含める情報

- 脆弱性の種類
- 影響を受けるバージョン
- 再現手順
- 潜在的な影響
- 修正案(あれば)

### 対応プロセス

1. **24時間以内**: 受領確認
2. **7日以内**: 初期評価と対応方針
3. **30日以内**: 修正版リリース(重要度による)

### 禁止事項

- 脆弱性の公開(修正前)
- 攻撃的な検証
- サービス妨害

## 謝辞

脆弱性を報告してくださった方は、修正後にCREDITS.mdに記載させていただきます。
EOF

git add SECURITY.md
git commit -m "docs: セキュリティポリシーを追加"
git push

24. GitHub Profile README

24.1 プロフィールREADMEの作成

自分のユーザー名と同じ名前のリポジトリを作成すると、プロフィールページに表示されます。

# ユーザー名と同じリポジトリを作成
# 例:username/username

cat > README.md << 'EOF'
# こんにちは!👋

私は[@username](https://github.com/username)です。

## 🚀 スキル

![Python](https://img.shields.io/badge/-Python-3776AB?style=flat-square&logo=python&logoColor=white)
![JavaScript](https://img.shields.io/badge/-JavaScript-F7DF1E?style=flat-square&logo=javascript&logoColor=black)
![React](https://img.shields.io/badge/-React-61DAFB?style=flat-square&logo=react&logoColor=black)

## 📊 GitHub Stats

![GitHub Stats](https://github-readme-stats.vercel.app/api?username=username&show_icons=true&theme=radical)

## 📫 連絡先

- Twitter: [@username](https://twitter.com/username)
- Email: your.email@example.com
- Blog: [https://blog.example.com](https://blog.example.com)

## 💼 現在の取り組み

- 🔭 オープンソースプロジェクトに貢献中
- 🌱 機械学習を学習中
- 👯 コラボレーションを歓迎します

## ⚡ Fun Fact

コーヒーとコードが大好きです!☕️
EOF

25. リリース管理

25.1 リリースの作成

GitHub UIから

  1. Releases → Draft a new release
  2. Tag version: v1.0.0
  3. Release title: Version 1.0.0
  4. 説明を記入
## 🎉 新機能
- ユーザー認証機能を追加
- ダッシュボードを実装

## 🐛 バグ修正
- ログイン時のタイムアウトを修正
- メモリリークを修正

## 📝 改善
- パフォーマンスを30%向上
- UIを改善

## ⚠️ Breaking Changes
- API v1は廃止されました。v2を使用してください

## 📦 アセット
- `app-v1.0.0.zip` - アプリケーション本体
- `source-v1.0.0.tar.gz` - ソースコード
  1. バイナリファイルをアップロード
  2. Publish release

コマンドラインから

# タグを作成
git tag -a v1.0.0 -m "Version 1.0.0"
git push origin v1.0.0

# GitHub CLIでリリースを作成
gh release create v1.0.0 \
  --title "Version 1.0.0" \
  --notes "リリースノート" \
  dist/*.zip

25.2 自動リリースノート生成

Settings → Releases → Automatically generated release notes

GitHub Actionsでの自動化:

name: Release

on:
  push:
    tags: ['v*']

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
      
      - name: Build
        run: |
          mkdir -p dist
          # ビルド処理
      
      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          files: dist/*
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

26. Webhooks

26.1 Webhookの設定

Webhooksは、GitHubのイベントを外部サービスに通知します。

Webhookの作成

  1. Settings → Webhooks → Add webhook
  2. Payload URL: https://your-server.com/webhook
  3. Content type: application/json
  4. Secret: セキュアなランダム文字列
  5. イベントを選択

イベントの種類

  • push - コミットのプッシュ
  • pull_request - PR作成・更新
  • issues - Issue作成・更新
  • issue_comment - Issueコメント
  • release - リリース作成
  • deployment - デプロイメント
  • star - スター追加

26.2 Webhookの受信例(Python)

from flask import Flask, request, jsonify
import hmac
import hashlib

app = Flask(__name__)
WEBHOOK_SECRET = "your-secret-here"

def verify_signature(payload_body, signature_header):
    """GitHub Webhookの署名を検証"""
    hash_object = hmac.new(
        WEBHOOK_SECRET.encode('utf-8'),
        msg=payload_body,
        digestmod=hashlib.sha256
    )
    expected_signature = "sha256=" + hash_object.hexdigest()
    return hmac.compare_digest(expected_signature, signature_header)

@app.route('/webhook', methods=['POST'])
def webhook():
    # 署名を検証
    signature = request.headers.get('X-Hub-Signature-256')
    if not verify_signature(request.data, signature):
        return jsonify({'error': 'Invalid signature'}), 401
    
    # イベントタイプを取得
    event = request.headers.get('X-GitHub-Event')
    payload = request.json
    
    if event == 'push':
        handle_push(payload)
    elif event == 'pull_request':
        handle_pull_request(payload)
    
    return jsonify({'status': 'success'}), 200

def handle_push(payload):
    """Pushイベントを処理"""
    repo = payload['repository']['full_name']
    commits = payload['commits']
    print(f"Received {len(commits)} commits to {repo}")

def handle_pull_request(payload):
    """Pull Requestイベントを処理"""
    action = payload['action']
    pr_number = payload['number']
    print(f"PR #{pr_number} was {action}")

if __name__ == '__main__':
    app.run(port=5000)

27. Gist

27.1 Gistの作成

Gistは、コードスニペットやメモを共有するサービスです。

Web UIから

  1. https://gist.github.com/ にアクセス
  2. ファイル名と内容を入力
  3. Public/Secretを選択
  4. Create gist

コマンドラインから

# GitHub CLIを使用
gh gist create file.txt

# 複数ファイル
gh gist create file1.txt file2.py

# 説明を追加
gh gist create file.txt --desc "便利なスクリプト"

# Secret gist
gh gist create file.txt --secret

27.2 Gistの活用例

  • コードスニペットの共有
  • 設定ファイルの保存
  • 簡単なメモ
  • マークダウンドキュメント

28. Fork・Star・Watch

28.1 Forkの使い方

リポジトリをFork

  1. リポジトリページで「Fork」をクリック
  2. 自分のアカウントにコピーされる
# Forkしたリポジトリをクローン
git clone git@github.com:your-username/original-repo.git
cd original-repo

# オリジナルをupstreamとして追加
git remote add upstream git@github.com:original-owner/original-repo.git

# upstreamから最新を取得
git fetch upstream
git merge upstream/main

変更を本家に提案

# 新しいブランチで変更
git checkout -b feature/improvement

# 変更をコミット
git add .
git commit -m "feat: 改善を追加"

# 自分のForkにプッシュ
git push origin feature/improvement

# GitHubでPull Requestを作成

28.2 Star

  • ✨ お気に入りのリポジトリをマーク
  • 📊 自分のスターリスト: https://github.com/username?tab=stars
  • 🔔 スターしたリポジトリの更新を通知

28.3 Watch

リポジトリの更新を通知で受け取る

オプション 説明
Not watching 通知なし
Releases only リリースのみ
Watching すべての活動
Ignoring 完全に無視

29. 通知管理

29.1 通知の種類

  • 👥 メンション(@username
  • 💬 コメントへの返信
  • 📝 アサインされたIssue/PR
  • 👀 レビュー依頼
  • ✅ CI/CDの結果

29.2 通知設定

Settings → Notifications

Email通知:
- Participating: 自分が参加しているもの
- Watching: Watchしているリポジトリ

Web通知:
- リアルタイムで受信

29.3 通知の管理

# GitHub CLIで通知を確認
gh api notifications

# 通知を既読にする
gh api notifications -X PUT

30. GitHub Actions 高度な機能

30.1 Reusable Workflows

再利用可能なワークフローを作成

# .github/workflows/reusable-tests.yml
name: Reusable Tests

on:
  workflow_call:
    inputs:
      python-version:
        required: true
        type: string
    secrets:
      token:
        required: true

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ inputs.python-version }}
      - run: pytest

使用する側:

# .github/workflows/ci.yml
name: CI

on: [push]

jobs:
  test:
    uses: ./.github/workflows/reusable-tests.yml
    with:
      python-version: '3.11'
    secrets:
      token: ${{ secrets.TOKEN }}

30.2 Composite Actions

複数のステップを1つのアクションにまとめる

# .github/actions/setup-app/action.yml
name: 'Setup Application'
description: 'Setup application dependencies'

inputs:
  node-version:
    description: 'Node.js version'
    required: true
    default: '20'

runs:
  using: 'composite'
  steps:
    - uses: actions/setup-node@v4
      with:
        node-version: ${{ inputs.node-version }}
    
    - run: npm ci
      shell: bash
    
    - run: npm run build
      shell: bash

使用例:

steps:
  - uses: actions/checkout@v4
  - uses: ./.github/actions/setup-app
    with:
      node-version: '20'

30.3 Matrix Strategy(詳細)

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        python-version: ['3.8', '3.9', '3.10', '3.11']
        exclude:
          - os: macos-latest
            python-version: '3.8'
        include:
          - os: ubuntu-latest
            python-version: '3.12'
            experimental: true
    
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
      - run: pytest
        continue-on-error: ${{ matrix.experimental || false }}

31. コントリビューション

31.1 コントリビューショングラフ

  • 📊 アクティビティの可視化
  • 🔥 連続日数(Streak)
  • 📈 年間のコミット数

31.2 良いコントリビューターになるために

オープンソースへの貢献手順

  1. プロジェクトを見つける

    • GitHub Explore
    • good first issueラベル
    • 自分が使っているツール
  2. Issueを確認

    • バグを報告
    • 機能を提案
    • ドキュメントを改善
  3. 小さく始める

    • タイポ修正
    • ドキュメント追加
    • テスト追加
  4. コミュニケーション

    • Issue/PRで丁寧に説明
    • フィードバックを受け入れる
    • コミュニティに敬意を払う

32. 総合チートシート

よく使うGitコマンド

# 初期設定
git config --global user.name "名前"
git config --global user.email "email"

# 基本操作
git init                    # リポジトリ初期化
git clone <URL>            # クローン
git add .                  # すべてステージング
git commit -m "message"    # コミット
git push                   # プッシュ
git pull                   # プル

# ブランチ
git branch <name>          # ブランチ作成
git checkout <name>        # ブランチ切り替え
git checkout -b <name>     # 作成+切り替え
git merge <name>           # マージ

# 確認
git status                 # 状態確認
git log --oneline          # ログ表示
git diff                   # 差分表示

# 取り消し
git reset HEAD~1           # コミット取り消し
git revert <commit>        # コミット打ち消し
git restore <file>         # 変更破棄

GitHub CLI チートシート

# 認証
gh auth login

# リポジトリ
gh repo create <name>      # 作成
gh repo view --web         # ブラウザで開く
gh repo clone <repo>       # クローン

# Issue
gh issue list              # 一覧
gh issue create            # 作成
gh issue view <number>     # 表示
gh issue close <number>    # 閉じる

# Pull Request
gh pr list                 # 一覧
gh pr create               # 作成
gh pr view <number>        # 表示
gh pr checkout <number>    # チェックアウト
gh pr merge <number>       # マージ

# その他
gh workflow list           # ワークフロー一覧
gh release create <tag>    # リリース作成
gh gist create <file>      # Gist作成

まとめ

このガイドで学んだすべての内容を実践すれば、GitHubのほぼすべての機能を使いこなせるようになります。

📚 カバーした機能

✅ 基本機能

  • Git基本操作
  • リポジトリ管理
  • ブランチ操作

✅ コラボレーション

  • Issue管理
  • Pull Request
  • コードレビュー
  • Discussions
  • Wiki
  • CODEOWNERS

✅ プロジェクト管理

  • GitHub Projects
  • マイルストーン
  • ラベル

✅ 自動化

  • GitHub Actions
  • Workflows
  • Reusable Workflows
  • Composite Actions
  • Webhooks

✅ セキュリティ

  • Dependabot
  • Code Scanning
  • Secret Scanning
  • Branch Protection
  • SECURITY.md

✅ デプロイ

  • GitHub Pages
  • GitHub Packages
  • Environments

✅ チーム管理

  • Organizations
  • Teams
  • 権限管理

✅ その他

  • GitHub CLI
  • Gist
  • Fork/Star/Watch
  • 通知管理
  • Profile README
  • リリース管理

🎯 次のステップ

  1. 毎日Gitを使う - 習うより慣れろ
  2. オープンソースに貢献 - 実践で学ぶ
  3. 自動化を進める - GitHub Actionsを活用
  4. ドキュメントを充実させる - チームで共有
  5. 継続的に学ぶ - 新機能をチェック

🎉 お疲れ様でした!🎉

このガイドで、あなたはGitHub マスターです!

GitHub

Happy Coding! 🚀

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?