contributed by <asahsieh>

Table of Content

References

Git Command Quick Reference

  • Undo Git previous one(^) operation
    $git reset HEAD^ --hard
  • Get reference menu of the command
    $git $command -help
  • Show the remote URL
    $git remote show <origin>: list detail, include URL of the repo

Cloning a repository

Cloning a repository

  • Type git clone, and then paste the URL of the repo.
    ​$ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
    

Configuration

  • git config global user.email "kchs.tw@gmail.com"
  • git config global user.name "ASaHsieh"
  • git config global core.editor vim
  • git config global merge.tool vimdiff
  • git config global alias.st status
  • git config global color.ui true
  • git config global init.defaultBranch <name> // for doing $git init locally

Caching credentials

To remember your credentials

I chose a method which has less limitation: Git's built-in credential cache

The credential cache

git-diff

Commands

  • Progress to next change
    Press space

Add and Commit

  • git add -p
    一個檔案有很多修改時,為了讓每次commit都是獨立的功能;patch -p 可以讓user各別標記這次要commit的部份。

  • git commit [-p]

    • 50/72 rule
      第一行50個字以內,空一行;加上描述且每一行72個字以內。
      對齊term寬度,減少換行。

      利用 VIM 會利用“文字變色”來提醒

log

git log filter by author

Find what file changed in a commit

  • git log --raw

  • show source with diff
    git show --source

How to use the git log graph command example

Branch and Merge

Branch

  • A label is attached to a commit as a branch

Move and Create a Branch

$ git checkout -b cload
  • Checkout: move to HEAD
  • 相當於下面這兩條命令:
$ git branch cload
$ git checkout cload

Remote branch

  • Tracking Branches
$ git fetch origin
$ git checkout -b serverfix origin/serverfix 

or

$ git checkout --track origin/serverfix

Merge

  • Use --no-ff (no fast-forwarding) to keep commits from merged branch

Further study on git-scm: 3.2 Git Branching - Basic Branching and Merging

  • It’s best to have a clean working state when you switch branches. There are ways to get around this (namely, stashing and commit amending) that we’ll cover later on, in Stashing and Cleaning.

  • A hotfix to make

    • Let’s create a hotfix branch on which to work until it’s completed:
      ​​​​$ git checkout -b hotfix
      ​​​​Switched to a new branch 'hotfix'
      ​​​​$ vim index.html
      ​​​​$ git commit -a -m 'Fix broken email address'
      ​​​​[hotfix 1fb7853] Fix broken email address
      ​​​​ 1 file changed, 2 insertions(+)
      
    • You’ll notice the phrase “fast-forward” in that merge.
      To phrase that another way, when you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together — this is called a “fast-forward.” > 不做合併並以之前最後一個commit的history當作commit的comment, 只將branch pointer移至要被merge的commit上。
  • Basic Merging

    • Merge a diverged development history branch which from some older point
      Because the commit on the branch you’re on isn’t a direct ancestor of the branch you’re merging in, Git has to do some work. In this case, Git does a simple three-way merge, using the two snapshots pointed to by the branch tips and the common ancestor of the two.
      Figure 24. Three snapshots used in a typical merge

Merge multiple commits onto another branch

https://stackoverflow.com/questions/5308816/how-can-i-merge-multiple-commits-onto-another-branch-as-a-single-squashed-commit

git merge --squash bugfix

git merge --squash does it all on the command line in one shot and you just hope it works. git rebase -i brings up an editor and lets you fine-tune the rebase. It's slower, but you can see what you're doing.

Rebase

Why and What

  • Move your branch to another place
  • Clean up your DAG/Edit commits

How

  • Rebase <new_base>
    • Rebase current branch to <new_base>
  • Rebase --onto <new base> <ref_commit> <branch>

Conflict

  • Rebase stops if there has conflict:
  • Commands to be excuted after merging
    • $ Rebase --continue until end
    • $ Rebase --abort if out of control

Rebase commands

  • git rebase -i <the-commit-to-be-based-on>

    • -i: interactive
  • Edit rebase todo file and save:

    • example:
  • operations you can make:

    • Correct the author information and then continue to the next concerned commit
      ​​​​$ git commit --amend --author="John Doe <john@doe.org>" --no-edit
      ​​​​$ git rebase --continue
      
    • :notes: add tbm on front of message to show the commit is just fixing a bug, it's to-be-merged.

Things to Notice

  • Rebase is re-commit, it changes history
    • Do not rebase on published commits
  • Prevent rebase across branch base
    • Example:
  • Suggest making a backup branch (e.g., bk) on the branch to do rebase, before doing rebase.

while rebasing

When do 3-ways merging

Remote and Github

Clone and Remote

Default remote name is origin

  • shows you the URLs that Git has stored for the shortname to be used when reading and writing to that remote:
    ​​$ git remote -v
    ​​origin	https://github.com/schacon/ticgit (fetch)
    ​​origin	https://github.com/schacon/ticgit (push)
    

    ref.: https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes

  • $git remote show <origin>: list detail, include URL of the repo
  • $git remote add <name> URL: add remote
  • $git rename <a> <b>: rename remote <a> to remote <b>
  • Show hidden branch by branch -a
  • :notes: Tracking Branches
    • Checking out a local branch from a remote-tracking branch automatically creates what is called a “tracking branch” (and the branch it tracks is called an “upstream branch”).

      What does 'set-upstream' do?
      > sets the default remote branch for the current local branch.

:star: Update Status

  • update: $git fetch origin
  • checkout and rebase local branch to remote state
    • $git checkout master
    • $git rebase remote/master
  • example from teacher:

Checking out pull requests locally

git fetch origin pull/ID/head:BRANCH_NAME

  • For example: git fetch origin pull/45545/head:mergify/bp/release_generator_rhino/pr-45312
  • Switch to the new branch that's based on this pull request:
    [main] $ git switch BRANCH_NAME

Basic Workflow

:zap: Make commits on local repository and pull the commits per day.

若 push 失敗的話,Git 會建議用 git pull 與 remote branch 做 merge,此時會將多個 commits 合併成一個 commit;若此 merge 有誤,要 reset 回 merge 前的 commit 的話,當時被 merged 進來的 commits 都會不見。

故建議做完 $git fetch 更新 remote stuff 到 local branch 後,將新的 commit rebase 到最新的 commit 上,再做 push

Authentication

Supplement or EXAMPLES

If you used git init to make a fresh repo

2.5 Git Basics - Working with Remotes

If you used git init to make a fresh repo, you'll have no remote repo to push changes to. A common pattern when initializing a new repo is to go to a hosted Git service like Bitbucket and create a repo there. The service will provide a Git URL that you can then add to your local Git repository and git push to the hosted repo. Once you have created a remote repo with your service of choice you will need to update your local repo with a mapping. We discuss this process in the Configuration & Set Up guide below.

Ref.: Bare vs. cloned repositories

Steps:

echo "# info2021_teached_by_jserv" >> README.md git init git add README.md git commit -m "first commit" git branch -M main git remote add origin https://github.com/asahsieh/info2021_teached_by_jserv.git git push -u origin main

What's upstream?

3.5 Git Branching - Remote Branches

【狀況題】 怎麼有時候推不上去

解決方法

  1. 先拉再推
    git pull --rebase
  2. :warning: 無視規則, 總之就是聽我的! (誤)
    git push -f

Stash

將做到一半的code丟在暫存區, and reverts the working directory to match the HEAD commit.

  • Usage

  • Options

    • for the command git stash (push):
      • give a name for the stash: (-m | --message) <message>

Patch and cherry-Pick

Generate Patch

  • git format-patch < base_commit >: towards to the latest commit
  • git format-patch -n3 < top_commit >: towrards to the previous three commits
  • or git format-path < branch >

Apply Patch

  • Commands:
  • Create Patchs from commits on a tree

Patch Conflict

  • Dump information of patch fail to file.rej by git apply --reject <patch>
  • Manually resovle the conflict and git add the file, then git am --continue

Cherry-pick

  • 緊急修bug的commit (a node in red)

Pick a commit but not merge

  • Add --no-commit option:
    ​​$ git cherry-pick 6a498ec --no-commit
    ​​$ git status
    ​​On branch cat
    ​​Changes to be committed:
    ​​(use "git reset HEAD <file>..." to unstage)
    ​​new file: dolphin.html
    

How to revert cherry-picks?

Further study

