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?

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • See my technique here https://stackoverflow.com/a/67361293/341994 – matt May 15 '21 at 00:32
  • 1
    Does this answer your question? [Git Merge only single file from master into current branch](https://stackoverflow.com/questions/39916006/git-merge-only-single-file-from-master-into-current-branch) – matt May 15 '21 at 00:34
  • 1
    Why not [`git merge-file`](https://git-scm.com/docs/git-merge-file)? https://stackoverflow.com/a/13711776/7976758 – phd May 15 '21 at 00:38
  • 1
    @phd Could work, but requires a base file that might not exist. That was the situation my approach was dealing with. – matt May 15 '21 at 00: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! – Thalles Portilho May 17 '21 at 12:59

1 Answers1

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
    
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Would be great to explain used symbols like abc123. – Nikolai Ehrhardt Apr 20 '22 at 10:28
  • @NikolaiEhrhardt `abc123` comes from the question, where it is referenced as a commit SHA1 (the shorthand form: https://stackoverflow.com/a/43764118/6309) – VonC Apr 20 '22 at 14:17
  • basiscally the parameter -s describes a source, and i think it could be any rev-description, like branch or tag. – Nikolai Ehrhardt Apr 20 '22 at 16:29
  • @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. – VonC Apr 20 '22 at 17:28