Skip to content

Instantly share code, notes, and snippets.

@Olshansk
Created September 25, 2024 22:10
Show Gist options
  • Save Olshansk/da0fc6270b15bb57ad16bbe84fe1e095 to your computer and use it in GitHub Desktop.
Save Olshansk/da0fc6270b15bb57ad16bbe84fe1e095 to your computer and use it in GitHub Desktop.
Git helpers to checkout collaborator branches from the main or forked repos
# Example usage: gcor feature-branch
# This will create a local branch 'feature-branch' based on 'origin/feature-branch'
function gcor {
# Create a new branch locally based on a remote branch from origin
git checkout -b $1 origin/$1
# Set the upstream branch for the new local branch to track the remote branch
git branch --set-upstream-to=origin/$1 $1
}
# Example usage: gcorfork username main
# This will automatically add the forked remote 'username' based on the current repo's URL,
# fetch 'main' from 'username', and create a local branch 'username-main'
function gcorfork() {
# Extract the current repo's URL
repo_url=$(git config --get remote.origin.url)
# Replace the username (between 'github.com/' and the repo name) with the fork's username
fork_url=$(echo $repo_url | sed "s|github.com/[^/]*|github.com/$1|")
# Add the remote for the fork if it doesn't already exist
git remote add $1 $fork_url 2>/dev/null
# Fetch the branch from the forked remote
git fetch $1
# Create a local branch with a hyphen instead of a slash (e.g., 'username-main')
local_branch_name="$1-$2"
git checkout -b $local_branch_name $1/$2
# Set the upstream to track the fork's branch
git branch --set-upstream-to=$1/$2 $local_branch_name
}
@Yoroitchi
Copy link

Clever

@ctsrc
Copy link

ctsrc commented Oct 11, 2024

    # Create a new branch locally based on a remote branch from origin
    git checkout -b $1 origin/$1

    # Set the upstream branch for the new local branch to track the remote branch
    git branch --set-upstream-to=origin/$1 $1

Isn't this the same like doing git checkout origin/$1?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment