Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Grub4K committed Feb 24, 2024
0 parents commit da07fb7
Show file tree
Hide file tree
Showing 15 changed files with 759 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/checks.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Checks
on: [push, pull_request]
permissions:
contents: read

jobs:
check:
name: Code check
if: "!contains(github.event.head_commit.message, 'ci skip all')"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- name: Install ruff
run: python3 -m pip install ruff
- name: Run lint check
run: ruff check --output-format github .
- name: Run format check
run: ruff check --output-format github .
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
repos:
- repo: local
hooks:
- id: check
name: code check
entry: hatch run check
language: system
types: [python]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Simon Sawicki

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# git-pr-helper

[![license](https://img.shields.io/badge/license-MIT-green)](https://github.com/Grub4K/git-pr-helper/blob/main/LICENSE)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)

Git subcommand to aid with GitHub PRs interaction

_**NOTE**_: While this software is still very early in development, it should already be useful.
Don't expect speedy execution or good error handling for now though.

## Installation
For now, you have to install from git, e.g. `pipx install git+https://github.com/Grub4K/git-pr-helper.git`, and ensure its in `PATH`.

For easier and more convenient usage, you should create a git alias as well: `git config --global alias.pr "!git-pr-helper"`.
After this you can invoke it conveniently via `git pr ...`. Use `git pr help` to access the help instead of `--help`.

## How does it work
GitHub provides `refs/pull/*/head`, which we can use to get each PR; these are read only though, so maintainers or even the original authors cannot push to it.
To be able to push, we store the actual upstream pr remote in the branch description, and provide it explicitly: `git push git@github.com:user/repo.git HEAD:branch`.

Additionally, GitHub provides `refs/pull/*/merge` for all open PRs.
These can be used to determine if local PR branches can be removed (`prune`).

## Improvements
These are in order of relevance
- [ ] Error handling
- [ ] Add a way to manage branch description
- [ ] Use a simpler format for the branch description
- [ ] Better input and output helpers and wrappers
- [ ] Caching and lazy execution
- [ ] Automated release CI
- [ ] Do not hardcode `github.com`
3 changes: 3 additions & 0 deletions git_pr_helper/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from __future__ import annotations

__version__ = "1.0.0"
78 changes: 78 additions & 0 deletions git_pr_helper/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
from __future__ import annotations

import inspect
import subprocess
import sys

from rich.console import Console

import git_pr_helper.actions


def _main():
import argparse

root_parser = argparse.ArgumentParser("git pr", add_help=False)
# root_parser.add_argument(
# "-C",
# dest="path",
# metavar="<path>",
# help="set the base path for the git repository",
# )
subparsers = root_parser.add_subparsers(title="action", dest="action")

ALL_ACTIONS = {
name.removeprefix("action_"): getattr(git_pr_helper.actions, name)
for name in dir(git_pr_helper.actions)
if name.startswith("action_")
}

parsers = {}
for name, module in ALL_ACTIONS.items():
parser_args = getattr(module, "PARSER_ARGS", None) or {}
parser = subparsers.add_parser(
name, **parser_args, add_help=False, help=inspect.getdoc(module)
)
module.configure_parser(parser)
parsers[name] = parser

parser = subparsers.add_parser("help", help="show this help message and exit")
parser.add_argument(
"subcommand",
nargs="?",
choices=[*ALL_ACTIONS, "help"],
help="the subcommand to get help for",
)
parsers["help"] = parser

args = root_parser.parse_args()
if args.action is None:
root_parser.error("need to provide an action")
elif args.action == "help":
parser = parsers[args.subcommand] if args.subcommand else root_parser
print(parser.format_help())
exit(0)

runner = ALL_ACTIONS[args.action].run

console = Console()
console.show_cursor(False)
try:
sys.exit(runner(console, args))

except subprocess.CalledProcessError as error:
sys.exit(error.returncode)

finally:
console.show_cursor()


def main():
try:
_main()
except KeyboardInterrupt:
pass


if __name__ == "__main__":
main()
8 changes: 8 additions & 0 deletions git_pr_helper/actions/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# ruff: noqa: F401
from __future__ import annotations

from git_pr_helper.actions import action_add
from git_pr_helper.actions import action_list
from git_pr_helper.actions import action_prune
from git_pr_helper.actions import action_push
from git_pr_helper.actions import action_setup
149 changes: 149 additions & 0 deletions git_pr_helper/actions/action_add.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""add a new pr branch or convert aan existing branch to one"""

from __future__ import annotations

import typing

import rich.text

from git_pr_helper import styles
from git_pr_helper.utils import PrBranchInfo
from git_pr_helper.utils import git
from git_pr_helper.utils import write_pr_branch_info

if typing.TYPE_CHECKING:
import argparse

import rich.console


def configure_parser(parser: argparse.ArgumentParser):
parser.add_argument(
"--prune",
action="store_true",
help="remove branches that have the same HEAD as the PR",
)
parser.add_argument(
"pr",
help="the pr to add, in the format <remote>#<number>",
)


def run(console: rich.console.Console, args: argparse.Namespace):
pr_remote, _, pr_number = args.pr.rpartition("#")
if not pr_remote:
pr_remote = "*"

try:
pr_number = str(int(pr_number))
except ValueError:
console.print(
rich.text.Text.assemble(
("error", styles.ERROR),
": ",
(pr_number, styles.ACCENT),
" is not a number",
)
)
return 1

head_hashes = [
line.partition(" ")[::2]
for line in git(
"for-each-ref",
"--format=%(objectname) %(refname:strip=2)",
f"refs/remotes/{pr_remote}/pr/{pr_number}",
)
]
if not head_hashes:
console.print(
rich.text.Text.assemble(
("error", styles.ERROR),
": did not find a matching pr",
)
)
return 1
elif len(head_hashes) > 1:
console.print(
rich.text.Text.assemble(
("error", styles.ERROR),
": found more than one PR: ",
rich.text.Text(", ").join(
rich.text.Text(pr_remote.replace("/pr/", "#"), style=styles.ACCENT)
for _, pr_remote in head_hashes
),
)
)
return 1
head_hash, pr_remote = head_hashes[0]
pr_remote = pr_remote.partition("/")[0]

branches = git(
"for-each-ref",
"--points-at",
head_hash,
"--exclude",
"refs/remotes/**/pr/*",
"--format",
"%(refname:strip=2)",
"refs/remotes/**",
)
if len(branches) > 1:
console.print(
rich.text.Text.assemble(
("More than one branch found", styles.ERROR),
": ",
rich.text.Text(", ").join(
rich.text.Text(branch, style=styles.ACCENT) for branch in branches
),
)
)
branches = []

if branches:
remote, _, branch = branches[0].partition("/")

else:
console.show_cursor()
info = console.input(
rich.text.Text.assemble(
"Enter branch info (",
("<user>/<repo>", styles.ACCENT),
":",
("<branch>", styles.ACCENT),
"): ",
)
)
console.show_cursor(False)
remote, _, branch = info.partition(":")
if "/" in remote:
remote = f"git@github.com:{remote}.git"

name = f"pr/{pr_number}"
git("switch", "-c", name, "--track", f"{pr_remote}/{name}")
write_pr_branch_info(name, PrBranchInfo(remote, branch, []))

if args.prune:
branches = git(
"for-each-ref",
"--points-at",
head_hash,
"--exclude",
"refs/heads/**/pr/*",
"--format",
"%(refname:strip=2)",
"refs/heads/**",
)
if branches:
git("branch", "-D", branch)
console.print(
rich.text.Text.assemble(
"Pruned branches: ",
rich.text.Text(", ").join(
rich.text.Text(branch, style=styles.ACCENT)
for branch in branches
),
)
)

return 0
Loading

0 comments on commit da07fb7

Please sign in to comment.