Skip to content

Instantly share code, notes, and snippets.

@thoroc
Created October 1, 2024 08:04
Show Gist options
  • Save thoroc/3052f4e9f00f6a355e524bab37553669 to your computer and use it in GitHub Desktop.
Save thoroc/3052f4e9f00f6a355e524bab37553669 to your computer and use it in GitHub Desktop.
Git checkout repository, reproducing the path of the origin locally
#!/bin/bash
# put an alias in your .gitconfig to where the script lives: co-repo = ~/.bin/git-checkout-repo.sh
# don't forget to `chmod +x` it
# Input Git repository URL
REPO_URL="$1"
# Define the target base directory (where all projects should reside)
TARGET_BASE_DIR=~/Projects
# Expand the tilde (~) to the full home directory path
TARGET_BASE_DIR=$(eval echo "$TARGET_BASE_DIR")
# Get the current working directory
CURRENT_DIR=$(pwd)
# Security check: Ensure we are in or under ~/Projects
if [[ "$CURRENT_DIR" != "$TARGET_BASE_DIR"* ]]; then
echo "Error: You must be within the '$TARGET_BASE_DIR' directory to run this script."
exit 1
fi
# Extract the host (source) and the full path from the repository URL
# Handle both SSH ([email protected]:owner/repo) and HTTPS (https://github.com/owner/repo)
if [[ "$REPO_URL" =~ ^git@ ]]; then
# SSH URL: [email protected]:owner/repo.git -> Extract host and path
HOST=$(echo "$REPO_URL" | sed -E 's|git@([^:]+):.*|\1|')
FULL_PATH=$(echo "$REPO_URL" | sed -E 's|git@[^:]+:||' | sed -E 's|\.git$||')
else
# HTTPS URL: https://github.com/owner/repo.git -> Extract host and path
HOST=$(echo "$REPO_URL" | sed -E 's|https?://([^/]+)/.*|\1|')
FULL_PATH=$(echo "$REPO_URL" | sed -E 's|https?://[^/]+/||' | sed -E 's|\.git$||')
fi
# Remove the top-level domain (e.g., .com, .org) from the host
HOST=$(echo "$HOST" | sed -E 's|\.[a-z]+$||')
# Create the directory structure: ~/Projects/host/owner/repo
TARGET_PATH="$TARGET_BASE_DIR/$HOST/$FULL_PATH"
# Identify the common path between the current working directory and the desired target directory
COMMON_PATH=$(echo "$TARGET_PATH" | grep -o "^$(basename "$CURRENT_DIR")")
# If the current working directory contains a part of the path, exclude the common part
if [[ -n "$COMMON_PATH" ]]; then
# Strip the common part from the full path
REMAINING_PATH=${TARGET_PATH#$COMMON_PATH/}
else
# If no common part, the remaining path is the full path
REMAINING_PATH="$TARGET_PATH"
fi
# Ensure the remaining path is not empty
if [[ -z "$REMAINING_PATH" ]]; then
echo "You're already in the target directory."
exit 0
fi
# Create the missing directories
mkdir -p "$REMAINING_PATH"
# Change to the target directory
cd "$REMAINING_PATH" || exit
# Clone the repository into the current directory
git clone "$REPO_URL" .
echo "Repository cloned into $(pwd)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment