Home > Blockchain >  How do I "extract" a tree-ish to a directory?
How do I "extract" a tree-ish to a directory?

Time:06-07

I have an application that accepts git tree object hashes as input, and needs to extract those trees to a temporary directory.

Today, we do this by: (morally)

mkdir -p temporary/directory
cd temporary/directory
git archive --format tar f6ad2c912329ae4108883b8b8e20f2c50e968466 --output throwaway.tar.gz
tar xf throwaway.tar.gz
rm throwaway.tar.gz

Is there a way to ask git to extract/checkout the tree-ish directly rather than needing to create a throwaway tarball first?

CodePudding user response:

Given a Git repository in environment variable $GIT_DIR and an arbitrary but valid tree hash ID argument $1, running this in an empty directory:

#! /bin/sh
GIT_INDEX_FILE=$(mktemp) || exit 1
rm -f "$GIT_INDEX_FILE"
trap "rm -f $GIT_INDEX_FILE" 0 1 2 3 15

git read-tree -m -u $1

does the trick. The git read-tree command reads the tree into the (non-existent because we removed it) temporary index file from mktemp, creating an index populated with that tree. The -m flag (one of -m, --reset, or --prefix is required) enables the -u flag, which fills in the working tree, which is the current directory.

Add a bit of boilerplate to accept a Git repository argument and use git --git-dir=$dir to avoid having to export GIT_DIR into the above shell fragment. The key command is git read-tree though. You can also read the tree object and then use git checkout-index, but given -u there's no need for a second separate Git command.

  •  Tags:  
  • git
  • Related