Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
name: settings
description: settings
inputs:
collaborators:
default: ""
description: |
Comma-separated list of 'username:permission' to grant access to the
repository, e.g. alice:push,bob:admin. Permission is one of pull,
triage, push, maintain or admin. Additive only: access that is not
listed is not removed. Empty leaves collaborators unchanged.
required: false
debug:
default: "false"
description: |
Expand Down Expand Up @@ -108,6 +116,15 @@ inputs:
description: |
Whether the wiki tab should be disabled or enabled.
required: true
teams:
default: ""
description: |
Comma-separated list of 'team-slug:permission' to grant teams of the
organization that owns the repository access to it, e.g.
maintainers:maintain. Permission is one of pull, triage, push,
maintain or admin. Additive only: access that is not listed is not
removed. Empty leaves team access unchanged.
required: false
topics:
description: |
At least one topic have to be set.
Expand Down Expand Up @@ -289,6 +306,39 @@ runs:
done
gh repo edit "$PROJECT" "${args[@]}"

# https://docs.github.com/en/rest/collaborators/collaborators?apiVersion=2022-11-28#add-a-repository-collaborator
# https://docs.github.com/en/rest/teams/teams?apiVersion=2022-11-28#add-or-update-team-repository-permissions
- name: grant collaborators and teams access to ${{ inputs.project }}
shell: bash
env:
PROJECT: ${{ inputs.project }}
ACTION_PATH: ${{ github.action_path }}
COLLABORATORS: ${{ inputs.collaborators }}
TEAMS: ${{ inputs.teams }}
run: |
# Validate every entry before granting anything, so a typo fails the
# step without a partial update.
entries=$("$RUNNER_TEMP/settings-action-venv/bin/python" "$ACTION_PATH/main.py" access \
--collaborators "$COLLABORATORS" \
--teams "$TEAMS")

org="${PROJECT%%/*}"
while read -r kind name permission; do
case "$kind" in
collaborator)
echo "grant ${name} '${permission}' on ${PROJECT}"
gh api --silent -X PUT "repos/${PROJECT}/collaborators/${name}" \
-f permission="$permission"
;;
team)
echo "grant team ${org}/${name} '${permission}' on ${PROJECT}"
gh api --silent -X PUT "orgs/${org}/teams/${name}/repos/${PROJECT}" \
-f permission="$permission"
;;
esac
done <<< "$entries"
if: ${{ inputs.collaborators != '' || inputs.teams != '' }}

- name: protect main branch
shell: bash
env:
Expand Down
21 changes: 21 additions & 0 deletions docs/inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ The inputs of the action, as used in the

| Option | Description |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| collaborators | Comma-separated `username:permission` list to grant access, e.g. `alice:push,bob:admin`. See [Access](#access) |
| debug | Enable debug logging |
| description | Change the description of a GitHub repository |
| project | The owner/repo |
Expand All @@ -25,4 +26,24 @@ The inputs of the action, as used in the
| settings_protect_main_branch_required_approving_review_count | The number of approvals that is required before a PR can be merged |
| settings_projects | Whether the project tab should be enabled |
| settings_wiki | Wiki enabled or not |
| teams | Comma-separated `team-slug:permission` list of teams in the owner's organization, e.g. `maintainers:maintain`. See [Access](#access) |
| topics | The topic(s) that will appear in the about menu of a project |

## Access

`collaborators` and `teams` grant access to the repository. The permission is
one of `pull`, `triage`, `push`, `maintain` or `admin`; any other value, or an
entry that is not `name:permission`, fails the step before anything is
granted. Leave both empty to skip the step.

- A user who is not a collaborator yet gets an invitation.
- `teams` takes team slugs of the organization that owns the repository, so it
does not work for repositories owned by a user.
- The token needs admin on the repository and, for `teams`, permission to
manage the team in the organization (organization owner or team
maintainer).

Access is additive only, by design: a collaborator or team that is not listed
keeps its access. Removing unlisted access would undo every grant made in the
GitHub UI and could lock people out after a typo, so revoking access stays a
manual step.
58 changes: 58 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import json
import re

import click

PERMISSIONS = ("pull", "triage", "push", "maintain", "admin")
# GitHub usernames: letters, digits and single hyphens. Team slugs: lowercase
# letters, digits, hyphens and underscores. Both end up in an API path, so
# nothing else is let through.
USERNAME = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$")
TEAM_SLUG = re.compile(r"^[a-z0-9][a-z0-9_-]*$")


@click.group()
def cli():
Expand Down Expand Up @@ -86,5 +95,54 @@ def actions_permissions(
json.dump(selected_data, f, indent=2)


def parse_access(value, name_pattern, option):
"""Parse 'name:permission,...' into (name, permission) pairs."""
entries = []
for entry in value.split(","):
entry = entry.strip()
if not entry:
continue
name, sep, permission = entry.partition(":")
if not sep or not name_pattern.match(name):
raise click.BadParameter(
f"'{entry}' is not 'name:permission'", param_hint=option
)
if permission not in PERMISSIONS:
raise click.BadParameter(
f"'{entry}' has permission '{permission}', expected one of "
f"{', '.join(PERMISSIONS)}",
param_hint=option,
)
entries.append((name, permission))
return entries


@cli.command()
@click.option(
"--collaborators",
default="",
help="comma-separated list, e.g. alice:push,bob:admin",
)
@click.option(
"--teams",
default="",
help="comma-separated list, e.g. maintainers:maintain",
)
def access(collaborators, teams):
"""Validate the access inputs and print one 'kind name permission' line
per entry, for action.yml to turn into API calls."""
lines = [
f"collaborator {name} {permission}"
for name, permission in parse_access(
collaborators, USERNAME, "'--collaborators'"
)
] + [
f"team {name} {permission}"
for name, permission in parse_access(teams, TEAM_SLUG, "'--teams'")
]
for line in lines:
click.echo(line)


if __name__ == "__main__":
cli()
64 changes: 64 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,67 @@ def test_actions_permissions_rejects_invalid_allowed_actions(
)

assert result.exit_code != 0


def test_access_prints_collaborators_and_teams():
runner = CliRunner()

result = runner.invoke(
cli,
[
"access",
"--collaborators",
"alice:push, bob-2:admin,",
"--teams",
"maintainers:maintain,ci_bots:triage",
],
)

assert result.exit_code == 0
assert result.output.splitlines() == [
"collaborator alice push",
"collaborator bob-2 admin",
"team maintainers maintain",
"team ci_bots triage",
]


def test_access_empty_inputs_print_nothing():
runner = CliRunner()

result = runner.invoke(cli, ["access"])

assert result.exit_code == 0
assert result.output == ""


def test_access_rejects_unknown_permission():
runner = CliRunner()

result = runner.invoke(cli, ["access", "--collaborators", "alice:write"])

assert result.exit_code != 0
assert "permission 'write'" in result.output


def test_access_rejects_entry_without_permission():
runner = CliRunner()

result = runner.invoke(cli, ["access", "--teams", "maintainers"])

assert result.exit_code != 0
assert "'maintainers' is not 'name:permission'" in result.output


def test_access_rejects_names_that_are_not_a_single_path_segment():
runner = CliRunner()

for option, value in [
("--collaborators", "../alice:push"),
("--collaborators", "al ice:push"),
("--teams", "030/maintainers:maintain"),
("--teams", "Maintainers:maintain"),
]:
result = runner.invoke(cli, ["access", option, value])

assert result.exit_code != 0, value
Loading