30日でマスター Git バージョン管理

Day 30: 実務で役立つ Git 操作の Tips 共有

Git を学んだ 29 日間を経て、この最終記事では、日々の Git 操作をより効率的で楽しいものにする実践的な Tips とコツを共有します。

設定の Tips

グローバル設定

# Set default editor
git config --global core.editor "code --wait"

# Enable color UI
git config --global color.ui auto

# Set default branch name
git config --global init.defaultBranch main

# Auto-correct typos
git config --global help.autocorrect 1

# Cache credentials
git config --global credential.helper cache --timeout=3600

便利なエイリアス

# Short status
git config --global alias.st status

# Short log
git config --global alias.ll "log --oneline --graph --all --decorate"

# Last commit
git config --global alias.last "log -1 HEAD"

# Undo last commit (keep changes)
git config --global alias.undo "reset HEAD~1 --mixed"

# Amend without editing message
git config --global alias.amend "commit --amend --no-edit"

# List branches sorted by last modified
git config --global alias.br "branch --sort=-committerdate"

# Show changed files in last commit
git config --global alias.dl "diff --name-only HEAD~1"

# Search commit messages
git config --global alias.search "log --all --grep"

# Nuke branch (force delete)
git config --global alias.nuke "branch -D"

生産性の Tips

クイックナビゲーション

# Jump to repository root
alias gr='cd $(git rev-parse --show-toplevel)'

# Open repo in browser
alias browse='git remote get-url origin | xargs open'

検索

# Find file in history
git log --all --full-history -- "**/filename.*"

# Search in all commits
git log -S "search term" --source --all

# Find who changed a line
git blame filename

# Prettier blame
git blame -w -C -C -L 10,20 filename

クリーンアップ

# Delete merged branches
git branch --merged main | grep -v "^*\|main" | xargs git branch -d

# Delete all local branches except main
git branch | grep -v "main" | xargs git branch -D

# Remove untracked files (dry run first!)
git clean -n
git clean -fd

# Prune remote branches
git fetch --prune

時間を節約するコマンド

クイックコミット

# Add and commit in one step
git commit -am "Quick fix"

# Add, commit, and push
alias gcp='git commit -am "$1" && git push'

ブランチ管理

# Create and checkout branch in one step
git checkout -b feature/new-feature

# Switch to previous branch
git checkout -

# Show branches with last commit
git branch -v

# Show remote tracking branches
git branch -vv

Stash のコツ

# Stash with message
git stash push -m "Work in progress on feature X"

# List stashes with details
git stash list --pretty=format:"%C(yellow)%gd%C(reset) - %C(bold)%s%C(reset)"

# Apply and drop in one step
git stash pop

# Apply specific stash
git stash apply stash@{2}

# Stash including untracked files
git stash -u

高度なテクニック

複数のコミットを cherry-pick する

# Cherry-pick a range of commits
git cherry-pick A^..B

# Cherry-pick from another branch
git cherry-pick feature-branch~3..feature-branch

インタラクティブなステージング

# Stage parts of a file
git add -p filename

# Interactive add
git add -i

Diff の Tips

# Word diff instead of line diff
git diff --word-diff

# Ignore whitespace changes
git diff -w

# Show diff of staged changes
git diff --staged

# Diff between branches
git diff main..feature-branch

# Diff specific file between commits
git diff commit1 commit2 -- filename

ログのフォーマット

# Pretty log
git log --pretty=format:"%C(yellow)%h%C(reset) - %C(green)(%cr)%C(reset) %s %C(blue)<%an>%C(reset)"

# Log with graph
git log --graph --abbrev-commit --decorate --all

# Show files changed per commit
git log --stat

# Show patches
git log -p

トラブルシューティング

ミスを取り消す

# Undo last commit (keep changes)
git reset --soft HEAD~1

# Undo last commit (discard changes)
git reset --hard HEAD~1

# Undo all uncommitted changes
git checkout .

# Unstage file
git reset HEAD filename

# Restore file from HEAD
git checkout HEAD -- filename

復旧

# Find lost commits
git reflog

# Recover deleted branch
git branch branch-name <commit-hash>

# Find dangling commits
git fsck --lost-found

デバッグ

