Skip to content

Instantly share code, notes, and snippets.

@reidmv
Created March 16, 2022 23:26
Show Gist options
  • Save reidmv/88ce3fa481b754460b756114b8395860 to your computer and use it in GitHub Desktop.
Save reidmv/88ce3fa481b754460b756114b8395860 to your computer and use it in GitHub Desktop.
Example script that uses a Git repo as a vehicle for storing content from a tarball as a new commit
#!/bin/bash
# This script demonstrates using a Git repo as a vehicle for storing content
# from a tarball. It creates new commits, children of a given repo's current
# HEAD, which contain exactly the contents of a given tarball. No consideration
# is given to the prior commit's contents when constructing the new commit.
# Basic usage message if incorrect number of params passed
if [ $# -ne 2 ]; then
echo "Usage: ${0} <path-to-tarball.tar.gz> <git@clone.url>"
exit 1
fi
tarball="${1}"
remote="${2}"
# Stop immediately if anything goes wrong. Be verbose.
set -e
set -x
# Start by creating a temporary working directory, and ensure it is removed on
# script exit.
tmpdir="$(mktemp -d)"
trap "rm -rf '${tmpdir}'" EXIT
# The remainder of the work occurs inside the tmpdir.
pushd "${tmpdir}"
# In the working directory, create a NEW git repo.
git init .
# Add the upstream remote, fetch it, and determine the current HEAD commit
# of the default branch.
git remote add upstream "${remote}"
git fetch upstream --depth 1
remote_branch="$(git remote show upstream | awk '/HEAD/ {print $3}')"
remote_parent="$(git rev-parse "refs/remotes/upstream/${remote_branch}")"
# Extract the tarball to the working directory and stage all of its contents
# to the git index. Do not commit. We will construct the commit manually.
tar -xzf "${tarball}"
git add -A
# Construct a new commit object with the staged content as the tree, and the
# upstream's default HEAD commit as the parent.
tree=$(git write-tree)
commit=$(git commit-tree "${tree}" -p "${remote_parent}" <<<"Set contents to $(basename "${tarball}")")
# Push the constructed commit to the remote's default branch
git push upstream "${commit}:${remote_branch}"
popd
# The EXIT trap will handle deleting the temporary working directory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment