📘

自分のgit config設定を忘れない環境を作る

2023/01/29に公開

私物でも会社のPCでも同じ設定を利用したいという理由から同じ設定ファイルを共有しています。
Gitのconfig設定方法をおさらいしつつまとめておこうと思います。
設定ファイルとそれを実現するコマンドも記載しておきますので、必要に応じて参照してください。
環境はMacです。

設定ファイル

自分はconfig以下のファイル群をprivateのGit内で管理しています。

ホームディレクトリ
├─ config/
│  ├─ gitconfig.txt
│  └─ gitmessage.txt
├─ .gitconfig(※シンボリックリンク)
└─ .gitmessage(※シンボリックリンク)

共有設定ファイルの利用方法

ホームディレクトリにconfigディレクトリ内のファイルからシンボリックリンクを作成します。
コマンドでglobalの設定を叩くと、きちんと元の~/config/gitconfig.txtのファイルが更新されます。

$ ln -s ~/config/gitconfig.txt ~/.gitconfig
$ ln -s ~/config/gitmessage.txt ~/.gitmessage

もし別の設定ファイルを使いたいなどあれば、上記の方法でGit管理+ブランチを切り替えるか、ファイルコピーして使用してください。

$ cp ~/config/gitconfig.txt ~/.gitconfig
$ cp ~/config/gitmessage.txt ~/.gitmessage

.gitconfigファイル

以下の設定を記載してます。

  • ユーザー名とメールアドレス
  • デフォルトのブランチ名
  • デフォルトのコミットメッセージ
  • コマンドのエイリアス
[user]
	name = sample
	email = sample@sample.com
[init]
	defaultBranch = main
[commit]
	template = ~/.gitmessage
[alias]
	ci = commit
	st = status
	br = branch
	co = checkout

.gitmessageファイル

先頭に#をつけることでコミットメッセージ例文を表示させます。(この部分はコミットのメッセージに含まれません)
また、先頭2行を空行にしています。git commitでvimが立ち上がったときに1行目の空行にカーソルが当たるのでコミットメッセージが書きやすいという理由です。



# コミットメッセージ例文)
# - Fix typo in docs
# - Remove unused code
# - Remove use of deprecated method
# - Update Xxxx to v1.6
# - Make sure to reset defaultOptions
# - Don't use xxxxx
# - Allow the user to drag faster

テンプレートを入れておきたい場合、先頭に#を入れなければOKです。

[ID-xxxx]: 

# コミットメッセージ例文)
# - Fix typo in docs
...(省略)

globalのconfig設定(コマンド)

ユーザー名とメールアドレスを設定

$ git config --global user.name "sample"
$ git config --global user.email "sample@sample.com"

デフォルトのブランチ名を設定

$ git config --global init.defaultBranch main

デフォルトブランチ名がmasterのままだとgit init時に下記のようなメッセージが出てくるかと思います。ここにコマンドが書かれているのでここからコピペするでもOKです。

$ git init
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint: 
hint:   git config --global init.defaultBranch <name>
hint: 
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint: 
hint:   git branch -m <name>
Initialized empty Git repository in /Users/onea/test/.git/

デフォルトのコミットメッセージを設定

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

コマンドのエイリアスを設定

$ git config --global alias.ci commit
$ git config --global alias.st status
$ git config --global alias.br branch
$ git config --global alias.co checkout

おまけ:~/.gitconfigファイルをエディタで編集する

$ git config --global --edit

~/.gitconfigをシンボリックリンクにしていても、きちんと元のファイルが更新されます。

Discussion