Gitの基本的なワークフロー
Gitは以下の3つの領域でコードを管理します。
- 作業ディレクトリ(Working Directory):現在編集中のファイル群
- ステージングエリア(Staging Area):次回コミットに含める変更を一時的に保存
- ローカルリポジトリ(Repository):コミット済みのスナップショットが保存される場所
一般的な流れは「作業ディレクトリで編集 → ステージング → コミット → リモートプッシュ」です。
リポジトリの初期化とクローン
$ git init --initial-branch=main
$ git clone https://github.com/vuejs/core.git
変更の追跡とコミット
ステージング
$ git add file.txt
$ git add src/
$ git add .
$ git status -s
コミット
$ git commit -m "feat: 新機能追加"
$ git commit -a -m "fix: バグ修正" # 既存ファイルのみ自動ステージ
コミットメッセージの修正
$ git commit --amend -m "修正後のメッセージ"
リモート操作
$ git remote add origin https://github.com/user/repo.git
$ git push -u origin main
$ git pull origin main
$ git fetch origin
履歴の操作
変更の取り消し
$ git restore file.txt # 作業ディレクトリの変更を破棄
$ git reset HEAD file.txt # ステージングから除外
$ git reset --hard HEAD~1 # 最新コミットを完全に破棄
安全な取り消し(履歴保持)
$ git revert HEAD # 逆コミットを作成
ブランチ管理
$ git branch feature/login
$ git checkout -b feature/auth
$ git merge --no-ff feature/auth # マージコミットを強制生成
$ git branch -d feature/auth # 安全削除
$ git push origin --delete old-branch
タグ操作
$ git tag -a v1.2.0 -m "リリースバージョン"
$ git push origin v1.2.0
$ git checkout -b release-v1.2.0 v1.2.0
一時退避(Stash)
$ git stash push -m "未完成の認証機能"
$ git stash list
$ git stash pop
.gitignore設定例
# ビルド成果物
/dist
/build
# 依存パッケージ
node_modules/
# IDE設定
*.idea
!.important.idea
# 特定拡張子
logs/*.log
高度な操作
Cherry-pick
$ git cherry-pick a1b2c3d # 特定コミットを移植
Rebaseによる履歴整理
$ git rebase -i HEAD~3
# エディタでsquash/fixupを指定して複数コミットを統合
作者情報の修正
$ git commit --amend --author="New Name <new@email.com>"
ネットワーク最適化
# HTTPSプロキシ設定
$ git config --global http.proxy http://127.0.0.1:8080
# GitHub専用SOCKS5プロキシ
$ git config --global http.https://github.com.proxy socks5://127.0.0.1:10808
マルチアカウント設定
~/.ssh/configに以下を追加:
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_work
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_personal
リポジトリ内でローカル設定:
$ git config user.name "Work Account"
$ git config user.email "work@company.com"
コミットログのエクスポート
# カスタムフォーマットで出力
$ git log --pretty=format:"%h - %an, %ar : %s" --since="1 week ago" > changelog.txt
# CSV形式で出力
$ git log --pretty=format:"%ai,%an,%s" --encoding=utf-8 > commits.csv
コミットメッセージ規約(Angularスタイル)
形式:<type>(<scope>): <subject>
- タイプ:feat, fix, docs, style, refactor, test, chore など
- 本文:命令形・小文字・末尾にピリオド不要
feat(auth): パスワードリセット機能を追加
fix(api): CORSエラーを修正