6

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...

cvrebert
  • 8,264
  • 2
  • 33
  • 47
  • Git fetch can't fetch by SHA by design. I don't see any solution other than creating and deleting branches. – Andrew C Nov 14 '14 at 00:49
  • @AndrewC If you repost that as an answer, I would happily mark it as accepted. – cvrebert Nov 14 '14 at 19:16
  • IT sounds like a duplicate but i can't find anything exact so I'll add it – Andrew C Nov 14 '14 at 19:42
  • Since Git 2.5 it's possible to fetch a specific commit, see http://stackoverflow.com/a/30701724/537554 – ryenus Mar 29 '16 at 16:01
  • 1
    Possible duplicate of [Retrieve specific commit from a remote Git repository](http://stackoverflow.com/questions/14872486/retrieve-specific-commit-from-a-remote-git-repository) – Bardi Harborow Nov 20 '16 at 05:02

2 Answers2

5

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.

Andrew C
  • 11,594
  • 4
  • 44
  • 52
1

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
Antwane
  • 15,262
  • 5
  • 37
  • 71