Skip to content

Commit

Permalink
support passing access token via cli
Browse files Browse the repository at this point in the history
  • Loading branch information
villebro committed May 27, 2022
1 parent 647b7ac commit a969ba8
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 36 deletions.
17 changes: 5 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,37 +74,30 @@ Usage: cherrytree bake [OPTIONS] RELEASE_BRANCH
Options:
-t, --target-branch TEXT target branch for baking. Leave empty for
dry run
-m, --main_branch TEXT name of branch containing cherries, usually
`master` or `main`
-r, --repo TEXT The name of the main repo. Example:
apache/superset [required]
-l, --label TEXT Name of label to use for cherry picking.
Supports multiple labels, e.g. `-l Label1 -l
Label2`
-b, --blocking-label TEXT Name of labels to block cherry picking
operation. Supports multiple labels, e.g.
`-b Blocker1 -b Blocker2`
-pr, --pull-request TEXT Pull request id to add to list of cherries
to pick. Supports multiple ids, e.g. `-pr
1234 -pr 5678`
-nd, --no-dryrun Should cherries be committed to target
branch [default: False]
branch
-e, --error-mode [break|dryrun|skip]
What to do in case of an error. `skip` skips
conflicted cherries, `dryrun` reverts to
dryrun for subsequent prs and `break` stops
cherry picking. [default: skip]
-f, --force-rebuild-target Forcefully remove target branch before
applying cherries. Only relevant when using
`--target-branch` [default: False]
`--target-branch`
-at, --access-token TEXT GitHub access token. If left undefined, will
use the GITHUB_TOKEN environment variable
--help Show this message and exit.
```
```
17 changes: 14 additions & 3 deletions cherrytree/bin/cherrytree
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python
import os
import sys
from typing import Tuple, List
from typing import Tuple, List, Optional

import click

Expand Down Expand Up @@ -31,7 +31,6 @@ def cli():
"--repo",
"-r",
help='The name of the main repo. Example: apache/superset',
show_default=True,
required=True,
)
@click.option(
Expand All @@ -57,6 +56,7 @@ def cli():
is_flag=True,
help="Should cherries be committed to target branch",
show_default=True,
default=False,
)
@click.option(
"--error-mode",
Expand All @@ -69,11 +69,20 @@ def cli():
show_default=True,
)
@click.option(
"--force-rebuild-target", "-f",
"--force-rebuild-target",
"-f",
is_flag=True,
help="Forcefully remove target branch before applying cherries. Only relevant "
"when using `--target-branch`",
show_default=True,
default=False,
)
@click.option(
"--access-token",
"-at",
multiple=False,
help="GitHub access token. If left undefined, will use the GITHUB_TOKEN "
"environment variable",
)
def bake(
release_branch: str,
Expand All @@ -86,6 +95,7 @@ def bake(
no_dryrun: bool,
error_mode: str,
force_rebuild_target: bool,
access_token: Optional[str],
):
"""Applies cherries to release"""
if no_dryrun:
Expand Down Expand Up @@ -133,6 +143,7 @@ def bake(
labels=list(label),
blocking_labels=list(blocking_label),
pull_requests=pull_requests,
access_token=access_token,
)
cherry_tree.apply_cherries(
target_branch=target_branch,
Expand Down
36 changes: 29 additions & 7 deletions cherrytree/branch.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from cherrytree.github_utils import (
commit_pr_number,
deduplicate_prs,
get_access_token,
get_issue,
get_issues_from_labels,
git_get_current_head,
Expand Down Expand Up @@ -48,6 +49,7 @@ def __init__(
labels: List[str],
blocking_labels: List[str],
pull_requests: List[int],
access_token: Optional[str],
):
self.repo = repo
self.labels = labels
Expand All @@ -59,6 +61,13 @@ def __init__(
self.git_repo = get_git_repo()
self.base_ref = self.get_base()
self.blocking_pr_ids = []
try:
self.access_token = get_access_token(access_token)
except NotImplementedError:
click.secho(
f"No access token provided. Either provide one via the --access-token "
f"parameter, or set the GITHUB_TOKEN env variable", fg="red")
exit(1)

click.secho(f"Base ref is {self.base_ref}", fg="cyan")

Expand All @@ -84,21 +93,34 @@ def __init__(
prs: List[Issue] = []
for label in self.labels:
click.secho(f'Fetching labeled PRs: "{label}"', fg="cyan", nl=False)
new_prs = get_issues_from_labels(self.repo, label, prs_only=True)
new_prs = get_issues_from_labels(
repo=self.repo,
access_token=self.access_token,
label=label,
prs_only=True,
)
click.secho(f' ({len(new_prs)} labels found)', fg="cyan")
prs += new_prs

for pull_request in pull_requests:
prs.append(get_issue(self.repo, pull_request))
prs.append(get_issue(self.repo, self.access_token, pull_request))
prs = deduplicate_prs(prs)

# add all PRs that are flagged as blocking
for label in self.blocking_labels:
click.secho(f'Fetching labeled PRs: "{label}"', fg="cyan", nl=False)
new_prs = get_issues_from_labels(self.repo, label, prs_only=True)
click.secho(f' ({len(new_prs)} labels found)', fg="cyan")
self.blocking_pr_ids += [pr.number for pr in new_prs]
prs += new_prs
click.secho(
f'Fetching labeled PRs marked as blocking: "{label}"',
fg="cyan",
nl=False,
)
blocking_prs = get_issues_from_labels(
repo=self.repo,
access_token=self.access_token,
label=label,
prs_only=True,
)
click.secho(f' ({len(blocking_prs)} blocking labels found)', fg="cyan")
self.blocking_pr_ids += [pr.number for pr in blocking_prs]
prs = deduplicate_prs(prs)
now = datetime.now()
prs.sort(
Expand Down
39 changes: 26 additions & 13 deletions cherrytree/github_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,34 @@
PR_REGEX = re.compile(r"(^Merge pull request #(\d+) from|\(#(\d+)\)$)")


def get_github_instance() -> Github:
token = os.environ.get("GITHUB_TOKEN")
if not token:
raise Exception("Env var 'GITHUB_TOKEN' is missing")
return Github(token)
def get_github_instance(access_token: str) -> Github:
return Github(access_token)


def get_repo(repo: str) -> Repository:
g = get_github_instance()
def get_access_token(access_token: Optional[str]) -> str:
if access_token:
return access_token

access_token = os.environ.get("GITHUB_TOKEN")
if not access_token:
raise NotImplementedError("Env var 'GITHUB_TOKEN' is missing")

return access_token


def get_repo(repo: str, access_token: str) -> Repository:
g = get_github_instance(access_token)
return g.get_repo(repo)


def get_issues_from_labels(repo: str, label: str, prs_only: bool = False) -> List[Issue]:
def get_issues_from_labels(
repo: str,
access_token: str,
label: str,
prs_only: bool = False,
) -> List[Issue]:
label_objects: List[Label] = []
gh_repo = get_repo(repo)
gh_repo = get_repo(repo, access_token)
try:
label_objects.append(gh_repo.get_label(label))
except UnknownObjectException:
Expand All @@ -45,18 +58,18 @@ def get_issues_from_labels(repo: str, label: str, prs_only: bool = False) -> Lis
return [o for o in issues]


def get_issue(repo: str, id_: int) -> Optional[Issue]:
gh_repo = get_repo(repo)
def get_issue(repo: str, access_token: str, id_: int) -> Optional[Issue]:
gh_repo = get_repo(repo, access_token)
try:
return gh_repo.get_issue(id_)
except UnknownObjectException:
# unknown id
return None


def get_commits(repo: str, branch: str, since=None):
def get_commits(repo: str, access_token: str, branch: str, since=None):
"""Get commit objects from a branch, over a limited period"""
gh_repo = get_repo(repo)
gh_repo = get_repo(repo, access_token)
branch_object = gh_repo.get_branch(branch)
sha = branch_object.commit.sha
if since:
Expand Down
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ def get_git_sha():
'python-dateutil',
'GitPython',
'delegator.py',
'pyhocon',
'pyyaml',
'yaspin',
],
Expand Down

0 comments on commit a969ba8

Please sign in to comment.