Posts tagged with “github”

GitHub CLI Multi-Account Auto-Switcher: Zero-Config Solution

If you juggle work and personal GitHub accounts like I do, constantly checking which account is active before running gh pr create gets old fast. Here's a perfect solution that completely eliminates this friction.

The Problem

Working with multiple GitHub accounts means:

  • Forgetting which account is currently active
  • Getting "No default remote repository" errors
  • Manually running gh auth switch and gh repo set-default
  • Accidentally creating PRs with the wrong account

The Solution

Create a gh wrapper script that automatically detects the current repository's owner, switches to the correct GitHub account, and sets the default repository before executing any command.

Implementation

#!/bin/bash

# Path to original gh binary
ORIGINAL_GH="/usr/local/bin/gh"  # Adjust for your system

# Get current repository's remote URL
remote_url=$(git remote get-url origin 2>/dev/null)

# If not in a git repo, pass through to original gh
if [ $? -ne 0 ]; then
    exec "$ORIGINAL_GH" "$@"
fi

# Extract full repository name (owner/repo) - remove .git suffix
if [[ $remote_url =~ github\.com[:/]([^/]+/[^/]+) ]]; then
    repo_full_name="${BASH_REMATCH[1]}"
    repo_full_name="${repo_full_name%.git}"
    repo_owner=$(echo "$repo_full_name" | cut -d'/' -f1)
else
    exec "$ORIGINAL_GH" "$@"
fi

# Get current active GitHub account
current_user=$("$ORIGINAL_GH" api user --jq '.login' 2>/dev/null)

if [ $? -ne 0 ]; then
    exec "$ORIGINAL_GH" "$@"
fi

# Switch account if needed
if [ "$repo_owner" != "$current_user" ]; then
    echo "→ Repository belongs to $repo_owner, switching from $current_user..." >&2
    "$ORIGINAL_GH" auth switch >/dev/null 2>&1
fi

# Set default repository to avoid "No default remote repository" errors
"$ORIGINAL_GH" repo set-default "$repo_full_name" >/dev/null 2>&1

# Execute original command
exec "$ORIGINAL_GH" "$@"

Setup

  1. Find your original gh path:
which gh
# Use this path in the ORIGINAL_GH variable
  1. Create the wrapper script:
# Save script as ~/.local/bin/gh
chmod +x ~/.local/bin/gh
  1. Adjust PATH priority:
# Add to ~/.bashrc or ~/.zshrc
export PATH="$HOME/.local/bin:$PATH"
  1. Verify setup:
source ~/.bashrc
which gh  # Should show ~/.local/bin/gh

Usage

All GitHub CLI commands now automatically use the correct account:

# In personal repository
gh pr create  # Uses personal account, sets correct default repo

# In work repository  
gh pr create  # Uses work account, sets correct default repo

# All other commands work transparently
gh issue list
gh pr view
gh repo clone username/repo

Advanced: Working with Forks

For forked repositories where you want to view PRs in the upstream repo:

# View your PRs in the upstream repository
gh pr list --author @me --repo upstream-owner/repo-name

# Or temporarily switch to upstream
gh repo set-default upstream-owner/repo-name
gh pr view [PR_NUMBER]

How It Works

  • Extracts repository owner from the current directory's origin remote URL
  • Compares repository owner with currently active GitHub account
  • Automatically runs gh auth switch if accounts don't match
  • Always sets the correct default repository to prevent CLI errors
  • Transparently proxies all other gh commands

Benefits

  • Zero configuration required - works out of the box
  • Zero habit changes needed - still use gh commands normally
  • Eliminates common errors - no more "No default remote repository" messages
  • Multi-account friction eliminated - never think about which account is active again

Perfect for developers who work across multiple GitHub organizations or maintain both work and personal projects.

Quick Tip: Get GitHub PR Diffs Easily

Need to share changes from a GitHub PR (even closed ones)? Just add .diff or .patch to the PR URL:

Original URL:

https://github.com/owner/repo/pull/123

For diff format:

https://github.com/owner/repo/pull/123.diff

For patch format:

https://github.com/owner/repo/pull/123.patch

Both work for open, closed, or merged PRs. Perfect for code reviews, investigations, or sharing changes with others.

For LLM/AI analysis: Use .diff format - it's cleaner and more standardized than .patch which includes extra email headers.

Tired of Git Branch Case Sensitivity? Here's a Fix for Git Bash Users

Hey fellow devs! Here’s a small but super useful Git trick for dealing with that annoying branch case sensitivity issue. You know the drill—someone creates feature/UserAuth, but you type feature/userauth. On a case-sensitive OS, Git tells you the branch doesn’t exist. On a case-insensitive OS like Windows or macOS, it’s worse—you switch to the wrong branch without realizing it. Later, you discover both feature/userauth and feature/UserAuth exist on GitHub. Ouch.

