Git 2.17.0窄克隆:仅拉取单个文件并提交的实操问题
Great question! Let's walk through exactly how to pull off editing a single file from a large repo with minimal bandwidth usage, while avoiding that frustrating "does not appear to be a git repository" error. Since you're on Git 2.17.0 (an older but still functional version), we'll work within its feature set.
Step 1: Fix the Clone Command & Avoid Repository Errors
First, let's nail down the initial clone command—this is usually where that "not a git repo" error originates:
- If
srv.bareis a bare repository, your path is correct. If it's a regular non-bare repo, you need to point to its.gitsubdirectory instead (e.g.,file://$(pwd)/srv/.git), since Git needs to interact with the repo's internal metadata files. - Update your clone command to include
--depth 1while keeping the narrow clone filters:
git clone --no-checkout --filter=blob:none --depth 1 "file://$(pwd)/srv.bare" pc1 cd pc1
This pulls only the latest commit's metadata (no actual file content yet) to save maximum space and bandwidth.
Step 2: Sparse Checkout to Fetch Only Your Target File
Git 2.17.0 doesn't have the modern git sparse-checkout init shortcut, so we'll set up sparse checkout manually to grab just the file you need:
- Enable sparse checkout in the repo config:
git config core.sparseCheckout true
- Specify the exact file path you want to fetch. For example, if your target file is
src/utils/helpers.js, run:
echo "src/utils/helpers.js" >> .git/info/sparse-checkout
- Check out the file to your working directory:
git checkout HEAD
Now you'll only see your target file in the pc1 directory—no other repo content is pulled down.
Step 3: Edit, Commit, and Push Your Changes
Shallow clones (created with --depth 1) block pushes by default, so we need to tweak a few configs to allow pushing your single-file change:
- Set up push defaults to target the correct remote branch:
git config push.default current git config remote.origin.push HEAD
- Edit your file as needed, then commit the change:
git add src/utils/helpers.js git commit -m "Update helper function logic"
- Push the commit to the remote repo:
git push
Note: If the remote repo has recent commits you don't have (since we're using a shallow clone), you might hit a non-fast-forward error. In that case, you'd need to fetch the latest changes first, but if you're the only one editing this file, this workflow should work smoothly.
Key Notes for Git 2.17.0
- The
--filter=blob:noneflag works with--depth 1here, but make sure your remote repo (local in this case) supports narrow clones—all local repos do, so this isn't an issue. - Double-check your remote path if you still get the "not a git repo" error: bare repos typically end with
.bare, but regular repos require the.gitsuffix in the URL.
内容的提问来源于stack exchange,提问作者Dan Jacobson

