Skip to content

Commit 8180a51

Browse files
✨ ENH: Auto-detecting the target (#45)
Co-authored-by: Erik Sundell <erik.i.sundell@gmail.com>
1 parent ca97183 commit 8180a51

File tree

12 files changed

+182
-57
lines changed

12 files changed

+182
-57
lines changed

.github/workflows/tests.yaml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@ jobs:
1919
run: |
2020
python -m pip install --upgrade pip
2121
pip install -e .[testing]
22-
# CURRENTLY NOT TESTING because it throws an API token error
23-
# - name: Run tests
24-
# run: pytest
22+
- name: Run tests
23+
env:
24+
GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
25+
run: pytest
2526

2627
docs:
2728

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ The easiest way to use `github-activity` to generate activity markdown is to use
2626
the command-line interface. It takes the following form:
2727

2828
```
29-
github-activity <org>/<repo> --since <date or ref> --until <date or ref>
29+
github-activity [<org>/<repo>] --since <date or ref> --until <date or ref>
3030
```
3131

3232
See [the github-activity documentation](https://github-activity.readthedocs.io)

docs/index.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,12 @@ The easiest way to use `github-activity` to generate activity markdown is to use
2828
the command-line interface. It takes the following form:
2929

3030
```
31-
github-activity <org>/<repo> --since <date or ref> --until <date or ref>
31+
github-activity [<org>/<repo>] --since <date or ref> --until <date or ref>
3232
```
3333

34+
The `[<org>/<repo>]` argument is **optional**.
35+
If you do not give it, then `github-activity` will attempt to infer this value by running `git remote -v` and using either `upstream` or `origin` (preferring `upstream` if both are available).
36+
3437
The (optional) arguments in `--since` (or `-s`) and `--until` (or `-u`) can either be
3538
a date, or a ref (such as a commit hash or tag). `github-activity` will pull the activity
3639
between the dates corresponding to these values.

github_activity/cli.py

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,24 @@
11
import argparse
22
import os
33
import sys
4+
from subprocess import run, PIPE
45

5-
from .github_activity import generate_activity_md
6+
from .github_activity import generate_activity_md, _parse_target
67
from .git import _git_installed_check
78

89
DESCRIPTION = "Generate a markdown changelog of GitHub activity within a date window."
910
parser = argparse.ArgumentParser(description=DESCRIPTION)
1011
parser.add_argument(
11-
"target",
12+
"-t",
13+
"--target",
14+
nargs="?",
15+
default=None,
1216
help="""The GitHub organization/repo for which you want to grab recent issues/PRs.
1317
Can either be *just* an organization (e.g., `jupyter`), or a combination
1418
organization and repo (e.g., `jupyter/notebook`). If the former, all
1519
repositories for that org will be used. If the latter, only the specified
16-
repository will be used. Can also be a GitHub URL to an organization or repo.""",
20+
repository will be used. Can also be a GitHub URL to an organization or repo. If
21+
None, the org/repo will attempt to be inferred from `git remote -v`.""",
1722
)
1823
parser.add_argument(
1924
"-s",
@@ -100,9 +105,7 @@
100105
"--branch",
101106
"-b",
102107
default=None,
103-
help=(
104-
"""The branch or reference name to filter pull requests by"""
105-
),
108+
help=("""The branch or reference name to filter pull requests by"""),
106109
)
107110

108111

@@ -111,8 +114,41 @@ def main():
111114
print("git is required to run github-activity", file=sys.stderr)
112115
sys.exit(1)
113116

114-
args = parser.parse_args(sys.argv[1:])
117+
args, unknown = parser.parse_known_args()
118+
# If we have unknown, it is the target
119+
# TODO: this feels sub-optimal, we should be able to just treat positional args
120+
# as optional.
121+
if unknown and not args.target:
122+
args.target = unknown[0]
123+
115124
tags = args.tags.split(",") if args.tags is not None else args.tags
125+
# Automatically detect the target from remotes if we haven't had one passed.
126+
if not args.target:
127+
err = "Could not automatically detect remote, and none was given."
128+
try:
129+
out = run("git remote -v".split(), stdout=PIPE)
130+
remotes = out.stdout.decode().split("\n")
131+
remotes = [ii for ii in remotes if ii]
132+
remotes = {
133+
ii.split("\t")[0]: ii.split("\t")[1].split()[0] for ii in remotes
134+
}
135+
if "upstream" in remotes:
136+
ref = remotes["upstream"]
137+
elif "origin" in remotes:
138+
ref = remotes["origin"]
139+
else:
140+
ref = None
141+
if not ref:
142+
raise ValueError(err)
143+
144+
org, repo = _parse_target(ref)
145+
if repo:
146+
args.target = f"{org}/{repo}"
147+
else:
148+
args.target = f"{org}"
149+
except Exception:
150+
raise ValueError(err)
151+
116152
md = generate_activity_md(
117153
args.target,
118154
since=args.since,
@@ -124,7 +160,7 @@ def main():
124160
include_opened=bool(args.include_opened),
125161
strip_brackets=bool(args.strip_brackets),
126162
heading_level=args.heading_level,
127-
branch=args.branch
163+
branch=args.branch,
128164
)
129165
if not md:
130166
return

github_activity/git.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import subprocess
22

3+
34
def _git_installed_check():
45
cmd = ["git", "--help"]
56
try:

github_activity/github_activity.py

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import sys
77
import urllib
88
from pathlib import Path
9+
from subprocess import run, PIPE
910

1011
from .graphql import GitHubGraphQlQuery
1112
from .cache import _cache_data
@@ -22,7 +23,7 @@
2223
},
2324
"enhancement": {
2425
"tags": ["enhancement", "enhancements"],
25-
"pre": ["NEW", "ENH", "ENHANCEMENT", "IMPROVE"],
26+
"pre": ["ENH", "ENHANCEMENT", "IMPROVE", "IMP"],
2627
"description": "Enhancements made",
2728
},
2829
"bug": {
@@ -149,7 +150,7 @@ def generate_activity_md(
149150
include_opened=False,
150151
strip_brackets=False,
151152
heading_level=1,
152-
branch=None
153+
branch=None,
153154
):
154155
"""Generate a markdown changelog of GitHub activity within a date window.
155156
@@ -258,7 +259,9 @@ def generate_activity_md(
258259

259260
# Filter the PRs by branch (or ref) if given
260261
if branch is not None:
261-
index_names = data[ (data["kind"] == "pr") & (data["baseRefName"] != branch)].index
262+
index_names = data[
263+
(data["kind"] == "pr") & (data["baseRefName"] != branch)
264+
].index
262265
data.drop(index_names, inplace=True)
263266
if data.empty:
264267
return
@@ -410,7 +413,11 @@ def generate_activity_md(
410413
changelog_url = f"https://github.com/{org}/{repo}/compare/{since_ref}...{until_ref}"
411414

412415
# Build the Markdown
413-
md = [f"{extra_head}# {since}...{until}", "", f"([full changelog]({changelog_url}))"]
416+
md = [
417+
f"{extra_head}# {since}...{until}",
418+
"",
419+
f"([full changelog]({changelog_url}))",
420+
]
414421
for kind, info in prs.items():
415422
if len(info["md"]) > 0:
416423
md += [""]
@@ -480,8 +487,21 @@ def extract_comments(comments):
480487

481488

482489
def _parse_target(target):
490+
"""
491+
Returns (org, repo) based on input such as:
492+
493+
- executablebooks
494+
- executablebooks/jupyter-book
495+
- http(s)://github.com/executablebooks
496+
- http(s)://github.com/executablebooks/jupyter-book(.git)
497+
- git@github.com:executablebooks/jupyter-book(.git)
498+
"""
483499
if target.startswith("http"):
484500
target = target.split("github.com/")[-1]
501+
elif "@github.com:" in target:
502+
target = target.split("@github.com:")[-1]
503+
if target.endswith(".git"):
504+
target = target.rsplit(".git", 1)[0]
485505
parts = target.split("/")
486506
if len(parts) == 2:
487507
org, repo = parts
@@ -530,8 +550,6 @@ def _get_datetime_from_git_ref(org, repo, ref):
530550

531551
def _get_latest_tag(org, repo):
532552
"""Return the latest tag name for a given repository."""
533-
response = requests.get(f"https://api.github.com/repos/{org}/{repo}/git/refs/tags")
534-
response.raise_for_status()
535-
tags = response.json()
536-
latest_tag = list(tags)[-1]
537-
return latest_tag["ref"].split("/tags/")[-1]
553+
out = run("git describe --tags".split(), stdout=PIPE)
554+
tag = out.stdout.decode().rsplit("-", 2)[0]
555+
return tag

tests/test_cli.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44

55
def test_cli(tmpdir, file_regression):
6+
"""The output of all file_regressions should be the same, testing diff opts."""
67
path_tmp = Path(tmpdir)
78
path_output = path_tmp.joinpath("out.md")
89

@@ -11,29 +12,36 @@ def test_cli(tmpdir, file_regression):
1112

1213
# CLI with URL
1314
cmd = f"github-activity {url} -s 2019-09-01 -u 2019-11-01 -o {path_output}"
14-
out = run(cmd.split(), check=True)
15+
run(cmd.split(), check=True)
1516
md = path_output.read_text()
16-
file_regression.check(md, extension=".md")
17+
file_regression.check(md, basename="cli_w_url", extension=".md")
1718

1819
# CLI with parts
1920
cmd = f"github-activity {org}/{repo} -s 2019-09-01 -u 2019-11-01 -o {path_output}"
20-
out = run(cmd.split(), check=True)
21+
run(cmd.split(), check=True)
2122
md = path_output.read_text()
22-
file_regression.check(md, extension=".md")
23+
file_regression.check(md, basename="cli_w_parts", extension=".md")
2324

2425
# CLI with default branch
2526
cmd = f"github-activity {org}/{repo} -s 2019-09-01 -u 2019-11-01 -o {path_output} -b master"
26-
out = run(cmd.split(), check=True)
27+
run(cmd.split(), check=True)
2728
md = path_output.read_text()
28-
file_regression.check(md, extension=".md")
29+
file_regression.check(md, basename="cli_def_branch", extension=".md")
2930

3031
# CLI with non-existent branch
3132
cmd = f"github-activity {org}/{repo} -s 2019-09-01 -u 2019-11-01 -o {path_output} -b foo"
32-
out = run(cmd.split(), check=True)
33+
run(cmd.split(), check=True)
3334
md = path_output.read_text()
3435
assert "Contributors to this release" in md
3536
assert "Merged PRs" not in md
3637

38+
# CLI with no target
39+
cmd = f"github-activity -s 2019-09-01 -u 2019-11-01 -o {path_output}"
40+
run(cmd.split(), check=True)
41+
md = path_output.read_text()
42+
file_regression.check(md, basename="cli_no_target", extension=".md")
43+
44+
3745
def test_pr_split(tmpdir, file_regression):
3846
"""Test that PRs are properly split by tags/prefixes."""
3947
path_tmp = Path(tmpdir)
@@ -43,7 +51,7 @@ def test_pr_split(tmpdir, file_regression):
4351

4452
# This release range covers some PRs with tags, and some with prefixes
4553
cmd = f"github-activity {url} -s v0.7.1 -u v0.7.3 -o {path_output}"
46-
out = run(cmd.split(), check=True)
54+
run(cmd.split(), check=True)
4755
md = path_output.read_text()
4856
md = md.split("## Contributors to this release")[0]
4957
file_regression.check(md, extension=".md")
Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@
44

55
## Merged PRs
66

7-
* defining contributions [#14](https://github.com/executablebooks/github-activity/pull/14) ([@choldgraf](https://github.com/choldgraf))
8-
* updating CLI for new tags [#12](https://github.com/executablebooks/github-activity/pull/12) ([@choldgraf](https://github.com/choldgraf))
9-
* fixing link to changelog with refs [#11](https://github.com/executablebooks/github-activity/pull/11) ([@choldgraf](https://github.com/choldgraf))
10-
* adding contributors list [#10](https://github.com/executablebooks/github-activity/pull/10) ([@choldgraf](https://github.com/choldgraf))
11-
* some improvements to `since` and opened issues list [#8](https://github.com/executablebooks/github-activity/pull/8) ([@choldgraf](https://github.com/choldgraf))
12-
* Support git references etc. [#6](https://github.com/executablebooks/github-activity/pull/6) ([@consideRatio](https://github.com/consideRatio))
13-
* adding authentication information [#2](https://github.com/executablebooks/github-activity/pull/2) ([@choldgraf](https://github.com/choldgraf))
14-
* Mention the required GITHUB_ACCESS_TOKEN [#1](https://github.com/executablebooks/github-activity/pull/1) ([@consideRatio](https://github.com/consideRatio))
7+
- defining contributions [#14](https://github.com/executablebooks/github-activity/pull/14) ([@choldgraf](https://github.com/choldgraf))
8+
- updating CLI for new tags [#12](https://github.com/executablebooks/github-activity/pull/12) ([@choldgraf](https://github.com/choldgraf))
9+
- fixing link to changelog with refs [#11](https://github.com/executablebooks/github-activity/pull/11) ([@choldgraf](https://github.com/choldgraf))
10+
- adding contributors list [#10](https://github.com/executablebooks/github-activity/pull/10) ([@choldgraf](https://github.com/choldgraf))
11+
- some improvements to `since` and opened issues list [#8](https://github.com/executablebooks/github-activity/pull/8) ([@choldgraf](https://github.com/choldgraf))
12+
- Support git references etc. [#6](https://github.com/executablebooks/github-activity/pull/6) ([@consideRatio](https://github.com/consideRatio))
13+
- adding authentication information [#2](https://github.com/executablebooks/github-activity/pull/2) ([@choldgraf](https://github.com/choldgraf))
14+
- Mention the required GITHUB_ACCESS_TOKEN [#1](https://github.com/executablebooks/github-activity/pull/1) ([@consideRatio](https://github.com/consideRatio))
1515

1616
## Contributors to this release
1717

tests/test_cli/cli_no_target.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# master@{2019-09-01}...master@{2019-11-01}
2+
3+
([full changelog](https://github.com/executablebooks/github-activity/compare/479cc4b2f5504945021e3c4ee84818a10fabf810...ed7f1ed78b523c6b9fe6b3ac29e834087e299296))
4+
5+
## Merged PRs
6+
7+
- defining contributions [#14](https://github.com/executablebooks/github-activity/pull/14) ([@choldgraf](https://github.com/choldgraf))
8+
- updating CLI for new tags [#12](https://github.com/executablebooks/github-activity/pull/12) ([@choldgraf](https://github.com/choldgraf))
9+
- fixing link to changelog with refs [#11](https://github.com/executablebooks/github-activity/pull/11) ([@choldgraf](https://github.com/choldgraf))
10+
- adding contributors list [#10](https://github.com/executablebooks/github-activity/pull/10) ([@choldgraf](https://github.com/choldgraf))
11+
- some improvements to `since` and opened issues list [#8](https://github.com/executablebooks/github-activity/pull/8) ([@choldgraf](https://github.com/choldgraf))
12+
- Support git references etc. [#6](https://github.com/executablebooks/github-activity/pull/6) ([@consideRatio](https://github.com/consideRatio))
13+
- adding authentication information [#2](https://github.com/executablebooks/github-activity/pull/2) ([@choldgraf](https://github.com/choldgraf))
14+
- Mention the required GITHUB_ACCESS_TOKEN [#1](https://github.com/executablebooks/github-activity/pull/1) ([@consideRatio](https://github.com/consideRatio))
15+
16+
## Contributors to this release
17+
18+
([GitHub contributors page for this release](https://github.com/executablebooks/github-activity/graphs/contributors?from=2019-09-01&to=2019-11-01&type=c))
19+
20+
[@betatim](https://github.com/search?q=repo%3Aexecutablebooks%2Fgithub-activity+involves%3Abetatim+updated%3A2019-09-01..2019-11-01&type=Issues) | [@choldgraf](https://github.com/search?q=repo%3Aexecutablebooks%2Fgithub-activity+involves%3Acholdgraf+updated%3A2019-09-01..2019-11-01&type=Issues) | [@consideRatio](https://github.com/search?q=repo%3Aexecutablebooks%2Fgithub-activity+involves%3AconsideRatio+updated%3A2019-09-01..2019-11-01&type=Issues)

tests/test_cli/cli_w_parts.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# master@{2019-09-01}...master@{2019-11-01}
2+
3+
([full changelog](https://github.com/executablebooks/github-activity/compare/479cc4b2f5504945021e3c4ee84818a10fabf810...ed7f1ed78b523c6b9fe6b3ac29e834087e299296))
4+
5+
## Merged PRs
6+
7+
- defining contributions [#14](https://github.com/executablebooks/github-activity/pull/14) ([@choldgraf](https://github.com/choldgraf))
8+
- updating CLI for new tags [#12](https://github.com/executablebooks/github-activity/pull/12) ([@choldgraf](https://github.com/choldgraf))
9+
- fixing link to changelog with refs [#11](https://github.com/executablebooks/github-activity/pull/11) ([@choldgraf](https://github.com/choldgraf))
10+
- adding contributors list [#10](https://github.com/executablebooks/github-activity/pull/10) ([@choldgraf](https://github.com/choldgraf))
11+
- some improvements to `since` and opened issues list [#8](https://github.com/executablebooks/github-activity/pull/8) ([@choldgraf](https://github.com/choldgraf))
12+
- Support git references etc. [#6](https://github.com/executablebooks/github-activity/pull/6) ([@consideRatio](https://github.com/consideRatio))
13+
- adding authentication information [#2](https://github.com/executablebooks/github-activity/pull/2) ([@choldgraf](https://github.com/choldgraf))
14+
- Mention the required GITHUB_ACCESS_TOKEN [#1](https://github.com/executablebooks/github-activity/pull/1) ([@consideRatio](https://github.com/consideRatio))
15+
16+
## Contributors to this release
17+
18+
([GitHub contributors page for this release](https://github.com/executablebooks/github-activity/graphs/contributors?from=2019-09-01&to=2019-11-01&type=c))
19+
20+
[@betatim](https://github.com/search?q=repo%3Aexecutablebooks%2Fgithub-activity+involves%3Abetatim+updated%3A2019-09-01..2019-11-01&type=Issues) | [@choldgraf](https://github.com/search?q=repo%3Aexecutablebooks%2Fgithub-activity+involves%3Acholdgraf+updated%3A2019-09-01..2019-11-01&type=Issues) | [@consideRatio](https://github.com/search?q=repo%3Aexecutablebooks%2Fgithub-activity+involves%3AconsideRatio+updated%3A2019-09-01..2019-11-01&type=Issues)

0 commit comments

Comments
 (0)