Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ The format is based on Keep a Changelog, and this project adheres loosely to Sem
- CI now also runs pre-commit on every file, runs the tests on macOS (Python 3.10 and 3.14), and builds the package and runs the commands from the installed wheel. The workflow token is read-only, and Dependabot keeps the actions up to date.
- CodeQL analysis of the Python code and the workflows, with the `security-and-quality` queries, on pull requests, pushes to `master` and weekly.

### Fixed
- `git pullrequest` no longer gives up silently when `GITHUB_TOKEN` and `GH_TOKEN` are unset: it uses the GitHub CLI's token (`gh auth token`) if you're logged in, and otherwise says the pull request wasn't created and prints its URL as well as opening it. A GitHub API error is now printed rather than hidden behind `GITFEATURES_DEBUG`.
- Running out of answers on stdin (e.g. `printf 'y\n' | git pullrequest` when it asks twice) now counts as "no" instead of crashing with `EOFError`.

### Breaking
- Default base branch changed from `master` to `main`. You can override via `GITFEATURES_MASTER_BRANCH`.
- Dropped Python 2 support and removed the `six` dependency. Python 3.10+ is now required (3.8 and 3.9 are end-of-life).
Expand Down
44 changes: 33 additions & 11 deletions gitfeatures/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,26 @@ def _call(args):
sys.exit(__name__ + ": none zero exit status executing: " + " ".join(args)) # noqa


def _confirm() -> bool:
"""Read a y/n answer from stdin. Running out of input (e.g. too few answers piped in) counts as no."""
try:
return input().strip().lower() == "y"
except EOFError:
print("(no answer on stdin, taking that as no)")
return False


def _github_token() -> Optional[str]:
"""GITHUB_TOKEN or GH_TOKEN, else the token the GitHub CLI is logged in with, if it is installed."""
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
if token:
return token
try:
return check_output(["gh", "auth", "token"], stderr=DEVNULL).decode("utf-8").strip() or None
except (CalledProcessError, OSError):
return None


def _git_output(args) -> Optional[str]:
"""Run git quietly and return its stripped output, or None if it fails."""
try:
Expand Down Expand Up @@ -211,7 +231,7 @@ def _resolve_base_branch(branch, requested=None) -> str:
base, source = _base_branch_from_reflog(branch), "the branch it was created from"
if not base:
print(f"gitfeatures doesn't know which branch {branch} was created from. Was it {master_branch}? [y/n]")
if input().lower() != "y":
if not _confirm():
sys.exit(f"Run git pullrequest --base <branch>, naming the branch {branch} was created from.")
base, source = master_branch, "confirmed"
if base == branch:
Expand Down Expand Up @@ -605,7 +625,7 @@ def new_feature(name, prefix, ticket_id=None):
master_branch, original_branch
)
) # noqa
if input().lower() != "y":
if not _confirm():
sys.exit("Ok, Exiting") # noqa

_call(["git", "remote", "update", "origin"])
Expand Down Expand Up @@ -802,7 +822,7 @@ def cleanup(args):
return
if not assume_yes:
print(f"Delete these {len(candidates)} local branches? [y/n]")
if input().lower() != "y":
if not _confirm():
sys.exit("Ok, Exiting")
for branch, _ in candidates:
_call(["git", "branch", "-D", branch])
Expand Down Expand Up @@ -838,7 +858,7 @@ def _branch_func(branch_type, args):
print(
f"you have more than 3 {branch_type} branches, shall I delete the eldest one ({branch})? [y/n]"
) # noqa
if input().lower() == "y":
if _confirm():
_call(["git", "push", "origin", "--delete", branch])
_call(["git", "branch", "-D", branch])
else:
Expand Down Expand Up @@ -898,7 +918,7 @@ def pullrequest(args):
f"Do you wish to fetch {base} and {merge_strategy} {branch} with it "
"(If conflicts occur, you will be able to fix them)? [y/n]"
)
if input().lower() == "y":
if _confirm():
_call(["git", "fetch", "origin", base_branch])
_update_branch_from(base)

Expand All @@ -908,7 +928,7 @@ def pullrequest(args):
print("You have unpushed commits:")
print(commits)
print("Push commits to origin [y/n]")
if input().lower() == "y":
if _confirm():
_call(["git", "push", "origin", branch + ":" + branch])

origin = _call(["git", "config", "--get", "remote.origin.url"])
Expand All @@ -920,9 +940,11 @@ def pullrequest(args):
if dry_run or os.environ.get("CONSOLEONLY", False):
print(url)
else:
# If a GitHub token is present, attempt to create the PR via API
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
if repo == "github" and token:
# If a GitHub token is available, attempt to create the PR via API
token = _github_token() if repo == "github" else None
if repo == "github" and not token:
print("No GITHUB_TOKEN, GH_TOKEN or `gh auth login`, so the pull request was not created.")
if token:
body = _read_changelog_body(branch) if changelog_enabled else None
ok, resp = _create_github_pr_with_token(name, branch, base_branch, body, token)
if ok:
Expand All @@ -936,8 +958,8 @@ def pullrequest(args):
pass
return
else:
print("Failed to create PR via API. Falling back to browser flow.")
_debug(f"GitHub API error: {resp}")
print(f"Failed to create the pull request via the GitHub API: {resp}")
print(f"Open it in your browser: {url}")
webbrowser.open_new_tab(url)


Expand Down
50 changes: 50 additions & 0 deletions tests/test_pullrequest.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,53 @@ def test_feature_finish_when_origin_already_deleted_the_branch(repo_with_origin)

assert git("branch", "--show-current", cwd=repo_with_origin) == "main"
assert "feature_d" not in git("branch", "-a", cwd=repo_with_origin)


@pytest.fixture
def pushed_feature(repo_with_origin, monkeypatch):
"""feature_p, pushed and level with origin/main, with its base recorded and the browser stubbed out."""
git("checkout", "-q", "-b", "feature_p", cwd=repo_with_origin)
git("push", "-q", "-u", "origin", "feature_p", cwd=repo_with_origin)
git("config", "branch.feature_p.gitfeaturesBase", "main", cwd=repo_with_origin)
opened = []
monkeypatch.setattr(core.webbrowser, "open_new_tab", opened.append)
return opened


def test_without_a_token_says_so_and_prints_the_url(pushed_feature, monkeypatch, capsys):
monkeypatch.setattr(core, "_github_token", lambda: None)

core.pullrequest([])

out = capsys.readouterr().out
assert "pull request was not created" in out
assert f"Open it in your browser: {pushed_feature[0]}" in out


def test_api_failure_is_reported_not_hidden(pushed_feature, monkeypatch, capsys):
monkeypatch.setattr(core, "_github_token", lambda: "t")
monkeypatch.setattr(core, "_create_github_pr_with_token", lambda *a: (False, '{"message":"Validation Failed"}'))

core.pullrequest([])

out = capsys.readouterr().out
assert "Validation Failed" in out
assert "Open it in your browser:" in out


def test_github_token_falls_back_to_the_gh_cli(monkeypatch):
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.setattr(core, "check_output", lambda args, **kw: b"gho_cli\n" if args[:2] == ["gh", "auth"] else b"")
assert core._github_token() == "gho_cli"

monkeypatch.setenv("GH_TOKEN", "from_env")
assert core._github_token() == "from_env"


def test_running_out_of_piped_answers_counts_as_no(monkeypatch):
def eof():
raise EOFError

monkeypatch.setattr("builtins.input", eof)
assert core._confirm() is False
Loading