git メモ

git コマンドメモまとめ

全てブランチ一覧

git branch -a

ローカルブランチ一覧

git branch
git graph

リモートブランチをローカルに落とす

git pull origin (branch_name)

リモートブランチをローカルに落とす(結果的にはgit pullと同じ)

git fetch origin (branch_name)
※特殊の設定がなければ、origin (branch_name)を省略すると全てリモートブランチをフェッチとなります。できれば「git fetch --all」を使用します。
git merge origin/(branch_name)

ワークスペースの編集確認

git status

変更したソースの確認(ワークスペースとインデックス間の差分)

git diff

ワークスペースの変更を取消

git checkout (filename)

ワークスペースの変更を全て取消

git checkout .

no track 追跡されていないファイル削除

削除される一覧ファイル表示
git clean -n (git clean -n ./)

削除する
git clean -f (git clean -f ./)

※git clean -dn,git clean -df 同じ効果

※危険※変更を完全クリア、新規追加ディレクトリとファイルも。。。慎重に

git clean -df

ステージング領域にコミットしたいファイル追加

git add .
git add (filename)

変更したソースの確認(インデックスとローカルリモート追跡リポジトリ間の差分)

git diff --cached

addを取り消したい

git reset --mixed HEAD

addを全て取り消したい

git reset HEAD
git reset HEAD .
git reset --hard

コミット

git commit -m "xxxxxx"
git commit ファイル名

add、commit一緒に実行

git add .
git commit -m "info"
↓
git commit -am "info"

変更したソースの確認(ローカルリポジトリとローカルリモート追跡リポジトリ間の差分)

git diff (branch_name) origin/(branch_name)

コミットを取消

コミット後の変更を全部消したい

git reset --hard HEAD^
git reset --hard origin/(branch_name)

直前のコミットをなかった事にする

git reset --hard HEAD^
  • --hard:「HEADの位置・インデックス・ワーキングツリー」全て
  • --mixed(or オプション無し):「HEADの位置・インデックス」
  • --soft:「HEADの位置」のみ

リモートにプッシュ

git push origin (branch_name)

pushを取消

git revert (commitのハッシュ値)
git push

新規ブランチ作成(なければ新規作成)してチェックアウト

git fetch (or git pull)
git checkout -b (branch_name) origin/(branch_name)

ブランチ作成

git branch (branch_name)

ブランチ削除

git branch -d (branch_name)

ブランチマージ

(ローカル)ブランチAにいる時、(ローカル)ブランチBをマージ

git merge ブランチB

(ローカル)ブランチAにいる時、ローカルリモート追跡ブランチCをマージ

git merge origin/ブランチB

ポイント

  • origin/masterとorigin masterの違い
  • origin/masterとスラッシュが付く場合、ローカルのrefs領域を指します。
  • origin masterとスペースが付く場合、サーバーを指します。
  • ここもつまづきポイント。pushする場合、ローカルに向けないと思うのでスペースと覚えると間違いないと思います。

GitHub上でリモートリポジトリをpull

git remote add origin (url)
git pull origin (branchname)

新しいリモートリポジトリをclone

git clone (ssh url) (ディレクトパス:省略でカレントパスとなる)[git@gitlab.xxxxxx.jp:xxxx/xxxx_server.git]

cloneしたローカルレポジトリ削除

rm -rf (レポジトリ名)
※普通にディレクトフォルダ削除だけ

リモートにあるブランチをローカルに新規チェックアウト

git checkout -b (branchname)

ローカルに新しいブランチ作成

git checkout -b (ローカルに作成するブランチ名) origin/(作成元のリモートのブランチ名)

ローカルで作成したブランチをリモートに登録

git push -u origin (作成したブランチ名)

削除されたremoteブランチがローカルのRepoに残っていて、それを削除する方法

  • remoteブランチを単純参照
    git remote show origin

  • remoteブランチでは削除されているが、ローカルに参照が残っているブランチを表示
    git remote prune --dry-run origin

  • ●これを実行● すでに削除されているremoteブランチのローカル参照を削除してきれいにする
    git remote prune origin

過去特定のコミットまで戻したい

git log //戻す対象のハッシュ値を調べる
commit ************************

git reset --hard (ハッシュ値)

一時的に別のコミットに切り替える

git log //戻す対象のハッシュ値を調べる
commit ************************

git checkout (ハッシュ値)

tag一覧表示

git tag
git tag -n //コメント付き

現在のコミットにタグを追加する

git tag (tag_name)

現在のコミットに注釈付きタグを追加する

git tag -am "(タグのコメント)" (tag_name)

タグ情報を含めて履歴を表示する

git log --decorate

タグを削除する

git tag -d (tag_name)

revert(過去に公開したコミットの打ち消すコミットを作成する)

git revert HEAD //直前のコミットを打ち消すコミットができる
→revert エディタ開かれる
→commitメッセージを入力して保存するで完了
→変更をpush
git revert (commitのハッシュ値) //特定のコミットを取り消す
git revert (commitのハッシュ値) -e // コミットメッセージ編集
git revert (commitのハッシュ値) --no-edit // コミットメッセージを編集しない(エディタを開かない)
git revert (commitのハッシュ値) -n (indexに戻すだけでコミットまではしない。※複数のコミットをrevertするときに、一度にコミットすることができる場合使用)
●git revert -m 1 (commitのハッシュ値) //マージコミットをrevert時、どちらの親を選択する必要があり
●git show //で親の数字を確認
$ git show
commit xyz
Merge: 1a1a1a 2b2b2b    #1a1a1aは1,2b2b2bは2※左から表示順番
Author: xxxx xxxx
Date:   Thu Jul 13 09:00:00 2017 +0000
    Merge commit
※消したいコミットを指定することです。

reset(コミットを捨てる)

  • モード名 HEADの位置 インデックス ワークツリー
  • soft 変更する 変更しない 変更しない
  • mixed 変更する 変更する 変更しない
  • hard 変更する 変更する 変更する
    git reset --hard HEAD~~ //直近二つコミット削除
    ※消したいコミットの一つ前のコミットを指定することです。
    ※例:commit1,commit2,commit3,commit4(HEAD)でcommit2を消したい場合は「git reset --hard HEAD~~~」或いは「git reset --hard (commit1のハッシュ値)」

    reset前のコミットはORIG_HEADという名前で参照することができます。

    間違えてresetしたなどの場合は、ORIG_HEADにresetするとreset前の状態に戻すことができます。

    git reset --hard ORIG_HEAD

rebase -i(コミットの履歴を書き換える)

主な利用シーン

  • pushする前にコミットコメントをきれいに書きなおす
  • 意味的に同じ内容のコミットをわかりやすいように一つにまとめる
  • コミット漏れしたファイルを後から追加する
    git rebase -i HEAD~~

commit --amend(直前のコミットを修正するとファイル追加する)

git commit --amend
//コメント修正エディタが開かれる

//ファイルだけ直前のコミットに追加
git add (add_filename)
git commit --amend --no-edit

ローカルブランチで編集途中他のローカルブランチにcheckoutする前に現在の変更内容をstashに保存する

  • 作業を退避する
    
    退避した作業一覧を確認する
    git stash list

指定の退避内容を削除する(drop)
git stash drop

退避内容を全削除する(clear)
git stash clear

作業を退避する
git stash apply ※引数無ければ一番新しい作業を指定
git stash apply

作業を戻す
git stash pop ※引数無ければ一番新しい作業を指定
git stash pop stash@{1} ※「stash@{1}」は例

git stash save "test_stash" # 名前を付けて作業を保存


## 「git checkout origin/(branchname)」ロカールリモート追跡ブランチにチェックアウトしたらどうなる

coming soon...


## ブランチ構造確認

[root@asus test]# cd .git/
[root@asus .git]# tree refs/
refs/
├── heads
│   ├── dev_c8
│   └── master
├── remotes
│   └── origin
│   ├── HEAD
│   └── dev_c8
└── tags

4 directories, 4 fi


## ローカルリモート追跡ブランチ確認

[root@asus test]# git remote -v
origin git@github.com:cstang/test.git (fetch)
origin git@github.com:cstang/test.git (push)
[root@asus test]#


## ローカルブランチとローカルリモート追跡ブランチの紐づけ確認
### git pullでローカルブランチとローカルリモート追跡ブランチの紐づけできていないメッセージが表示される

[root@asus test]# git checkout dev_c8
Switched to branch 'dev_c8'
[root@asus test]# git pull
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

git branch --set-upstream-to=origin/<branch> dev_c8

[root@asus test]# git branch -vv

  • dev_c8 de3aa7e add file
    dev_st de3aa7e [origin/dev_st] add file
    master de3aa7e [origin/master] add file
    [root@asus test]# git branch --set-upstream-to=origin/dev_c8 dev_c8
    Branch 'dev_c8' set up to track remote branch 'dev_c8' from 'origin'.
    [root@asus test]# git branch -vv
  • dev_c8 de3aa7e [origin/dev_c8] add file
    dev_st de3aa7e [origin/dev_st] add file
    master de3aa7e [origin/master] add file
    [root@asus test]# git status
    On branch dev_c8
    Your branch is up to date with 'origin/dev_c8'.

