DEV Community

vast cow
vast cow

Posted on Edited on

Using Multiple GitHub Accounts: Automatically Select the Correct `gh` PAT Based on Repo Owner

Using Multiple GitHub Accounts: Automatically Select the Correct `gh` PAT Based on Repo Owner | vast-cow's blog

When using multiple GitHub accounts, the process of selecting the correct Personal Access Token (PAT)...

favicon vast-cow.github.io

Top comments (3)

Collapse
 
vast-cow profile image
vast cow •

For those who want to map owners and repository names, please refer to this.

[credential "https://github.com/"]
    helper =
    helper = "!f() { \
        [ \"$1\" = get ] || exit 0; \
        path=''; \
        while IFS='=' read -r k v; do \
            [ \"$k\" = path ] && path=$v; \
        done; \
        [ -n \"$path\" ] || exit 0; \
        owner=${path%%/*}; \
        repo=${path#*/}; \
        repo=${repo%.git}; \
        case \"$owner/$repo\" in \
            my-org/special-repo) account='special-account' ;; \
            *) \
                case \"$owner\" in \
                    my-org) account='my-work-account' ;; \
                    another-org) account='another-account' ;; \
                    *) account=\"$owner\" ;; \
                esac \
                ;; \
        esac; \
        token=$(gh auth token --user \"$account\") || exit 0; \
        printf 'username=%s\\npassword=%s\\n' \"$account\" \"$token\"; \
    }; f"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mrdgh2821 profile image
Mihir Rabade •

What about repos in an organization?

Collapse
 
vast-cow profile image
vast cow •

Good question! For organization-owned repositories, you can add an explicit owner-to-account mapping with a case statement.

For example, the helper could be extended like this:

[credential "https://github.com/"]
    helper =
    helper = "!f() { \
        [ \"$1\" = get ] || exit 0; \
        owner=''; \
        while IFS='=' read -r k v; do \
            [ \"$k\" = path ] && owner=${v%%/*}; \
        done; \
        [ -n \"$owner\" ] || exit 0; \
        case \"$owner\" in \
            my-org) account='my-work-account' ;; \
            another-org) account='another-account' ;; \
            *) account=\"$owner\" ;; \
        esac; \
        token=$(gh auth token --user \"$account\") || exit 0; \
        printf 'username=%s\\npassword=%s\\n' \"$account\" \"$token\"; \
    }; f"
Enter fullscreen mode Exit fullscreen mode

So, for example:

github.com/my-org/foo
        ↓
owner = my-org
        ↓
account = my-work-account
        ↓
gh auth token --user my-work-account
Enter fullscreen mode Exit fullscreen mode

For personal repositories that aren't explicitly mapped, the *) account="$owner" ;; fallback preserves the original behavior.

This is probably the simplest way to support organization-owned repositories while keeping the helper self-contained in .gitconfig.