19
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ターミナルでgitを使う際に設定していること

Posted at

はじめに

  • 世の中にgitクライアントはたくさんあるけれど、ターミナルからコマンドでgit操作する際に自分が設定していることを記載します

プロンプトにブランチ名を出すようにしておく

  • 基本的にこれだけ
  • 偉そうに前置きしておいてスミマセン
  • ちなみに前提として、bash5.1以上での話になります

やりかた

.git-prompt.shを入れる

  • なんなら .git-completion.sh も入れる
  • .git-prompt.shはGitリポジトリの状態を表示できるようになる
  • .git-completion.shはコマンドをタブキーで補完できるようになる

  1. .git-prompt.shと.git-completion.shを自分のHOME配下に持ってくる
  2. .bashrcに設定を記載(以下は例)
source ~/.git-prompt.sh
source ~/.git-completion.sh

# addされていなかったりcommitされていないファイルがある場合に*や+を表示
GIT_PS1_SHOWDIRTYSTATE=true

# __git_ps1でプロンプト上にブランチ名を表示
# 1行が長くなるので改行を挿入
PS1='\[\033[32m\]\u@\h\[\033[00m\]:\[\033[36m\]\w\[\033[31m\]$(__git_ps1)\[\033[00m\]\n\$ '
export PS1

プロンプトに表示する文字について色を変えるには次を参考に。
https://qiita.com/araki-yzrh/items/421d75dde0bec8a28c69
表示する内容についてはbashのエスケープシーケンスで好きなものを。

エスケープシーケンス 表示される内容
\u 現在のユーザー名
\h ホスト名
\w 現在のディレクトリの絶対パス
\\$ rootの場合#、それ以外のユーザーの場合$
... ...

以上

git-promptとかgit-completionを入れられない場合

  • 参画するプロジェクト、会社によっては勝手に何かしらダウンロードしたりインストールできない場合もあるかと思います
    • vscodeの拡張機能についても一つ一つ申請して許可が下りないとインストールさせてもらえないとかありました
  • しかしブランチ名だけでも表示したほうが良いと思うので少しだけ頑張って表示する

.bashrcに以下を追記しブランチ名を表示するようにする

  • awkが嫌だとか使えない場合はsedとかで代替
function is_under_git_tree {
  git rev-parse --is-inside-work-tree &>/dev/null
}

function get_branch_name {
  if ! is_under_git_tree; then
    return
  fi

  branch=$(git branch --no-color |  awk '$1 == "*" {print $2}')
  [[ -n "$branch" ]] && echo " ($branch)"
}

PS1='\[\033[32m\]\u@\h\[\033[00m\]:\[\033[36m\]\w\[\033[31m\]$(get_branch_name)\[\033[00m\]\n\$ '
export PS1

.gitconfigに以下を追加しタイピング量を減らして補完無しでもなんとかなるようにする

[alias]
    co = checkout
    st = status
    ci = commit
    di = diff
    br = branch
    tree = log --pretty=format:\"%C(yellow)%h%C(auto)(%ce) %C(auto)%s %C(green)%d %C(auto)%cd \" --graph

以上

19
6
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
19
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?