Fetch specific commit from remote git repo

6.1k views Asked by At

So, what I'm basically trying to do is to pull down a given commit (identified by its SHA) from one remote repo, and then push it to another remote repo as a new branch (whose name I autogenerate). The source repo will vary and these are all one-shot operations, so I don't want to git remote add these remotes and I don't want to create refs/branches for the commits. And I don't want to change the HEADs of any of my local branches.

So, how do I just grab the given remote commit (and any of its parent commits that are new to me) and add it/them to my local git database?

git pull implicitly involves a merge or rebase, so that's out of the question.

I tried git fetch https://github.com/foo/bar.git 7d0969daba1fdf9d5bb9bc9a2847fd1bc1c7e426
but that just leads to
error: no such remote ref 12819ad8e10e5906df5352d7d8fec1fceb1f3afc
(and yes, I verified that that commit SHA exists on that remote; looks like git doesn't accept a SHA here anyway).

I mean, I guess I could come up with a single arbitrary local branch name to always pull the commits down into, and then delete that branch after every push, but that's seems inelegant...

2

There are 2 answers

0
Andrew C On BEST ANSWER

Git does not allow you to fetch by SHA by design. It doesn't seem like there are any plans to enable that either based on previous conversations on the developers mailing list

You will have to have a reference on the remote in order to be able to fetch. You should be able to auto-generate this part I would imagine, since you have to have a mechanism to pass the remote and sha back and forth already.

0
Antwane On

Use git fetch to get all commits from your origin repository. Then, create a branch on the desired commit

git branch theBranch 7d0969dab

Now, you can push this branch to the second repo

git push https://github.com/secondRepo/bar.git theBranch:theRemoteBranchNameYouWant