-
Notifications
You must be signed in to change notification settings - Fork 1
/
gh-labels
executable file
·78 lines (64 loc) · 2.42 KB
/
gh-labels
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
# Author: github.com/danielhoherd
# License: MIT
"""Export and import Github repository labels."""
import github # PyGithub
import typer
import yaml
app = typer.Typer(help=__doc__)
keepers = ("name", "color", "description")
def get_repo(repo: str, github_token: str) -> github.Repository.Repository:
try:
gh = github.Github(login_or_token=github_token)
gh.per_page = 100
repo = gh.get_repo(repo)
except github.GithubException as e:
if e.status == 404:
typer.echo(f"Repo {repo} not found!")
raise typer.Exit(1)
raise
return repo
@app.command()
def get(
repo: str,
filename: str = typer.Option("labels.yaml", "--filename", "-f"),
github_token: str = typer.Option(None, envvar="GITHUB_TOKEN"),
):
"""Dump labels from the given repo to a YAML file."""
gh_repo = get_repo(repo, github_token)
print(f"Copying labels from {gh_repo.html_url}/labels")
repo_labels = list(gh_repo.get_labels())
labels = [{key: label._rawData.get(key) if label._rawData.get(key) else "" for key in keepers} for label in repo_labels]
with open(filename, "w") as f:
f.write(yaml.safe_dump(labels, default_flow_style=False))
print(f"Wrote output to {filename}")
@app.command()
def apply(
repo: str,
filename: str = typer.Option("labels.yaml", "--filename", "-f"),
github_token: str = typer.Option(None, envvar="GITHUB_TOKEN"),
):
"""Apply labels in the given YAML file to the given repo."""
try:
with open(filename) as f:
labels = yaml.safe_load(f)
except FileNotFoundError:
typer.echo(f"File {filename} not found!")
raise typer.Exit(1)
gh_repo = get_repo(repo, github_token)
print(f"Applying labels to {gh_repo.html_url}/labels")
for label in labels:
if label["description"] is None:
label["description"] = ""
try:
existing_label = gh_repo.get_label(label["name"])
existing_label.edit(name=label["name"], color=label["color"], description=label["description"])
print(f"Edited label {label}")
except github.GithubException as e:
if e.status == 404:
gh_repo.create_label(name=label["name"], color=label["color"], description=label["description"])
print(f"Created label {label}")
else:
raise
if __name__ == "__main__":
app()