# See who introduced a bug (binary search)
git bisect start
git bisect bad  # Current version is bad
git bisect good <commit>  # Known good commit
# Git checks out middle commit
# Test and mark as good or bad
git bisect good/bad
# Repeat until found
git bisect reset

# Blame with line range
git blame -L 10,20 filename

# Show commit that introduced line
git log -S "function name" --source --all

ワークフローの最適化

Pre-Commit フック

.git/hooks/pre-commit を作成します。

#!/bin/bash

# Run tests before commit
npm test
if [ $? -ne 0 ]; then
    echo "Tests failed, commit aborted"
    exit 1
fi

コミットメッセージテンプレート

~/.git-commit-template を作成します。

# <type>: <subject>
#
# <body>
#
# <footer>
#
# Types: feat, fix, docs, style, refactor, test, chore

デフォルトとして設定します。

git config --global commit.template ~/.git-commit-template

統合の Tips

Git と VS Code

# Open current repo in VS Code
code .

# Open merge tool
git mergetool --tool=vscode

Git と Vim

# Set Vim as default editor
git config --global core.editor vim

# Vim as diff tool
git config --global diff.tool vimdiff
git config --global difftool.prompt false

パフォーマンスの Tips

大規模なリポジトリ

# Shallow clone (faster)
git clone --depth 1 https://github.com/user/repo.git

# Partial clone (Git 2.22+)
git clone --filter=blob:none https://github.com/user/repo.git

# Sparse checkout (specific folders)
git sparse-checkout init
git sparse-checkout set folder1 folder2

より高速なステータス

# Use untracked cache
git config core.untrackedCache true

# Use file system monitor
git config core.fsmonitor true

セキュリティの Tips

GPG 署名

# Generate GPG key
gpg --gen-key

# List keys
gpg --list-secret-keys --keyid-format LONG

# Configure Git
git config --global user.signingkey <key-id>
git config --global commit.gpgsign true

# Sign commits
git commit -S -m "Signed commit"

認証情報

# Never store passwords in config
# Use credential helpers instead

# SSH for authentication (recommended)
ssh-keygen -t ed25519 -C "email@example.com"

# Use HTTPS with token
# Generate personal access token on GitHub
# Use it as password

最後の知恵

ベストプラクティスのチェックリスト

  • 頻繁にコミットし、定期的にプッシュする
  • 意味のあるコミットメッセージを書く
  • コミットをアトミックで焦点の絞られたものに保つ
  • すべての機能/修正にブランチを作る
  • PR の前に自分のコードをレビューする
  • プッシュする前にプルする
  • 共有ブランチには決して強制プッシュしない
  • .gitignore を適切に使う
  • リリースにタグを付ける
  • ワークフローを文書化する

問題が起きたとき

  1. 慌てない:Git がデータを失うことはめったにありません
  2. reflog を確認する:あなたのセーフティネットです
  3. バックアップを作る:実験する前にブランチを作成します
  4. 助けを求める:Git コミュニティは親切です
  5. ミスから学ぶ:すべてのエラーが何かを教えてくれます

おめでとうございます!

30 日間の Git マスターの旅を完了しました!以下を学びました。

  • Git の基礎とアーキテクチャ
  • ブランチとマージの戦略
  • 履歴の操作(reset、rebase、amend)
  • リモートワークフローとコラボレーション
  • GitHub のワークフローとベストプラクティス
  • 高度な Tips とトラブルシューティング

学び続ける

  • 定期的に練習します
  • オープンソースに貢献します
  • 他の人の Git 履歴から学びます
  • 高度な機能を探求します
  • Git のリリース情報を常に把握します

最後に

Git は、使えば使うほど価値が高まる強力なツールです。すべてを覚えようとする必要はありません。このガイドをブックマークして、必要なときに参照してください。最も大切なのは、練習を続けることと、(安全な環境で)実験を恐れないことです。

ハッピーコーディング!そして、あなたのマージが常に競合フリーでありますように!

参考リンク



ありがとうございました!

この 30 日間の Git の旅にお付き合いいただき、ありがとうございました。練習を続け、学び続けましょう。そして、すべての Git エキスパートも、かつては初心者だったことを忘れないでください!