1

Saying that I've execute git add --all && git commit twice. So for now my local git repository contains two new commits: A and B.

If I execute git push, I will push both of them.

How can I push only the newer commit, which is B? In other words, is it possible to remove the commit A without touching the commit B?

2
  • You can do a git rebase and skip the commit you don't want. Commented Jul 18, 2018 at 7:34
  • 2
    It's fundamentally impossible to remove A while keeping B and leaving it untouched. B keeps track of its parent. It specifies that its parent is A. git rebase, as Jaa-c commented, may work, but it works by creating a new commit which doesn't specify A as its parent. Commented Jul 18, 2018 at 7:37

3 Answers 3

1

Say you want to push to master. I would cherry pick the commit I want to deliver:

git fetch git checkout -b delivery_branch origin/master git cherry-pick B git push origin master 
Sign up to request clarification or add additional context in comments.

Comments

1

The short and rather unsatisfying answer is "you can't". Commit B inherently depends on commit A because A is B's parent commit.

What you can do is stop using commit B at all. Construct a third commit—call it C—whose parent is the parent of A, and whose content is whatever content you want. (This could match B's content, for instance, or not.) Then move the name of the branch so that instead of pointing to commit B (which points back to A, which points back to older commits), the name points to new commit C:

 B--A [no longer on your branch - abandoned in favor of C] / ...--o--C <-- branch 

You can now git push origin branch to push commit C, without using commits A and B at all.

(Note that the precise mechanics for making commit C depend on what snapshot you want to have attached to C.)

Comments

0

Assuming your log is like this :

Z--A--B 

Where A is the commit you want to remove and B is the commit that you want to preserve. Also assume that 'dev' is the name of this branch.

Then, (with A,B and Z representing the respective commit IDs):

  1. Create a temporary branch say, 'temp', from the commit Z.

    git checkout -b temp git reset --hard Z 
  2. Cherry-pick the commit B to temp. (Resolve conflicts if any)

    git cherry-pick B 
  3. Go back to your branch (dev in this case), and remove A and B

    git checkout dev git reset --hard Z 
  4. Merge temp branch into your branch (dev)

    git merge temp 
  5. Delete the temp branch

    git branch -d temp 

Note:

  1. The commit ID of B will change as we are cherry-picking.

  2. If you have A and B in your remote branch, then you will have to push with the force option.

    git push -f 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.