2

I have one version of a file at commit "#abc123" and the current version of the same file locally.

I want to MERGE, NOT REVERT, the two versions for only this file.

I read about some workarounds using "git cherry pick", but nothing direct.
Is there a simple way of doing this?

5
  • See my technique here stackoverflow.com/a/67361293/341994 Commented May 15, 2021 at 0:32
  • 1
    Does this answer your question? Git Merge only single file from master into current branch Commented May 15, 2021 at 0:34
  • 1
    Why not git merge-file? stackoverflow.com/a/13711776/7976758 Commented May 15, 2021 at 0:38
  • 1
    @phd Could work, but requires a base file that might not exist. That was the situation my approach was dealing with. Commented May 15, 2021 at 0:47
  • 1
    @matt Maybe, but I'm kind of newbie with git, so this solution seems a little complicated to me. I did what VonC suggested and it worked very fine. Any way, thank you for your availability. Cheers! Commented May 17, 2021 at 12:59

1 Answer 1

2

I would:

  • make sure the current version of that file is committed.

  • switch to a new branch from the current commit:

      git switch -c tmp
    
  • restore that one file from the old commit, using git restore:

      git restore -s abc123 -SW -- aFile
      git restore --source=<tree> --staged --worktree -- <pathspec>
    
      git commit -m "restore old version of a file
    

Meaning: restore aFile content from commit abc123 -- the source --, and apply that content both to the index/cache (--staged), and the working tree -- where files are checked out: --worktree)

  • finally I can merge two commits, which will merge only that one file

      git switch main (or master)
      git merge tmp
    
Sign up to request clarification or add additional context in comments.

4 Comments

Would be great to explain used symbols like abc123.
@NikolaiEhrhardt abc123 comes from the question, where it is referenced as a commit SHA1 (the shorthand form: stackoverflow.com/a/43764118/6309)
basiscally the parameter -s describes a source, and i think it could be any rev-description, like branch or tag.
@NikolaiEhrhardt Correct. I have added a link to the documentation as well as a clear explanation of each parameters used in the git restore command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.