This is particularly painful when working with Windows or macOS, where the filesystem is case-insensitive, but Git isn't. Add in a mix of developers with different habits (some love their CamelCase, others are all-lowercase fans), and you've got yourself a daily annoyance.

The Fix

I wrote a little Git alias that makes checkout case-insensitive. It's basically a smarter version of git checkout that you use as git co. Here's what it does:

$ git co feature/userauth
⚠️ Warning: "feature/userauth" is incorrect. Switching to: "feature/UserAuth"
Switched to branch 'feature/UserAuth'

Nice, right? No more "branch not found" errors just because you got the case wrong!

Important Note ⚠️

This works in:

  • Windows Git Bash (tested and used daily)
  • Should work in macOS/Linux (though I haven't tested it - let me know if you try!)

But it won't work in:

  • Windows CMD
  • Windows PowerShell
  • Any other Windows terminals

Why? Because it uses Bash commands and parameters. But hey, you're using Git Bash anyway, right? 😉

How to Install

Just run this in Git Bash:

git config --global alias.co '!f() {
  # If no args or help flag, show git checkout help
  if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    git checkout --help;
    return;
  fi;
  # If any flags are present (except -q or --quiet), pass through to regular checkout
  if [ $# -gt 1 ] || [[ "$1" == -* && "$1" != "-q" && "$1" != "--quiet" ]]; then
    git checkout "$@";
    return;
  fi;
  # Pass through if argument is a commit reference (HEAD, SHA, tag, etc)
  if [[ "$1" =~ ^HEAD([~^]|@{)[0-9]*$ ]] || # HEAD~1, HEAD^1, HEAD@{1}
     [[ "$1" =~ ^(FETCH_HEAD|ORIG_HEAD|MERGE_HEAD)$ ]] || # Special refs
     [[ -f ".git/refs/tags/$1" ]]; then # Tags
    git checkout "$@";
    return;
  fi;
  # Fetch and prune to ensure we have latest refs
  git fetch --prune --quiet;
  # Check both remote and local branches
  correct_branch=$(git branch -r | sed "s/^  origin\///" | grep -i "^$1$");
  if [ -z "$correct_branch" ]; then
    correct_branch=$(git branch | sed "s/^[* ] //" | grep -i "^$1$");
  fi;
  # If branch found with different case, warn and use correct case
  if [ -n "$correct_branch" ] && [ "$1" != "$correct_branch" ]; then
    echo "⚠️ Warning: \"$1\" is incorrect. Switching to: \"$correct_branch\"";
    git checkout "$correct_branch";
    return;
  fi;
  # Otherwise just pass through to regular checkout
  git checkout "$1";
}; f'

What's Cool About It?

  • Finds your branch regardless of how you type the case
  • Still works normally for everything else (files, creating branches, etc.)
  • Shows you the correct branch name when you get the case wrong
  • Auto-fetches to make sure it sees all remote branches

The best part? If it doesn't recognize what you're trying to do, it just passes everything to regular git checkout. So it won't break any of your normal Git workflows.

Real World Usage

I use this daily in a Windows-heavy dev team where we have branches like:

  • feature/UpdateUser
  • hotfix/FixLoginBug
  • release/v2.0.0

And now I can type them however I want. Life's too short to remember exact branch capitalization!

Give It a Try!

If you're using Git Bash on Windows and tired of case sensitivity issues, give this a shot. It's one of those small tools that just makes your day a tiny bit better.

And hey, if you try this on macOS or Linux, let me know how it goes! Always curious to hear if these tricks work in other environments.

GitHub: Persist "Hide whitespace" preference across PRs

Default 'Hide whitespace' can significantly save your time on reviewing. Many many developers have asked for this feature for a long time, but GitHub still doesn't officially support it. You don't have to wait. This small browser extension GitHub Whitespace comes to rescure!

gh pr view can't find PR just created

TLDR;

The solution is git push -u

David.Wei @ /d/git/xemt-core/dfx - [feature/mt-38546-axo] $ git push -u
branch 'feature/mt-38546-axo' set up to track 'origin/feature/mt-38546-axo'.
Everything up-to-date
David.Wei @ /d/git/xemt-core/dfx - [feature/mt-38546-axo] $ gh pr view
MT-38546 Fintrac API| DFX DB changes #1355
Open • David-Wei_euronet wants to merge 6 commits into integration from feature/mt-38546-axo • about 3 days ago
...

vilmibm wrote the following on this issue and it reminds me why I couldn't find the PR:

gh pr view relies on mapping the current locally checked out branch to a remote tracking branch so that the github host can be queried appropriately for PR data; in your example it seems like you're creating PRs without any configured tracking information, making it impossible for gh to open the PR.

To avoid this issue happening in the future, you can run the following command to enable the auto tracking feature.

git config --global push.autoSetupRemote true

If your git version is lower and couldn't upgrade easily, another measure is to create an alias like the following

git config --global alias.p 'push -u origin HEAD'

Then always use git p instead of git push will do the trick.