Kyle Hsieh (謝阿Sa)
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    > contributed by <[asahsieh](https://github.com/asahsieh)> :::spoiler Table of Content [TOC] ::: # References - [熟悉Git和Github操作](https://hackmd.io/@sysprog/gnu-linux-dev/https%3A%2F%2Fhackmd.io%2F%40sysprog%2Fgit-with-github) - [Git offical doc](https://git-scm.com/docs) - `SCM` tools: stands for Source Code Management - [Git offical book](https://git-scm.com/book/en/v2) - [Git guide by Atlassian](https://www.atlassian.com/git/tutorials/using-branches/git-checkout) - [On undoing, fixing, or removing commits in git](https://sethrobertson.github.io/GitFixUm/) # 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](//https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/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](https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git) To remember your credentials :::info I chose a method which has less limitation: [Git's built-in credential cache](https://github.com/GitCredentialManager/git-credential-manager/blob/main/docs/credstores.md#gits-built-in-credential-cache) > The [credential cache](https://git-scm.com/docs/git-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](https://opensource.com/article/21/4/git-whatchanged) - `git log --raw` - show source with diff `git show --source` ### [How to use the git log graph command example](https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/How-to-use-the-git-log-graph-command) ## Branch and Merge ### Branch - A label is attached to a commit as a branch #### Move and Create a Branch ```console $ git checkout -b cload ``` - Checkout: move to HEAD - 相當於下面這兩條命令: ```console $ git branch cload $ git checkout cload ``` #### Remote branch - Tracking Branches ```shell $ 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](https://git-scm.com/book/en/v2/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](https://git-scm.com/book/en/v2/ch00/_git_stashing). - A hotfix to make - Let’s create a `hotfix` branch on which to work until it’s completed: ```console $ 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](https://i.imgur.com/JvsfidI.png) #### 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` :::info `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: ![](https://i.imgur.com/4BV00Gn.png) - 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: ![](https://i.imgur.com/Ke3QMI2.png) - operations you can make: ![](https://i.imgur.com/lJhcYxX.png) - **Correct the author information** and then **continue to the next concerned commit** ```shell $ 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: ![](https://i.imgur.com/4gRI6ze.png) - Suggest making a **backup branch** (e.g., *bk*) on the branch to do rebase, before doing rebase. #### while rebasing *When do 3-ways merging* - which revision is `incoming`, and other revision is `HEAD` - When rebasing MyBranch onto master , "incoming" is the branch you have checked out, which is MyBranch , and "current" is master. > https://stackoverflow.com/questions/71332146/incoming-and-current-in-a-rebase ## 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**](https://git-scm.com/book/en/v2/Git-Branching-Remote-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?](https://stackoverflow.com/q/18031946) --> 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: ![](https://i.imgur.com/ovoajq3.png) ### 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 ![](https://i.imgur.com/FHVkKp9.png) :zap: Make commits on local repository and pull the commits per day. :::warning 若 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 - [ ] (TO-READ) [Why is Git always asking for my password?](https://docs.github.com/en/get-started/getting-started-with-git/why-is-git-always-asking-for-my-password) - by **ssh**: `set-url` --> `git remote set-url origin git@github.com:asahsieh/lab0-c` :crying_cat_face: 交大圖書館會檔ssh連線 - by **HTTPS**: > ref.: [Caching your GitHub credentials in Git](https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git) > > 因不想再安裝一套CLI, GitHub CLI;故改用[Git Credential Manager](https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git#git-credential-manager) > > Credential stores: 選擇跨平台且較其他方法來得不受限的方式,Git's built-in [credential cache](https://git-scm.com/docs/git-credential-cache) ### Supplement or EXAMPLES #### If you used git init to make a fresh repo > [2.5 Git Basics - Working with Remotes](https://git-scm.com/book/en/v2/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](https://www.atlassian.com/git/tutorials/setting-up-a-repository) Steps: ```shell= 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](https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches) ### 【狀況題】 怎麼有時候推不上去 #### 解決方法 1. 先拉再推 `git pull --rebase` 2. :warning: 無視規則, 總之就是聽我的! (誤) `git push -f` ## [Stash](https://git-scm.com/docs/git-stash) 將做到一半的code丟在暫存區, and reverts the working directory to match the `HEAD` commit. - Usage ![](https://i.imgur.com/yyCPJ6e.png) - 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: ![](https://i.imgur.com/CI7FNCH.png) - Create Patchs from commits on a tree ![](https://i.imgur.com/3J4yskf.png) ### 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: ```shell $ 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? - [Git 版本控制系統 - cherry-pick 合併提交與 revert 抵銷提交](https://awdr74100.github.io/2020-05-05-git-cherrypick-revert/) #### Further study - [How to merge only specific commits from a pull request with git cherry-pick](https://mattstauffer.com/blog/how-to-merge-only-specific-commits-from-a-pull-request/) - **You can grab only specific commits with a very simple git command: `git cherry-pick`.** ## Bisect and Blame ![](https://i.imgur.com/EMrh1rf.png) ![](https://i.imgur.com/ijgyYQj.png) - Keep mark the found commit is good or bad, or use a test script; for example: ![](https://i.imgur.com/SmfcIyf.png) ## Ending ![](https://i.imgur.com/ZuamKMp.png) ## Note ### Can not open display on `gitg` - Terminal returns an error massage on executing `gitg`: - ![](https://i.imgur.com/snS3cMf.png) - it means that there has no graphics display 1. Install a windowing system to display GUI application, X~11~ - XQuartz is an X~11~ 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: ![](https://i.imgur.com/fJXN6x3.png) 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. 3. Find IP address of local host. There are two methods: 1. From default gateway, by the command `netstat -nr`: ![](https://i.imgur.com/VBrFiqQ.png) 2. Find the current actived ethernet interface by `ifconfig`: ![](https://i.imgur.com/j3WfPN9.png) 3. or use command from the reference: ![](https://i.imgur.com/dGUkxxW.png) 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****. ![](https://i.imgur.com/mFUwTa3.png) > References: - [Use Canonical's Multipass to display Linux GUI applications on macOS desktop](https://techsparx.com/linux/multipass/display-gui-on-mac.html) - https://www.businessnewsdaily.com/11035-how-to-use-x11-forwarding.html #### On [lima](https://github.com/lima-vm/lima) - Prerequisite: reference [SSH](https://github.com/lima-vm/lima#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](https://github.com/lima-vm/lima/blob/master/docs/network.md) - Set the IP addresses to Host/Guest is the same as above steps on `Multipass` :::warning Issues I encountered ::: When I progress to the last step, executing `gitg` with setting display to Host IP, but an error returned: ```shell= 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: ```shell= 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! ```shell= 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) ``` ![](https://i.imgur.com/8ho0Ikm.png) ### Manage Home directory - https://opensource.com/article/21/4/git-home - (status) build private Git server ### Tools #### for *merge* ##### [Meld](https://wiki.gnome.org/Apps/Meld) - Using tips 1. [Which version of the git file will be finally used: LOCAL, BASE or REMOTE?](https://stackoverflow.com/questions/11133290/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](https://i.stack.imgur.com/IyhA4.png) 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 - by GUI - [LearnGitBranching](https://learngitbranching.js.org/) - [Visualizing Git Concepts with D3](https://onlywei.github.io/explain-git-with-d3/#checkout-b) - Visualize `git log` on Linux: `$tig` ## Futher study ### Proper none - `WIP`: work in progress ### [為你自己學 Git](https://gitbook.tw/) #### 請說明 `git clone`、`git fetch` 跟 `git pull` 這三個指令有什麼不同? - **git clone** clone 指令會把線上的專案,「整個」複製一份到你的電腦裡,並且在你的電腦裡建立相對應的標案及目錄(包括 `.git` 目錄),通常這個指令只會在一開始的時候使用,clone 之後要再更新的話,通常是執行 `git fetch` 或 `git 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 | 是 | | ![](https://hackmd.io/_uploads/Hk0TPbVms.png) ### 新增、初始 Repository - [Setting up a repository](https://www.atlassian.com/git/tutorials/setting-up-a-repository) ### [Collaborate with pull requests from GitHub Docs](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests) - 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](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/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](https://docs.github.com/en/articles/duplicating-a-repository)" and "[Creating a repository from a template](https://docs.github.com/en/articles/creating-a-repository-from-a-template)". ### [git-submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules) 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](https://stackoverflow.com/a/17871677) for [How do I revert my changes to a git submodule?](https://stackoverflow.com/questions/10906554/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) ![](https://i.imgur.com/3uQr4rn.png) 1. Method 1: by `git merge` I followed the `basic merge` section introduced on the above [further study on Merge](https://hackmd.io/GUqMIriHTXmNzuZIOaWVLw?both#Further-study-on-git-scm-32-Git-Branching---Basic-Branching-and-Merging), 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](https://www.atlassian.com/git/tutorials/using-branches/git-merge): 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: ![](https://i.imgur.com/ejHaKq7.png) :+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](https://mattstauffer.com/blog/how-to-merge-only-specific-commits-from-a-pull-request/) :notes: `The tested branch` is still merged to the latest commit of `main` branch, not merged to the started commit of tested branch. :::warning The tested branch can not be merged back to its started commit? ::: 3. by `git rebase` > ref.: [另一種合併方式(使用 rebase)](https://gitbook.tw/chapters/branch/merge-with-rebase) - Steps: 1. Switch to the branch to be rebase 2. Execute `git rebase <the_branch_to_be_base>` - :::info 【狀況題】怎麼取消 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` ::: :::success 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: ![](https://i.imgur.com/AsoCuHV.png) ### [Does git-clone support http redirects?](https://www.reddit.com/r/git/comments/r5odvh/does_gitclone_support_http_redirects/) - [x] 301 vs 302 redirect > [301 轉址與 302 轉址的兩大差異](https://awoo.ai/zh-hant/blog/301-302-redirect/#301_%E8%BD%89%E5%9D%80%E8%88%87_302_%E8%BD%89%E5%9D%80%E7%9A%84%E5%85%A9%E5%A4%A7%E5%B7%AE%E7%95%B0) > [What Is a 301 or 302 Redirect?](https://www.domain.com/blog/what-is-a-redirect/) - Just remember. Permanent redirect = 301, while temporary = 302. - 301 redirect: - The redirect typically helps change the URL of the page when it shows up in search engine results. - An example: When you want to [transfer a domain](https://www.domain.com/domains/transfer) - 302 redirect: - This 302 redirect may be shown as a 302 found (HTTP 1.1), or moved temporarily (HTTP 1.0). - A example of such a time would be in **an e-commerce setting**. - [ ] Yes, git will follow redirects only for the initial request to a remote, but not for subsequent follow-up HTTP requests. > From [document of git-config http.followRedirects ](https://git-scm.com/docs/git-config/2.15.4#Documentation/git-config.txt-httpfollowRedirects) - and git only support `301 redirect` > From [Hi everyone! I want to shorten the URL to a Github repo and use it for `git clone`.](https://www.reddit.com/r/git/comments/r5odvh/does_gitclone_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](https://www.codegrepper.com/code-examples/shell/git+push+with+github+token+) The command: ```shell 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.: > - https://ibexoft.com/creating-git-branch-in-detached-head-state/ > - https://stackoverflow.com/questions/22366034/git-create-branch-where-detached-head-is ```shell git branch <branch> git checkout <branch> ``` ### Recovering Lost Commits - [Git Reflog: A Guide to Recovering Lost Commits](https://www.thisdot.co/blog/git-reflog-a-guide-to-recovering-lost-commits/) ### How to revert multiple commits in Git - No further commit to be created on reverting the commits: https://timmousk.com/blog/git-revert-multiple-commits/#:~:text=Final%20thoughts-,How%20to%20revert%20multiple%20commits%20with%20git%20revert%3F,the%20%2D%2Dno%2Dcommit%20option.&text=Note%3A%20You%20can%20find%20the,commit%20and%20push%20your%20changes. - A formal method but a new commit will be created: https://dev.to/isabelcmdcosta/how-to-undo-the-last-commit--31mg#:~:text=If%20you%20want%20to%20revert,git%20checkout%20. ### 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](https://hackmd.io/_uploads/BJJ03-X9A.png) - 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 - ...

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully