﻿# 如何以最小下載量的方式取得 Git Repo 中特定資料夾下的特定檔案類型

我在[一小時 No-Code 打造可搜尋的 AI 知識庫系統 (RAG)](https://www.accupass.com/event/2405240341251259777110)課程中有準備一個知識庫範例，可以將整份 [angular.dev](https://angular.dev/) 網站轉成知識庫所需的文字檔案。由於 `angular.dev` 網站內容都是開源的，放在 GitHub 的 [angular/angular](https://github.com/angular/angular) Repo 中的 `adev` 目錄下。但這個 Repo 有 30,486 個 Commits，檔案數與下載量都非常大，如果只想取得特定目錄下的檔案，就需要動用一些 Git 的進階技巧，今天我想來分享一下我是如何快速下載 Git Repo 中特定資料夾下的所有 `*.md` 檔案，並且批次轉成 `*.txt` 的過程。

![RAG Git Repo](https://stwillblogassets.blob.core.windows.net/files/images/external/stwillblogassets.blob.core.windows.net/d0be396f595d9054ba21-00b40cae-68dd-427b-b090-b79cd0072080.webp)

我們預計下載的內容位於這個路徑：

> [https://github.com/angular/angular/tree/main/adev/src/content](https://github.com/angular/angular/tree/main/adev/src/content)

為了能夠最快速的下載檔案，我的下載順序是這樣的：

1.  先下載整個 Repo 的最新版，不取回所有歷史紀錄，而且不做 Checkout 動作。
    
    ```powershell
    git clone https://github.com/angular/angular.git -b main --no-checkout --depth=1
    cd angular
    ```
    
    這樣就可以只取回最新版的檔案，而且不會花費太多時間。
    
2.  使用 `git sparse-checkout` 指令，只取回 `adev/src/content` 目錄下的所有 `.md` 檔案。
    
    以下我是透過 PowerShell 指令來完成這個步驟：
    
    ```powershell
    git sparse-checkout init --cone
    
    echo "/adev/src/content/**/*.md" | Out-File -FilePath '.git/info/sparse-checkout' -Encoding ascii
    
    git checkout
    ```
    
    取出檔案時，會有幾行警告訊息，不過不用擔心，你還是可以僅取回特定想要的檔案！
    
    ```
    warning: unrecognized pattern: '/adev/src/content/**/*.md'
    warning: disabling cone pattern matching
    warning: unrecognized pattern: '/adev/src/content/**/*.md'
    warning: disabling cone pattern matching
    Your branch is up to date with 'origin/main'.
    ```
    
    這樣就可以只取回 `adev/src/content` 目錄下的所有 `.md` 檔案，而且不會取回其他不需要的檔案，因此取出檔案的速度也會非常快。
    
3.  然後我將所有 `.md` 檔案批次轉成 `.txt` 檔案。
    
    ```powershell
    Get-ChildItem -Recurse -Filter *.md | Rename-Item -NewName { $_.Name -replace '\.md$', '.txt' }
    ```
    
    這樣就可以將所有 `.md` 檔案批次轉成 `.txt` 檔案，這樣就可以快速的將所有檔案轉換成 RAG 所需的文字檔案。
    
4.  最後，我將所有檔案移動到當前目錄下，並且刪除所有的子目錄，確保所有「文字檔」都在同一個目錄下。
    
    ```powershell
    cd adev/src/content/
    Get-ChildItem -Recurse -Filter *.txt | ForEach-Object {
        $newName = ($_.DirectoryName -replace [regex]::Escape((Get-Location).Path), '') -replace '\\', '_'
        $newName = $newName.TrimStart('_') + "_" + $_.Name
        Move-Item $_.FullName -Destination (Join-Path -Path (Get-Location) -ChildPath $newName)
    }
    
    Get-ChildItem -Directory -Recurse | Remove-Item -Recurse -Force
    ```
    
    這樣就可以將所有的 `.txt` 檔案移動到當前目錄下，並且刪除所有的子目錄，確保所有「文字檔」都在同一個目錄下，方便我們匯入 [Coze](https://www.coze.com/) 的知識庫。
    

簡單的幾個步驟，就可以快速整理好整個網站所需的知識庫資料，接著當然就是 RAG 所需的**文字分塊**與**文字嵌入**(向量化)等工作，這樣就可以快速的完成資料的清理與準備工作。👍

### 相關連結

-   [Git - git-sparse-checkout Documentation](https://git-scm.com/docs/git-sparse-checkout)
