How to invite a user to a private github repo within an organisation using the command line

2.4k views Asked by At

I am trying to add users to a private Github repo within an organisation. Starting from this post, I've simply changed the API endpoint to cope with organizations (as explained here), and I end up with the following command:

gh api orgs/MY_ORG/repos/MY_USER_NAME/MY_REPO/collaborators/COLLABORATOR_USER_NAME -f '{"permission":"maintain"}';

This command systematically returns a 404 error (note that I also get a 404 when I just try to check if a user has access to a repo, i.e. the GET version of the above command). I also need to mention that this doesn't seem to be a trivial gh auth login issue since a command like gh repo create MY_ORG/MY_REPO works fine.

Here is also some technical details:

  • os: macosx 10.15.16
  • git: 2.24.3
  • gh: 1.1.0
2

There are 2 answers

2
greg hor On BEST ANSWER

I take the initiative to answer my own question here since after some investigations (thanks to mislav for his help) and trials and errors, I ve found the proper way to add collaborators to a GitHub repo within an organization with the CLI. I think it is worth posting it, hopefully this will help others.

Invite an outside collaborator to a repo within an organization

gh api -X PUT repos/:org/:repo/collaborators/:username -f permission=:perm

the -X PUT specifies that the request is a PUT and not a GET (default request). The repo's identifier is specified by :org/:repo (note that if the repo is not under an organization, the identifier will be :owner/:repo). The :perm argument indicates the type of access, the default value is push (see here)

So assume I want to provide admin access to jonsnow to the repo winterfell under the organization got, I will use the following command

gh api -X PUT repos/got/winterfell/collaborators/jonsnow -f permission=admin

Note that if you send an invite for the repo directly, the user will appear as an outside collaborator (not as an organization member)

Add a member to the organization and invite him to a repo

You just need to include the user as a member to the organisation beforehand with

gh api -X PUT /orgs/:org/memberships/:username -f role=:role

and then you can provide him access to a specific repo with the same command as above, i.e.

gh api -X PUT repos/:org/:repo/collaborators/:username -f permission=:perm

Note that the value for the various :role can be found here

2
VonC On

You can set organization membership for a user

put /orgs/{org}/memberships/{username}

You can add a collaborator to a repo

put /repos/{owner}/{repo}/collaborators/{username}

But I don't think you can combine the two (add a collaborator to an org repo)

That is because that collaborator need to be a member of the organisation first (so receive and accept the invitation), before being added to a repository.