How to cherry-pick from a remote branch?

I'm having trouble performing a cherry-pick. On my local machine, I'm currently on my "master" branch. I want to cherry-pick in a commit from another branch, named "zebra". The "zebra" branch is a remote branch.

So git status:

# On branch master
nothing to commit (working directory clean)

Ok, now I try to cherry-pick the commit I want:

git cherry-pick xyz
fatal: bad object xyz

where "xyz" is the signature of the commit I'm interested in, that happened on branch "zebra".

So the first obvious question is, why can't git find the commit I'm referencing? I don't really understand how this is working in the first place to be honest. Does git store something like a database of commits locally in my working directory, for all other branches? When executing the cherry-pick command, does it go and search that local database to find the commit I'm talking about?

Since "zebra" is a remote branch, I was thinking I don't have its data locally. So I switched branches:

git checkout zebra
Switched to branch 'zebra'

So now here on my local machine, I can see that the files in the directory reflect zebra's state correctly. I switch back to master, try to cherry-pick again (hoping the commit data is available now), but I get the same problem.

I've got a fundamental misunderstanding of what's going on here, any help would be great.


Solution 1:

Since "zebra" is a remote branch, I was thinking I don't have its data locally.

You are correct that you don't have the right data, but tried to resolve it in the wrong way. To collect data locally from a remote source, you need to use git fetch. When you did git checkout zebra you switched to whatever the state of that branch was the last time you fetched. So fetch from the remote first:

# fetch just the one remote
git fetch <remote>
# or fetch from all remotes
git fetch --all
# make sure you're back on the branch you want to cherry-pick to
git cherry-pick xyz

Solution 2:

Just as an addendum to OP accepted answer:

If you having issues with

fatal: bad object xxxxx

that's because you don't have access to that commit. Which means you don't have that repo stored locally. Then:

git remote add LABEL_FOR_THE_REPO REPO_YOU_WANT_THE_COMMIT_FROM
git fetch LABEL_FOR_THE_REPO
git cherry-pick xxxxxxx

Where xxxxxxx is the commit hash you want.