gitgit-checkoutgit-sparse-checkout

Git checkout with exclusions fails when branch isn't local


I'm trying to checkout a branch, but want to exclude the REAMDE.md and CHANGELOG.md files.


Working:

git clone [url] --no-checkout .
git checkout BranchnameA
git checkout BranchnameB # (any other branch)
git checkout BranchnameA ':^README.md' ':^CHANGELOG.md'

The above leaves the README.md and CHANGELOG.md files from BranchnameB, and doesn't overwrite them with the README.md and CHANGELOG.md files from BranchnameA.


Not working:

git clone [url] --no-checkout .
git checkout BranchnameA ':^README.md' ':^CHANGELOG.md'

Error message:

error: pathspec 'BranchnameA' did not match any file(s) known to git
error: pathspec ':^README.md' did not match any file(s) known to git
error: pathspec ':^CHANGELOG.md' did not match any file(s) known to git

The only difference I can see between the working and not working versions, is that the working version has a local BranchnameA, while the not working one doesn't.

So why do I need a local version for checking out with exclusion patterns?
Also, is there a way around this? I've tried sparse-checkout, but that doesn't really work for my goals.


Solution

  • In the 1st case git checkout BranchnameA creates a new local branch BranchnameA from which later you can checkout files.

    In the second case you don't have branch BranchnameA hence the errors. You have remote-tracking branch origin/BranchnameA (from which git checkout BranchnameA could create local branch) so if you don't want to create a local branch but checkout files directly from the remote branch:

    git checkout origin/BranchnameA ':^README.md' ':^CHANGELOG.md'