Yichung
    • 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 No publishing access yet

      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.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      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 New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Objects behind git: snapshots, not differences ###### tags: `blog` `git` `git objects` ![](https://i.imgur.com/hXbu0af.png) Git 是我們重要的版本紀錄工具,讓我們可以快速的在各個版本間切換,讓我們的工作目錄跟某個時刻的工作目錄一摸一樣。Git還有branch的概念把上下相關的版本連結在一起,方便我們做版本控制。 當我們使用 git 時,git object 會在背後運作,我們的 git object 存在 `.git/objects` 資料夾中,我們平常的commit、branch就放在這個地方。git object 紀錄著專案歷史中的每個commit,幫助git將我們的工作目錄變成過去的樣子。 雖然我們常常用 git,但我們鮮少知道在背後的 git object 到底長怎樣,也鮮少去徹底理解branch到底怎麼運作的。這篇文章描述了在git背後紀錄著各個commit的object,以及git如何實現branch的概念幫助我們管理版本。 ## Commits are snapshots, not diff 平常我們在 commit 時,會看到 git 顯示有多少 insertion 多少deletions,有可能會因此以為git 的版本是這些差異累積起來的,但實際上git在背後是存了一個個 snapshot,每一個版本的目錄跟檔案都被git完整的存了下來。 Git 做的事情就是將檔案系統按照時間做 snapshots。 我們先回想檔案系統是個怎樣的結構,我們的目錄底下會有目錄以及檔案;而底下的目錄,底下還會有目錄以及檔案;而底下的目錄,......。**我們的檔案系統就是由檔案以及樹狀目錄組成的結構**。 ![](https://i.imgur.com/RcBpXve.jpg) 而 **git 的snapshot 有著很類似的結構**,一共有三種主要的 objects: * Blob: blob (binary large object) 代表檔案的內容,就真的只有內容而已,如果 hello.txt,內容是 hello world,blob只會存 hello world 而已。 * Tree: tree代表著目錄,檔案系統中的目錄會儲存其他目錄以及檔案,而tree就跟目錄一樣,會儲存其他的tree以及blob。 * Commit: 這就是我們認識的 commit 的真面目,他會紀錄commit message 、作者、提交時間等metadata,並且有個pointer指向反映當時檔案系統的tree, 還有pointer指向先前的 commit 稱為 parent。 為了快速查找這些物件,git 透過 SHA-1 從objects 得到一個雜湊值,用這個雜湊值標記我們的物件,作為我們搜尋物件的依據。 ![](https://i.imgur.com/9JYAdTy.jpg) 而這些objects 被放在 .git/objects 裡。 ``` .git ├── objects │   ├── 2f │   │   └── bb293b693940a43e6c33d24600ebf2320e21fe │   ├── 3b │   │   └── b22ead3b2eb7b9b2d5f137c75a0b74229161fa │   ├── 55 │   │   ├── 35bde54383fce2e851f466b08fa732ff636710 │   │   └── e535d6157ee4f046e3c374cb9e8db17d5c7542 │   ├── a0 │   │   └── 1b5ab47afa25d1278782b6671d5c0b0e4f9b44 │   ├── ce │   │   └── 85dda57857ca9621c8acbe5d625ba6ec42f6a4 │   ├── info │   └── pack ├── COMMIT_EDITMSG ├── HEAD ├── config ├── description ├── hooks ├── index ├── info ├── logs └── refs ``` 我們可以進一步比較前後兩個 commits。 由於是透過雜湊值標記我們物件,前後兩個 commits 裡只要是內容一樣的檔案或是內容一樣的 directory,tree 或 blob都會對應到跟先前 commit 相同的 object。如此一來,雖然 commit 是 snapshot,但每次增加的 git object 並沒有想像中的多。 ![](https://i.imgur.com/XqwO7Kl.jpg) ## Branch 只是一個指標 branch 把上下相關的版本連結在一起,方便我們做版本控制。 但實際上把上下版本相連的是 commits,commit 中存著一個 parent,指向前一個 commit,被指向的 commit 又有自己的 parent,一個commit 指一個 commit。當我們查看 branch 的時候,就是透過這樣的 linked list ,把 branch 中commit 一個個給列出來。 所以當我們,在branch新增一個 commit 的時候,我們會有一個新的 commit object,他的parent指向前一個 commit,接著把 branch指向新的commit上,就跟 push 一個 node 進 linked list 一樣。 那我們要怎麼知道現在在哪個 branch呢? 我們會透過HEAD來指出現在在哪個 branch,HEAD是一個特別的指標,通常會指著一個 branch ,隨著我們切換到不同branch,HEAD 就跟著指到另一個的 branch。 ![](https://i.imgur.com/gaQw11k.jpg) 另外補充,我們其實可以讓HEAD直接指向一個 commit。但這個時候,HEAD 沒有指向任何 branch,就會變成 detached HEAD。 這樣的 linked list 看起來很簡單,但實際上還有一點問題,因為我們branch 會有 merge 的時候。難道新的 commit 來自兩個 commit,那新的 commit 就要有兩個 parent 嗎? 對啊,就是兩個 parent。 我們可以用 `$ git cat-file -p <SHA-1>` 來看 commit object的內容 ``` $ git cat-file -p 5593c80 tree bb5c7ff40fff92125847ffbe62c7f5873f02fdfa parent e0e5e188e058fcdeabd9e9057accb782c02b9070 parent d0fbd6a432fd42a9c3353db005f8782792637f6e author yiz <yiz@email.com> 1649339110 +0800 committer yiz <yiz@email.com> 1649339110 +0800 Merge branch 'new-feature' ``` 可以看到 commit object 裡有兩個 parent,而且這兩個 parent 的順序是很重要的,分為 first parent 以及 second parent。 ![](https://i.imgur.com/I0KIu0u.jpg) 另外的細節是,針對 parent 的 notation 其實比想像的複雜一點: 在平常使用 git 的時候可能會使用 `~` 跟 `^` 來指定某個 commit 的 parent,但指定的細節有點不同。 我們可以翻一下 git 的 manual: `$ git help rev-parse` ``` <rev>^[<n>], e.g. HEAD^, v1.5.1^0 A suffix ^ to a revision parameter means the first parent of that commit object. ^<n> means the <n>th parent (i.e. <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when <rev> is the object name of a tag object that refers to a commit object. <rev>~[<n>], e.g. HEAD~, master~3 A suffix ~ to a revision parameter means the first parent of that commit object. A suffix ~<n> to a revision parameter means the commit object that is the <n>th generation ancestor of the named commit object, following only the first parents. I.e. <rev>~3 is equivalent to <rev>^^^ which is equivalent to <rev>^1^1^1. See below for an illustration of the usage of this form. ``` `^n` 代表第 n 個 parent `~n` 在只看 first parent 的情況下,代表第 n 個的祖先 在 git 的 manual 還補充了一個圖, ``` Here is an illustration, by Jon Loeliger. Both commit nodes B and C are parents of commit node A. Parent commits are ordered left-to-right. G H I J \ / \ / D E F \ | / \ \ | / | \|/ | B C \ / \ / A A = = A^0 B = A^ = A^1 = A~1 C = A^2 = A^2 D = A^^ = A^1^1 = A~2 E = B^2 = A^^2 F = B^3 = A^^3 G = A^^^ = A^1^1^1 = A~3 H = D^2 = B^^2 = A^^^2 = A~2^2 I = F^ = B^3^ = A^^3^ J = F^2 = B^3^2 = A^^3^2 ``` 圖中,`B` 和 `C` 為 `A` 的 parent,左側為第一個parent。 透過 `A^1`、`A^2` 我們會找到 `B` 以及 `C` ,`^` 只從所有 `A` 的 parent中找commit node 而我們透過 `A~1`、`A~2`、`A~3` 會找到BDG,`~` 只會從每個 commit 的 first parent 去追蹤祖先。 如此一來,我們就知道 git reset HEAD^ 就明確的指定要 reset 成哪個 parent 了。 ## How git commands work 有了這些概念,我們再回頭來看兩個過去熟悉的指令到底做了什麼事情。 ### git checkout <branch> `git checkout` 讓我們在不同的 branch 之間切換,讓我們的 working directory,變得跟某個 branch 一樣。 首先是HEAD,HEAD會一直指向現在的branch,git會讓HEAD指到新的 brach。接著是 working directory,由於版本的 snapshot 完整的存在git中,我們只要找出的 branch 指到的 snapshot,再把 snapshot 還原即可。 ![](https://i.imgur.com/lpWXpjs.jpg) ### git reset <commit> git reset 做的事其實超級簡單,就是把 branch指到指定的 commit 上,接著branch中的每個 commit,就會自動透過 commit 裡的parent,沿路指向branch 裡個commit。 ![](https://i.imgur.com/Ewd3cZ1.jpg) 但 git reset 的不同參數,還有是不同的處理。 * --soft: 不對 staged area 跟working tree 做任何動作。 * --mixed: 把 staged area 弄得跟 commit 一樣,但不對 working tree 做任何動作 * --hard: 把 staged area 跟working tree 都弄得跟 commit 一樣 ## 結語 這篇文章解釋了git 背後的物件如何運作,說明 git 是如何對當前的檔案系統做出快照,還有快照間是如何串成 branch。希望這篇對讀者幫助,在使用git的時候能所,更清楚 git 現在是什麼狀態,了解指令到底做了什事。

    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
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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