nothing to commit, working tree clean
[root@asus test]# git pull
Already up to date.
[root@asus test]#


## 「touch .gitignore」が効かない時、gitのキャッシュファイルをすべて削除

git rm -r --cached .


## centos8 git install

[root@asus ~]# dnf install git-all
省略


## gitバージョン確認

[root@asus ~]# git --version
git version 2.18.4


## gitの初期設定
 - system /etc/gitconfig
 - global ~/.gitconfig
 - local repository/.git/config
### 確認用コマンド

git config --global -l --show-origin
git config --get core.filemode
git config core.filemode
git config --list
git config --l

### グローバ
#### 必須(global or system)

git config --global user.name "cstang"
git config --global user.email "tangyin@yahoo.co.jp"

git config --global core.autocrl false
git config --global core.filemode false

#### 必須でない

git config --global color.ui auto
// Visual Studio Code
git config --global core.editor 'code --wait'
git config --global sequence.editor 'code --wait'


### プロジェクトの設定ファイル開く

vim /etc/gitweb.conf
vim .git/config
vim ~/.gitconfig


## sourcetree
### windows10のsourcetreeでgithubからリポジトリをclone

#### (cmd)コマンドプロンプトでSSH鍵生成

C:\Users\tangyin>ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (C:\Users\tangyin/.ssh/id_rsa):
Created directory 'C:\Users\tangyin/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\tangyin/.ssh/id_rsa.
Your public key has been saved in C:\Users\tangyin/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:GzzgCMAJTQybwCsDgJkUMS55muH6Fio2YnrZkFqnf3c tangyin@DESKTOP-4NHSUN2
The key's randomart image is:
+---[RSA 2048]----+
|&%= |
|BO+ |
|B.+ . |
|=* . o o |
|+o .. . S |
|. = . + |
|.+ B . |
|=== . . . E |
|Boo... . . |
+----[SHA256]-----+
C:\Users\tangyin>


#### C:\Users\tangyin/.ssh/id_rsa.pub の内容をgithubに登録

#### sourcetreeの「SSHクライアントの設定」を行う
- SSHキーを「C:\Users\tangyin/.ssh/id_rsa.pub」(デフォルトのまま)に設定
- SSHクライアントを「OpenSSH」

#### githubからクーロンできる

## その他

### 記号
- ~ (チルダ):~世代前のコミットを指定できる。
- ^ (キャレット):複数ある親コミットのなかからコミットを指定できる。(HEAD^1はマージ前の親1,HEAD^2はマージ前の親2)
#### HEAD~~ = HEAD~2、HEAD~~ = HEAD^^ != HEAD^2
#### 例:

・一つ前のコミットをみたいとき
git show HEAD^
git show HEAD~
・三つ前のコミットをみたいとき
$ git show HEAD^^^
$ git show HEAD~3
$ git show HEAD~~~
※ $ git show HEAD^3は違う
gitのv1.8.5からは大文字「HEAD」の4文字を打たなくて済むよう「@」というエイリアスが用意されたので以下のようにも書くことができます。
$ git show @^^^
$ git show @~3
$ git show @~~~


### .gitフォルダ構造
- HEAD:現在のブランチの参照
- branches: git fetch、git pull、およびgit pushのURLを省略形を指定するために使用される、廃止予定
- config: リポジトリのGit設定、git configで設定するメールなど
- description: GitWeb(gitのデフォルトのWebUI)で使われる
- hooks: Gitの各コマンドを実行した時に呼び出されるスクリプトを設定できる(e.g. pre-commitならgit commitの前)
- info: このリポジトリに対する追加情報
 - exclude: .gitignoreのようなもの
- objects:Gitの実体(オブジェクト)が保存される場所
 - info: オブジェクトに対する追加情報
 - pack: ランダムアクセスするためのインデックスファイルや、多数のオブジェクトを圧縮したファイル
- refs: Gitの各参照先が保存されている場所
 - heads: 参照先のブランチ(実体はコミットオブジェクト)
 - tags: 参照先のタグ名(実体はコミットオブジェクト)

### コマンドラインとsourcetreeの違い:
- git clone ssh ->プロジェクト名のフォルダ作成してくれる
- clone ->プロジェクト名のフォルダ作成してくれない

### gitlabのバージョンが古い場合(GitLab Community Edition 9.1.1 d3123f6)は
### sourcetreeとgitkraken等GUIを使用しないでコマンドライン操作のほうが無難。

- gitkrakenは商用でないとプライベートリポジトリ対応できなくなったため、会社では使用しない。※古いバージョンで使える可能性があり
- sourcetreeはコミット内容が表示されないなど不具合が発生しています、バージョンダウンでも色々不具合があるためあきらめる。※もっと古いバージョンで使える可能性があり

