Skip to content

Instantly share code, notes, and snippets.

@nicnocquee
Created April 27, 2024 15:51
Show Gist options
  • Save nicnocquee/18adc1abaf0f532442b0bb9e410311fc to your computer and use it in GitHub Desktop.
Save nicnocquee/18adc1abaf0f532442b0bb9e410311fc to your computer and use it in GitHub Desktop.
#!/bin/bash
# Check if the correct number of arguments are passed
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <git-url> <path-to-directory> <target-directory>"
exit 1
fi
# Variables from arguments
GIT_URL=$1
DIRECTORY_PATH=$2
TARGET_DIR=$3
# Cleanup function to remove the target directory on failure
cleanup() {
echo "An error occurred. Cleaning up the target directory..."
/bin/rm -rf "$TARGET_DIR"
echo "Cleanup complete."
}
# Cloning the repo into the specified target directory with minimal depth and no tree
git clone -n --depth=1 --filter=tree:0 "$GIT_URL" "$TARGET_DIR"
if [ $? -ne 0 ]; then
echo "Git clone failed."
cleanup
exit 1
fi
# Change directory to the specified target directory
cd "$TARGET_DIR"
if [ $? -ne 0 ]; then
echo "Failed to change directory to $TARGET_DIR"
cleanup
exit 1
fi
# Setup sparse checkout
git sparse-checkout set --no-cone "$DIRECTORY_PATH"
if [ $? -ne 0 ]; then
echo "Sparse-checkout setup failed."
cleanup
exit 1
fi
# Checkout the files
git checkout
if [ $? -ne 0 ]; then
echo "Git checkout failed."
cleanup
exit 1
fi
# Verify the contents of the checkout
if [ -z "$(ls -A $DIRECTORY_PATH)" ]; then
echo "Error: The specified path '$DIRECTORY_PATH' does not exist in the repository."
cleanup
exit 1
fi
echo "Checkout complete. The repository is located in '$TARGET_DIR'."
echo "To enter the directory, use: cd '$TARGET_DIR'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment