---
title: Linux 核心設計 / Git基本功能教學
description:
tags: Linux Kernal
---
# Git基本功能教學
主要內容節錄至 YouTube頻道-李祐棠:
[Git中文教學](https://www.youtube.com/watch?v=LZ4oOzZwgrk&list=PLlyOkSAh6TwcvJQ1UtvkSwhZWCaM_S07d&index=1)
## 1. 安裝與設定
### Git useful tool 圖形介面程式
1. Linux : gitk(built-in)
2. MacOS : gitx
### Start a Project
* Simple
* `git init`
* `git add <file>`
* `git commit`
* Setup user name and email
* `git config user.name`
* `git config user.email`
---
* Setup editer
* `git config core.editor vim`
* Setup merge tool
* `git config merge.tool vimdiff`
* Setup alias (快捷名稱設定)
* `git config alias.xxx yyy`
* Setup color
* `git config color.ui true`
補充:`git config --global` 可以一次性更改所有 git 設定。
---
## 2. Add and Commit


而 `git commit` 是把 staged 的東西移到 commit 資料庫內。
* **`git commit -a`** 將 `git commit` + `git add` 兩個動作一次完成。
* See your repository status by `git status`
* git add
* `git add -p` 分別檢視與是否加入**每一個改變**,這就是 patch add 。
* git commit
* 50/72 rule
* As detailed as possible
### 常用指令:
* 查看狀態
```
$ git status
```

* Changed to be committed:
>已經透過 `git add` 把需要加入的修改項目,添加到下一次的 Commit (等待發送的)當中。
* Changes not staged for commit:
>代表 GitHub 上面有這個檔案,但是還在 Commit 中(還沒更新到 Git 上面的意思)。
* Untracked files:
>代表 GitHub 上面還沒有這個檔案。
* 加入想要 Commit 的修改項目
* 全部修改皆加入
```
$ git add
```
* 逐一審查要加入的修改
```
$ git add -p
```
* log 查看版本紀錄
```
$ git log
```
* ignore (不要出現在 status 的方法)
1. 產生一個 `gitignore` ,裡面
```
$ vim .gitignore
```
>在欲加入 `gitignore` 的檔案,加上 `/` 後為現在這個資料夾下的那個檔案
>```
>/檔名
>```
2. 將新建的 `gitignore` 檔案加入 Commit 中
```
$ git add .gitignore
```
如果要取消加入
```
$ git reset HEAD .gitignore
```
[該 ignore 什麼的參考資料](https://github.com/github/gitignore)
[Git:--local-branching-on-the-cheap](https://git-scm.com/book/en/v2)
### 重要守則
1. 不要留下個人機密資料(因為幾乎刪不掉)
2. 不要放上非必要的大檔案
3. Generated files(產生的檔案,例如執行檔)
### 50/72法則
在 Commit 中,遵從標題,內文72字的規則,標題清楚標,細節在內文。會有字數限制是因為,在終端機用 `$ git log` 閱讀 Commit 時,這樣可以一行看完,而不會有些 Commit 標題一行,有些兩行。
>標題在超過字數(50字)後,文字會變成白色提醒使用者。
撰寫 Commit 建議須包含以下:
1. 議題編號: `Relate Issue: Issue #159`
2. 問題敘述: `The Problem:`
3. 原因解釋: `The Cause:`
4. 解決方式: `The fix:`
:::spoiler 建議範本
```commit
Relate Issue:
Issue #159
The Problem:
The following source code will create wrong branch arrow.
var graph1 = new GitGraph({
elementId: 'badGraph',
mode: 'compact',
template: 'blackarrow'
});
var m1 = graph1.branch("master");
m1.commit();
var r1 = m1.branch('1.0.x');
m1.commit();
r1.commit();
The arrow pointed to r1 commit will pointed from second commit of m1
not follow the line from first commit of m1.
The Cause:
When create a commit, if user does not specify parent commit in options
gitgraph.js will execute following code:
options.parentCommit = options.parentCommit || _getParentCommitFromBranch(this);
to determine the parent commit of the created commit.
In the function _getParentCommitFromBranch, it will try to get the last
commit from current branch, then from parent branch. Since r1.commit()
is the first commit in its branch 1.0.x, it will set its parent commit
to last commit of its parent branch, that is master. And since master
already add some new commit, the arrow will point from wrong commit, the
last commit of master branch.
There is code that deal with branch case:
if (options.parentCommit instanceof Commit === false && this.parentBranch instanceof Branch) {
options.parentCommit = this.parentCommit;
}
It set parentCommit to the correct commit. However, since
options.parentCommit already been set by previous code, this code will
never execute since options.parentCommit is always a Commit.
The fix:
The fix is combining two scenario. If current branch already has commits,
the parentCommit will be set to last commit in this branch. Otherwise,
it will set to parent commit of this branch, which will be the correct commit
instead of last commit of parent branch.
```
[參考資料:fix wrong arrow angle on branching #171](https://github.com/nicoespeon/gitgraph.js/pull/171)
:::
### 偉大 Git commit message 的七條規則
1. 用一行空白行分隔標題與內容
2. 限制標題最多只有 50 字元
3. 標題開頭要大寫
4. 標題不以句點結尾
5. 以祈使句撰寫標題
6. 內文每行最多 72 字
7. 用內文解釋 what 以及 why vs. how
## 3. Indicate a Commit
Hash Value: 指定是哪個Commit。
* `-(n)` :只顯示最後 n 筆提交。
```
$ git log -n1
```
* `HEAD` 、`master` 目前的commit。
```
$ git log -n1 HEAD
```
```
$ git log master
```
* `^` 看目前 Commit 的舊一個。
* `--oneline` 只顯示一行。
* `$ git log --oneline load.cpp` : 只顯示與 `load.cpp` 有關的 Commit。
* `Git log <path>|<commit>`
* -n : limit number
* __oneline : view hash and commit summary
* --stat : view files change
* --patch : view lines change
* -S or --grep : find modification
---
* `diff` :顯示改了什麼( Commit 與未加入 Commit 的不同)。
>
```
$ git diff
```
##### 參考資料:
[Git 基礎 - 檢視提交的歷史記錄](https://git-scm.com/book/zh-tw/v2/Git-基礎-檢視提交的歷史記錄)
## 4. Patch Add and Amend
* Git add -p
* My experience: always use this
* this hunk from worktree [y,n,q,a,d,/,j,J,g,s,e,?]?
* s: seperate all change parts
* e: edit
Modify Commit
1. Use git commit -- amend
a. Check before doing this
2. Use reset HEAD^ then re-commit

## 5. Branch and Merge
### Move and Create Branch
* Checkout: move HEAD
* `git checkout <commit>` Move to HEAD
* `git checkout <path>` WARNING: discard change
* Branch:
* `git branch` List branch
* `git branch <name>` Create branch
* Or just: `git checkout -b`
* 綜合開新的Branch和移動HEAD到新增的Branch
* `git checkout -b <name>`
### View Branch
* `git branch`
* `git log ru8 加下面`
* --decorate (看 reference 用的,若無效輸入下面那行)
* config log.decorate auto
* --graph
### Delete Branch
* `git branch -d <name>`
* `git branch -D <name>` for no-merge commit
* WARNING: Discard Commit
### Merge
* `git merge <branch>`
* Usually mainline merge other
* `git checkout master`
* `git merge <branch>`
### Resolve Conflict
* Manually resole
* Check evert codes between `<<<<<<`, `>>>>>>`
* Edit code to what it should be
* Use `git mergetool` (圖形化介面,展示哪裡不同) like vimdiff
* It shows: local, base, remote, file to be edited
* Edit "file to be edited" to what is should be
* Add and commit

上圖的意思:
`<<<<<<`
未修改的版本
`======`
新改的地方
`>>>>>>`
去對照後,手動改成最新版的,再 commit 。
### Reference
* https://git-scm.com/book/en/v2
* 3.1 Branches in a Nutshell
* 3.2 Basic Branching and Merging
* https://yodalee.blogspot.com/2013/03/vimdiffgit-merge-conflict_28.html
## 6. Rebase
### Rebase: Why and What
* Move your branch to another place
* Clean up your DAG (Directed Acyclic Graph) / Edit commits
* Main branch has updated, rebase feature branch to new master

### What Rebase Do
1. Checkout the new-base
2. Re-apply commits

### Rebase: How
* Rebase <new_base>
* Rebase current branch to <new_base>
* Start from `git merge-base HEAD <new-base>`
* `rebase --onto <new base><ref_commit><branch>`
* Rebase from common ancestor of `<ref_commit>` and `<branch>`
Example:
* `git rebase --onto master A dev`
* Notice the Hash Value

### Rebase: Conflict
* Rebase stop if conflict
* A little different to merge case: just add the final result
* `git rebase --continue` until end
* `git rebase --abort` if out of control
### Rebase -i
* Change content (edit)
* Change message (reword): 修改 Commit message
* Change order: 直接在介面裡面換順序就好
* Remove commit (drop)
* Combine commit (squash, fixup)
* Split (edit->reset)
* Run command (exec)
### Some Tips
* Rebase can do fast-forward if new base is child of current branch
* Just forward reference
### Thing to Notice
* Rebase is re-commit, it changes histoy
* ==Do not rebase on published commits==
* Prevent rebase across branch base
* Suggest making a ==backup before rebase==
### Reference
* https://git-scm.com/book/en/v2
* 3.6 Rebasing
* https://blog.yorkxin.org/posts/git-rebase/
## 7. Remote and Github
### Clone and Remote
* `git clone`
* Default remote name is origin
* Remote:
* `git remote show <origin>`: list detail
* `git remote add <name>`URL: add remote
* `git remote rename <a><b>`: rename
### Remote is Reference
* Remote branch is named by: `<remote>/<branch>`
* Show hidden branch by `branch -a`
### Update Status
* fetch remote
* `git fetch <name>`
* Rebase local branch to remote state
Or
* Just `pull`(=fetch + rebase)
### Push
* `git push <remote><branch>`: `<branch>`
* `--set-upstream`
* `git push <remote>`: `<branch>` delete remote branch
### basic Workflow
* Fork on Github, clone your repository as `<origin>`
* Add `<upstream>`
* Develop on mew branch
* Push branch to `<origin>`, open Pull Request
* After merge, fetch `<upstream>` and rebase master
### Reference
* https://git-scm.com/book/en/v2
* 2.1 Getting a Git Repository
* 5.2 Contributing to a Project
* http://yodalee.blogspot.tw/2014/05/pull-requestgithub.html
## 8. Stash
### Why Stash
* Temporarily store your work not enough for commit
### Usage
* `git stash`: store stash content
* `git stash list`: show stored content
* Use `stash@{n}` to indicate stash
* `git stash pop`: pop top
* `git stash drop`: drop stash WARNING
### Reference
* https://git-scm.com/book/en/v2
* 7.3 Stashing and Cleaning
* http://yodalee.blogspot.tw/2013/12/git-stash.html
## 9. Patch and Cherry-Pick
### Generate Patch
* `git format-patch <base_commit>`
* `git format-patch -n3 <top_commit>`
Or
* `git diff > name.patch`
### Apply Patch (貼上去)
* `git apply <patch>`: apply patch
* `git apply --check`: check no conflict
* Commit after apply
* `git am`: apply and commit
* `git am *.patch` is very useful
### Patch Conflict
* `git apply --reject <patch>`
* Patched failed stored in file.rej
* Manual resolve the conflict, then `git am --continue`
### cherry-pick
* `git cherry-pick <commit>`
* Resolve conflict like rebase, just ass then `git cherry-pick -- continue`
### Reference
* https://git-scm.com/book/en/v2
* 5.3 Maintaining a Project
* http://yodalee.blogspot.tw/2017/03/git-patch.html
## 10. Bisect and Blame
### Serch for Modification
* `git blame -L <start>,<end> <file>`
* `git blame -L`: `<function> <file>`
### Bisect
Find where program failed
1. `git bisect start`
2. `git bisect good <commit>`
3. `git bisect bad <commit>` ... Do binary search, mark good, bad...
Or
* Just `git bisect run <shell>`
### Refernece
* https://git-scm.com/book/en/v2
* 7.10 Debugging with Git
* http://yodalee.blogspot.tw/2014/08/git-bisect.html
## 11. Ending
### Not Mention
* Open your own derver
* Manage branch on local or server
* Use git with SVN server
* Submodule
* Tag
* Save deleted data
* Modify history