## 例:ローカルdevelop_tangブランチをリモートdevelopブランチにマージ

git checkout develop_tang
git status

git add .
git commit -m "xxxxxx"
git push origin develop_tang

git checkout develop
git pull
git status
git merge develop_tang
git push origin develop


## 例:コンフリクト対応例
- 現状:dev_stブランチに「test1.txt」ファイルがあります
- (windows)sourcetreeで「test2.txt」を追加、「test1.txt」に内容を追加
- (centos8)commandlineで「test3.txt」を追加、「test1.txt」に内容を追加
- (centos8)commandlineでコンフリクトを確認
### ※省略※(windows)sourcetreeで「test2.txt」を追加、「test1.txt」に内容を追加
### (centos8)commandlineで「test3.txt」を追加、「test1.txt」に内容を追加

[root@asus test]# vi test1.txt
[root@asus test]# touch test3.txt
[root@asus test]# echo "aaa" > test1.txt

### dev_stブランチ編集後の状態確認

[root@asus test]# git status
On branch dev_st
Your branch is up to date with 'origin/dev_st'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)

    modified:   test1.txt

Untracked files:
(use "git add <file>..." to include in what will be committed)

    test3.txt

no changes added to commit (use "git add" and/or "git commit -a")

### リモートdev_stブランチをロカールリモートdev_st追跡ブランチを反映してロカールdev_stブランチにマージ

[root@asus test]# git fetch origin dev_st
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (2/2), done.
Unpacking objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0
From github.com:cstang/test

  • branch dev_st -> FETCH_HEAD
    de3aa7e..cef9b83 dev_st -> origin/dev_st
    [root@asus test]# git merge origin/dev_st
    Updating de3aa7e..cef9b83
    error: Your local changes to the following files would be overwritten by merge:
    test1.txt
    Please commit your changes or stash them before you merge.
    Aborting

    ### マージでエラーが発生している、「先にローカルブランチの編集をコミットしてください」と怒られたで、ローカルブランチの編集をコミット

    [root@asus test]# git add .
    [root@asus test]# git commit -m "20200730_cm_1"
    [dev_st 7873074] 20200730_cm_1
    2 files changed, 1 insertion(+)
    create mode 100644 test3.txt
    [root@asus test]# git merge origin/dev_st
    Auto-merging test1.txt
    CONFLICT (content): Merge conflict in test1.txt
    Automatic merge failed; fix conflicts and then commit the result.

    ### 「マージ完了したが、コンフリクト発生して解決が必要」との意味。
    ### 現状確認:
    - (windows)sourcetreeで追加した「test2.txt」->コンフリクト無しで正常にマージできた
    - (centos8)commandlineで追加した「test3.txt」->コンフリクト無しで正常にマージできた
    - 編集した「test1.txt」->コンフリクトが発生してます

    [root@asus test]# git status
    On branch dev_st
    Your branch and 'origin/dev_st' have diverged,
    and have 1 and 1 different commits each, respectively.
    (use "git pull" to merge the remote branch into yours)
    You have unmerged paths.
    (fix conflicts and run "git commit")
    (use "git merge --abort" to abort the merge)
    Changes to be committed:

    new file:   test2.txt

    Unmerged paths:
    (use "git add <file>..." to mark resolution)

    both modified:   test1.txt
    ### 試しにコミットしたら「コンフリクト解決しないとコミットできない」と怒られた

    [root@asus test]# git commit
    U test1.txt
    error: Committing is not possible because you have unmerged files.
    hint: Fix them up in the work tree, and then use 'git add/rm <file>'
    hint: as appropriate to mark resolution and make a commit.
    fatal: Exiting because of an unresolved conflict.

    ### 「test1.txt」の内容を直接編集して保存したら再度コミット、プッシュ

    [root@asus test]# git add test1.txt
    [root@asus test]# git commit -m "コンフリクト対応済"
    [dev_st 2652bd3] コンフリクト対応済
    [root@asus test]# git status
    On branch dev_st
    Your branch is ahead of 'origin/dev_st' by 2 commits.
    (use "git push" to publish your local commits)
    nothing to commit, working tree clean
    [root@asus test]# git push origin dev_st
    Enumerating objects: 10, done.
    Counting objects: 100% (10/10), done.
    Delta compression using up to 2 threads.
    Compressing objects: 100% (4/4), done.
    Writing objects: 100% (6/6), 639 bytes | 127.00 KiB/s, done.
    Total 6 (delta 0), reused 0 (delta 0)
    To github.com:cstang/test.git
    cef9b83..2652bd3 dev_st -> dev_st
    [root@asus test]#

    
    ### これでコンフリクトの解決ができました