|
| 1 | +#!/usr/bin/env python |
| 2 | +""" |
| 3 | +Generate a commit message |
| 4 | +Parses staged files and generates a commit message with Last-Translator's as |
| 5 | +co-authors. |
| 6 | +Based on Stan Ulbrych's implementation for Python Doc' Polish team |
| 7 | +""" |
| 8 | + |
| 9 | +import argparse |
| 10 | +import contextlib |
| 11 | +import os |
| 12 | +from subprocess import run, CalledProcessError |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +from polib import pofile, POFile |
| 16 | + |
| 17 | + |
| 18 | +def generate_commit_msg(): |
| 19 | + translators: set[str] = set() |
| 20 | + |
| 21 | + result = run( |
| 22 | + ["git", "diff", "--cached", "--name-only", "--diff-filter=ACM"], |
| 23 | + capture_output=True, |
| 24 | + text=True, |
| 25 | + check=True, |
| 26 | + ) |
| 27 | + staged = [ |
| 28 | + filename for filename in result.stdout.splitlines() if filename.endswith(".po") |
| 29 | + ] |
| 30 | + |
| 31 | + for file in staged: |
| 32 | + staged_file = run( |
| 33 | + ["git", "show", f":{file}"], capture_output=True, text=True, check=True |
| 34 | + ).stdout |
| 35 | + try: |
| 36 | + old_file = run( |
| 37 | + ["git", "show", f"HEAD:{file}"], |
| 38 | + capture_output=True, |
| 39 | + text=True, |
| 40 | + check=True, |
| 41 | + ).stdout |
| 42 | + except CalledProcessError: |
| 43 | + old_file = "" |
| 44 | + |
| 45 | + new_po = pofile(staged_file) |
| 46 | + old_po = pofile(old_file) if old_file else POFile() |
| 47 | + old_entries = {entry.msgid: entry.msgstr for entry in old_po} |
| 48 | + |
| 49 | + for entry in new_po: |
| 50 | + if entry.msgstr and ( |
| 51 | + entry.msgid not in old_entries |
| 52 | + or old_entries[entry.msgid] != entry.msgstr |
| 53 | + ): |
| 54 | + translator = new_po.metadata.get("Last-Translator") |
| 55 | + translator = translator.split(",")[0].strip() |
| 56 | + if translator: |
| 57 | + translators.add(f"Co-Authored-By: {translator}") |
| 58 | + break |
| 59 | + |
| 60 | + print("Update translation\n\n" + "\n".join(translators)) |
| 61 | + |
| 62 | + |
| 63 | +# contextlib implemented chdir since Python 3.11 |
| 64 | +@contextlib.contextmanager |
| 65 | +def chdir(path: Path): |
| 66 | + """Temporarily change the working directory.""" |
| 67 | + original_dir = Path.cwd() |
| 68 | + os.chdir(path) |
| 69 | + try: |
| 70 | + yield |
| 71 | + finally: |
| 72 | + os.chdir(original_dir) |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + parser = argparse.ArgumentParser( |
| 77 | + description="Generate commit message with translators as co-authors." |
| 78 | + ) |
| 79 | + parser.add_argument( |
| 80 | + "path", |
| 81 | + type=Path, |
| 82 | + nargs='?', |
| 83 | + default=".", |
| 84 | + help="Path to the Git repository (default: current directory)", |
| 85 | + ) |
| 86 | + args = parser.parse_args() |
| 87 | + |
| 88 | + with chdir(args.path): |
| 89 | + generate_commit_msg() |
0 commit comments