Skip to content

Commit

Permalink
Add pre-commit hook check if branch needs rebase, fix spellcheck (#89)
Browse files Browse the repository at this point in the history
Signed-off-by: Bernhard Kaindl <[email protected]>
  • Loading branch information
bernhardkaindl authored Mar 21, 2024
1 parent bd7e5df commit 1461413
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 2 deletions.
102 changes: 102 additions & 0 deletions .github/workflows/check_branch-needs-rebase.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Check if the current branch is up-to-date with the remote branch."""

# pylint: disable=using-f-string-in-unsupported-version
import subprocess
import sys
from logging import info as log


def run(command: list[str], check=False) -> tuple[int, str]:
"""Run a command and return the output."""
cmd: subprocess.CompletedProcess[str] = subprocess.run(
command,
check=check,
text=True,
capture_output=True,
)
return cmd.returncode, cmd.stdout.strip()


def check_if_local_branch_is_behind_target(
current_branch: str,
target="origin/master",
) -> int:
"""
Check if the current branch is behind the target branch.
Return: int - the number of commits behind the target branch or 0 if up-to-date
"""

# Fetch the remote branch in order to get the number of commits behind
if run(["git", "fetch", *target.split("/", maxsplit=1)])[0]:
log("Failed to fetch the remote branch")
return 1

# Get the number of commits behind the remote branch
error, commits_behind = run(
["git", "rev-list", "--left-right", "--count", f"{target}...{current_branch}"],
)
if error:
log(f"Failed to get the number of commits behind {target}")
return 1

# If the current branch is behind the remote branch, print the commits
# and return the number of commits behind
if commits_behind.split()[0] != "0":
print(
f"The current branch {current_branch} is behind {target} "
f"by {commits_behind.split()[0]} commits:"
)

left_right = run(
["git", "rev-list", "--left-right", "--oneline", f"{target}...HEAD"],
)[1]
for line in left_right.split("\n"):
if line.startswith("<"):
print(line.replace("<", ""))

return int(commits_behind.split()[0]) # Return the number of commits behind

print(f"The current branch {current_branch} is up-to-date with {target}")
return 0 # Return 0 if the current branch is up-to-date


def get_remote_default_branch(remote_url):
"""Get the default branch name of the remote repository."""

default_branch_info = subprocess.check_output(
["git", "ls-remote", "--symref", remote_url, "HEAD"], text=True
)
return default_branch_info.strip().split("\t")[0].split("refs/heads/")[1]


def main():
"""Check if the current branch is up-to-date with the remote branch.
Check if the current branch is up-to-date with the remote branch.
On errors and if not up-to-date, return an error exit code.
"""

# Check if the current directory is a git repository
# Get the current branch name
current_branch = subprocess.check_output(
["git", "rev-parse", "--abbrev-ref", "HEAD"], text=True
).strip()

# Get the default branch name of the remote repository
err, remote_ref = run(
["git", "rev-parse", "--abbrev-ref", f"{current_branch}@{{upstream}}"],
)
if err: # Default to origin/master if no upstream is set yet
target = "origin/master"
else:
remote = remote_ref.split("/")[0]
remote_default = get_remote_default_branch(remote)
target = f"{remote}/{remote_default}"

return check_if_local_branch_is_behind_target(current_branch, target)


if __name__ == "__main__":
sys.exit(main())
4 changes: 3 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,9 @@ jobs:
env:
PYTHONDEVMODE: yes # Enable Python3 checks. See the comment above.
# Skip the no-commit-to-branch check inside of GitHub CI (for CI on merge to master)
SKIP: no-commit-to-branch
# TODO: For push workflows, fix check-branch-needs-rebase to work in GitHub CI.
# GitHub PR workflows are already always rebased to the target branch (on run):
SKIP: no-commit-to-branch,check-branch-needs-rebase

- name: Upload coverage reports to Codecov
# If CODECOV_TOKEN is set, use the new codecov CLI to upload the coverage reports
Expand Down
23 changes: 22 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,12 @@ repos:
hooks:
- id: mypy
name: Run mypy to check e.g. that all expected arguments are passed to functions etc
additional_dependencies: [defusedxml, pytest, types-lxml, types-mock]
additional_dependencies:
- defusedxml
- pytest
- types-lxml
- types-mock
- types-requests


- repo: https://github.com/pylint-dev/pylint
Expand All @@ -114,6 +119,15 @@ repos:

- repo: local
hooks:
- id: check-branch-needs-rebase
name: Check if the current branch needs a rebase
entry: .github/workflows/check_branch-needs-rebase.py
language: python
always_run: true
pass_filenames: false
additional_dependencies: [requests]


- id: git-diff # Ref: https://github.com/pre-commit/pre-commit/issues/1712
name: Show not staged changes (fixups may make them too)
entry: sh -c '.vscode/ltex-sort-dictionary.sh && git diff --exit-code'
Expand Down Expand Up @@ -184,6 +198,13 @@ repos:
rev: '2023.5.8'
hooks:
- id: pytype
# Note: Pytype does not support Python 3.12 yet:
# https://google.github.io/pytype/support.html
#
# If your pre-commit has been installed in a Python3.12 environment,
# you need to uncomment the next line to run pytype in a Python3.10 environment:
# that also the GitHub Action currently uses:
# language_version: "3.10"
name: Run pytype to check the unit tests for any typing warnings (does not work on bugtool yet)
exclude: xen-bugtool
additional_dependencies: [pytest]
3 changes: 3 additions & 0 deletions .vscode/ltex.dictionary.en-US.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ attr
authkey
autoflake
autouse
backend
basename
basepath
basestring
Expand Down Expand Up @@ -131,6 +132,7 @@ nsswitch
nvme
O_CREAT
O_RDONLY
oneline
openvswitch
opterr
os
Expand Down Expand Up @@ -238,6 +240,7 @@ xc
xcp
xen
xen-bugtool
xenapi
XenCenter
xenopsd
XENRT
Expand Down

0 comments on commit 1461413

Please sign in to comment.