Bisect and Blame


  • Keep mark the found commit is good or bad, or use a test script; for example:

Ending

Note

Can not open display on gitg

  • Terminal returns an error massage on executing gitg:
    • it means that there has no graphics display
    1. Install a windowing system to display GUI application, X11
      • XQuartz is an X11 display server for Mac OS X. Download a DMG directly from (www.xquartz.org) https://www.xquartz.org/
      • Once you have XQuartz running, go into its Preferences and make this settings change:
    2. Create a new Ubuntu instance by Multipass and here we use firefox as an example:
      multipass launch --name firefox
    3. To inject X11 setting to the virtual machine
      • $ multipass mount /tmp/.X11-unix your_vm:/tmp/.X11-unix
      • The next file to inject is **~/.Xauthority **- unfortunately Multipass only lets us mount directories, not files, into the virtual machine. So we had to do this instead:
        $ multipass mount ~/.Xauthority foo:/home/ubuntu/.Xauthority
        Source path "/Users/david/.Xauthority" is not a directory
        $ multipass transfer ~/.Xauthority foo:/home/ubuntu/.Xauthority
      • The attempt to mount the file failed, as I said. The transfer command copies the file into the virtual machine.
      • This will have to be re-executed every time that file changes.
    4. Find IP address of local host. There are two methods:
      1. From default gateway, by the command netstat -nr:
      2. Find the current actived ethernet interface by ifconfig:
      3. or use command from the reference:
      4. Configure XQuartz display server by entering the xhost command with the IP address of OS on the machine you want to display on it (in red box on the below diagram)
      5. Execute gitg with DISPLAY parameter in the IP address on VM (in red box of below diagram) and we are done****.

References:

On lima

  • Prerequisite: reference SSH chapter in FAQ
    • lima supports port fowarding after v0.7.0
    • Upgrade libslirp after v4.6.1
  • Set the Guest/Host IP addresses to forward
    The IP addresses are set to be fixed, shown in ./docs/network.md
    • Set the IP addresses to Host/Guest is the same as above steps on Multipass

Issues I encountered

When I progress to the last step, executing gitg with setting display to Host IP, but an error returned:

asahsieh@lima-default:~/courses/ca-fa21_taught_by_jserv$ DISPLAY=192.168.5.2:0 gitg Unable to init server: Could not connect: Connection refused Failed to parse options: Cannot open display:

I tried to ping the address and the IP pong successfully:

asahsieh@lima-default:~/courses/ca-fa21_taught_by_jserv$ ping 192.168.5.2 PING 192.168.5.2 (192.168.5.2) 56(84) bytes of data. 64 bytes from 192.168.5.2: icmp_seq=1 ttl=255 time=13.6 ms 64 bytes from 192.168.5.2: icmp_seq=2 ttl=255 time=0.577 ms 64 bytes from 192.168.5.2: icmp_seq=3 ttl=255 time=0.757 ms 64 bytes from 192.168.5.2: icmp_seq=4 ttl=255 time=0.617 ms 64 bytes from 192.168.5.2: icmp_seq=5 ttl=255 time=0.705 ms ^C --- 192.168.5.2 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4021ms rtt min/avg/max/mdev = 0.577/3.246/13.577/5.165 ms

Then I tried to use permission of root, and it worked!

asahsieh@lima-default:~/courses/ca-fa21_taught_by_jserv$ sudo DISPLAY=192.168.5.2:0 gitg & [1] 76309 asahsieh@lima-default:~/courses/ca-fa21_taught_by_jserv$ (gitg:76310): dconf-WARNING **: 08:18:22.934: failed to commit changes to dconf: Failed to execute child process “dbus-launch” (No such file or directory) (gitg:76310): dconf-WARNING **: 08:18:22.941: failed to commit changes to dconf: Failed to execute child process “dbus-launch” (No such file or directory) (gitg:76310): dconf-WARNING **: 08:18:22.947: failed to commit changes to dconf: Failed to execute child process “dbus-launch” (No such file or directory) (gitg:76310): dconf-WARNING **: 08:18:23.039: failed to commit changes to dconf: Failed to execute child process “dbus-launch” (No such file or directory)

Manage Home directory

Tools

for merge

Meld
  • Using tips
    1. Which version of the git file will be finally used: LOCAL, BASE or REMOTE?
      It's the one in the middle : BASE.

      In fact, BASE is not the common ancestor, but the half-finished merge where conflicts are marked with >>>> and <<<<.

      You can see the file names on the top of meld editing window.

      image alt

      You can edit the BASE file as you want with or without using meld commands.
      You can also get rid of meld and just edit the file with your favorite text editor.

      • The code between <<<< HEAD and ===== markers is the one of your local file before the merge.
      • The code between ==== and >>>> <branch name> is the one of the remote file.

for familar Git instruction

Futher study

Proper none

  • WIP: work in progress

為你自己學 Git

請說明 git clonegit fetchgit pull 這三個指令有什麼不同?

  • git clone
    clone 指令會把線上的專案,「整個」複製一份到你的電腦裡,並且在你的電腦裡建立相對應的標案及目錄(包括 .git 目錄),通常這個指令只會在一開始的時候使用,clone 之後要再更新的話,通常是執行 git fetchgit pull 指令。

  • git fetch
    假設遠端節點叫做 origin,當執行 git fetch 指令的時候,Git 會比對本機與遠端(在這邊就是 origin)專案的差別,會「下載 origin 上面有但我本機目前還沒有」的內容下來,並且在本地端形成相對應的分支。

    不過,fetch 指令只做下載,並不會進行合併

  • git pull
    pull 指令其實做的事情跟 fetch 是一樣的,差別只在於 fetch 只有把檔案抓下來,但 pull 不只抓下來,還會順便進行合併。也就是說,本質上,git pull 其實就等於 git fetch 加上 merge 指令

Reset, Rebase, Revert 這三個命令的差別是?

指令 改變歷史紀錄 說明
Reset

新增、初始 Repository

Collaborate with pull requests from GitHub Docs

  • Getting started
    • Collaborative development
      • Fork and pull model
        You do not need permission to the source repository to push to a user-owned fork. The changes can be pulled into the source repository by the project maintainer. When you open a pull request proposing changes from your user-owned fork to a branch in the source (upstream) repository, you can allow anyone with push access to the upstream repository to make changes to your pull request.
  • Working with forks
    • About forks
      • If you want to create a new repository from the contents of an existing repository but don't want to merge your changes to the upstream in the future, you can duplicate the repository or, if the repository is a template, you can use the repository as a template. For more information, see "Duplicating a repository" and "Creating a repository from a template".

git-submodule

It often happens that while working on one project, you need to use another project from within it.

  • Here’s an example. Suppose you’re developing a website and creating Atom feeds. Instead of writing your own Atom-generating code, you decide to use a library.

How to revert the changes on submodules

reference the answer for How do I revert my changes to a git submodule?

If you want to do this for all submodules, without having to change directories, you can perform
git submodule foreach git reset --hard

You can also use the recursive flag to apply to all submodules:
git submodule foreach --recursive git reset --hard

Examples or handy commands

Merge a tested branch back to the commit which is the start point of the tested branch

illustration (the branch in green)

  1. Method 1: by git merge

    I followed the basic merge section introduced on the above further study on Merge, but a message of Automatic merge failed was returned:

    ​​​asahsieh@lima-default:~/courses/ca-fa21_taught_by_jserv$ git co main
    ​​​Already on 'main'
    ​​​Your branch is up to date with 'origin/main'.
    ​​​asahsieh@lima-default:~/courses/ca-fa21_taught_by_jserv$ git merge origin/check_correctness_of_init_node
    ​​​Auto-merging lab1/max_depth_of_binary_tree.s
    ​​​CONFLICT (content): Merge conflict in lab1/max_depth_of_binary_tree.s
    ​​​Automatic merge failed; fix conflicts and then commit the result.
    

    I checked the file to be merged and found that the merge is on HEAD, not on the start point of the tested branch.

    Git Merge from Atlassian:
    However, a fast-forward merge is not possible if the branches have diverged. When there is not a linear path to the target branch, Git has no choice but to combine them via a 3-way merge:

    :+1: So, We make a new commit from two branches;

    BUT not merging the branch onto old commits of Main

  2. by git cherry-pick

ref.: How to merge only specific commits from a pull request with git cherry-pick

:notes: The tested branch is still merged to the latest commit of main branch, not merged to the started commit of tested branch.

The tested branch can not be merged back to its started commit?

  1. by git rebase

ref.: 另一種合併方式(使用 rebase)

  • Steps:

    1. Switch to the branch to be rebase
    2. Execute git rebase <the_branch_to_be_base>
  • 【狀況題】怎麼取消 rebase?

    • after executing git merge
      > by git reset HEAD^ --hard
    • after executing git rebase
      > by Reflog
      • find the commit before doing rebase
      • execute git reset <sha_val_of_the_commit_before_doing_rebase> --hard
        > by ORIG_HEAD
        it records the commit be pointed by HEAD pointer before doing danger operation
      • execute git reset ORIG_HEAD --hard

I got a conclusion that commits on other branches can only be merged onto the lastest commit of master branch

All of the above methods can achieve our goal, I used git merge and result is as follows:

Does git-clone support http redirects?

Discard changes in working directory

Use "git restore <file>..."

How to push code to your github repository using token authentication

git push with github token Code Example

The command:

git remote set-url origin https://<githubtoken>@github.com/<username>/<repositoryname>.git

Can a branch be renamed?

Creating Git branch in detached HEAD State

Ref.:

git branch <branch>
git checkout <branch>

Recovering Lost Commits

How to revert multiple commits in Git

What to do when git branch has diverged?

https://poanchen.github.io/blog/2020/09/19/what-to-do-when-git-branch-has-diverged

  • by git rebase origin/master or git merge origin/master
  • Rule of thumb: Frequently rebase your feature branch to make process of resolving conflict easier in the future.

How to partially revert a commit in git?

  • :heavy_check_mark: A reference: https://link-intersystems.com/blog/2015/04/19/how-to-partially-revert-a-commit-in-git/
    > I chose the method in the final for easily adopt.
  • A method which keep revert history from pal:
    IMG_0129
    • Detail command

      ​​​​44078  git log
      ​​​​44079  git log cook.sh
      ​​​​44080  git revert de56b27c
      ​​​​44081  git log
      ​​​​44082*
      ​​​​44083  git am de56b27c
      ​​​​44084  git format-patch -p1 de56b27c
      ​​​​44085  git am 0001-default-tirgger-p470-p670-p870-checkpoint-on-cook-91.patch
      ​​​​Git log // 29f53897
      ​​​​44086  git reset HEAD~1
      ​​​​44090  git add ../../jenkins/checkpoint_restore.Jenkinsfile
      ​​​​44091  git add -p cook.sh
      ​​​​44094  git commit -m "applied change"
      ​​​​44095  git log
      ​​​​44096  git rebase -i HEAD~2
      ​​​​44097  git st
      ​​​​44098  git restore cook.sh
      ​​​​44099  git st
      ​​​​44100  git rebase HEAD~2
      ​​​​44101  git rebase -i HEAD~2
      ​​​​44102  git log
      ​​​​44103  git format-patch -p1
      ​​​​44104  gb -a
      ​​​​44105  gb
      ​​​​44106  git co dev/khsieh/fix-output-path-of-cook
      ​​​​44107  ls
      ​​​​44108  git am 0001-Revert-default-tirgger-p470-p670-p870-checkpoint-on-.patch
      ​​​​44109  git log
      ​​​​44110  gitl p
      ​​​​44111  git lp
      ​​​​44112  git log --patch
      ​​​​44113  ls
      ​​​​44114  gs
      ​​​​44115  git co master
      ​​​​44116  gco master
      
    • ​​​​git log
      

      Check commit id of A

    • ​​​​git revert A
      
      • ​​​​​​COMMIT_EDITMSG
        ​​​​​​  Revert "default tirgger p470/p670/p870 checkpoint on cook (#915)"
        ​​​​​​  
        ​​​​​​  This reverts commit de56b27c96e525c8f8c9b54368cd749b240c2000.
        ​​​​​​  
        ​​​​​​  # Please enter the commit message for your changes. Lines starting
        ​​​​​​  # with '#' will be ignored, and an empty message aborts the commit.
        ​​​​​​  #
        ​​​​​​  # On branch master
        ​​​​​​  # Your branch is up to date with 'origin/master'.
        
    • Create a commit (or patch) with reverting some file