Imposter!
Notes from someone pretending!



Copying files across git-branches

How would one copy files across a git branch without checking out that branch.

Posted on


While working on a repo with several branches, sometimes the need arises to get a file from another branch. After checking out the internet for options I saw some examples in junegunn/fzf and a particular function snag looked interesting.

I modified that function slightly to suit my needs and thought let me quickly pen it down here; lest i forget it!

function snag --description 'Pick desired files from a chosen branch and checkout in '
  # use fzf to choose source branch to snag a file FROM
  set branch (git for-each-ref --format='%(refname:short)' | fzf --prompt="Search for a Branch:> " --multi=1 --height 20% --layout=reverse --border)
  # avoid doing work if branch isn't set
  if test -n "$branch"
    # use fzf to choose files that differ from current branch
    set file (git diff --name-only $branch | fzf --prompt="Search for a file to checkout at CWD:> " --multi=1 --height 20% --layout=reverse --border)
  end
  # Stop the operation, if there is already a file with the same name in $CWD.
  if test -e (basename $file)
    echo "$file: Already exists and this operation will overwirite the existing file!"
    echo ""
    echo "If you still want to continue, run the below command:"
    set bfile (basename $file)
    echo "git show $branch:$file > $bfile"
    return 1
  end

  # avoid checking out branch if files aren't specified
  if test -n "$file"
    git show $branch:$file > (basename $file)
  end
end

This function is a little paranoid, where if it finds a file with the same name that you wish to checkout, aborts the operation and gives you the command if you really want to do it.

The pre-reqs for this function to work are:

As always a rando xkcd ...

Thats it for today!