Git

Set up

Install

sudo yum install git-all
sudo apt-get install git-all

Repository

建立server上的bare repository

git init --bare <name>.git

Config

git config --(global|system|local) <options>

Global

  • Windows
C:\Users\name\.gitconfig
  • Linux
~/.gitconfig

System

  • Windows
C:\Program Files\Git\mingw64\etc

如果有安裝類linux輔助,則會其目錄下的/etc內

  • Linux
/etc/.gitconfig

Local

位在repository當前.git/config

Options

項目 option
使用者名稱 user.name
信箱 user.email

RSA key

  1. 跟著Github官方的教學文件
Trouble shoot
host key verification failed

通常是known_hosts的問題,執行以下動作來覆蓋內容修正:

ssh-keyscan -t rsa github.com > ~/.ssh/known_hosts

Commands

Checkout

根據tag建立branch

git checkout -b <branch> <tag>

Bisect

主要用於檢查是哪個commit開始造成程式錯誤。

  1. 指定壞掉的點
git bisect start HEAD <SHA1/Tag>

指定好後,會直接二元方式切換到另一個commit。

  1. 指定當前commit是好或壞
git bisect bad/good
  1. 返回bisect前狀態
git bisect reset

Clone

下載一個repository

git clone <repository url>

如果是.git結尾的url則必須要給定server端的絕對路徑

下載特定目錄

新Repository
  1. 建立資料夾
mkdir <folder name>
  1. 進入資料夾
cd <folder name>
  1. 初始化git
git init
  1. 加入remote
git remote add –f <remote name> <url>
  1. 開啟sparse checkout功能
git config core.sparsecheckout true</code>
  1. 設定想要抓取的目錄
echo <path of folder> >> .git/info/sparse-checkout</code>
  1. 執行pull抓取
git pull <remote name> master</code>

現有Repository

  1. 開啟sparse checkout功能
git config core.sparsecheckout true
  1. info內加入想要抓取的目錄
echo <path of folder> >> .git/info/sparse-checkout
  1. 執行read-tree更新git並抓取
git read-tree -mu HEAD
過濾不必要的檔案或目錄
  • 目錄
!<folder path>
  • 檔案
!*<file name or type> 

參考

Fetch

單取一個PR

git fetch {remote} pull/{ID}/head:{from BRANCHNAME}

Log

從訊息找對應字串的commit

git log --grep="<string>"

從內容找有對應字串的commit

git log -S "<string>"

Merge

不自動產生commit

git merge <branch name> --no-commit

Push

強制更新

git push -f <remote branch> <local branch>

強制返回remote至某一commit

git reset --hard <commit>
git push -f <remote branch> <local branch>

Stash

自訂訊息

git stash save <message>

查看所有stash

git stash list

取用特定的stash

git stash apply stash@{<index>}

需要搭配git stash list

Worktree

主要用於多個feature同時進行,但想簡化工作流程而不用互相干擾時。

  1. 開啟新的worktree
git worktree add -b <branch> ../hotfix <upstream>

執行後會以目前狀態建立新的資料夾../hotfix,建立並切換branch至<branch>,遠端是追蹤<upstream>

  1. 查看worktree列表
git worktree list
  1. 刪除worktree
直接rm -rf刪除目錄, 或
git worktree prune 清除記錄

Submodule

  1. 加入submodule
git submodule add <repository> <path>

目錄底下會出現.gitmodules

  1. 打開.gitmodules 確認 path 及 repository
// In .gitmodules
[submodule "user_guide"]
path = your/path
url = xxx/xxx/xxx/repository.git
  1. 設定結束,Push

Useful

顯示執行過程

<git command> --progress

Clone有submodule的repository

  1. clone後執行init,讓git知道有submodule
git submodule init
  1. 取得submodule
git submodule update

查看所有被track的檔案

git ls-tree -r master --name-only

刪除track的檔案

git rm -r --cached <file>