import dataclasses from shell_command import resolved, Simple # git's global options that take a value as the next word. GIT_VALUED = {"-C", "-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"} @dataclasses.dataclass(frozen=True) class Commit: directory: str messages: list[str] from_file: bool def commits(simples: list[Simple], home: str) -> list[Commit]: found = [] for simple in simples: invoked = git_subcommand(simple.words, simple.directory, home) if invoked and invoked[0] == "commit": found.append(Commit(invoked[2], *commit_message(invoked[1]))) return found def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, list[str], str] | None: """A git command's subcommand, its arguments and the directory it runs in, after git's own options such as -C.""" if words[:1] != ["git"]: return None args = iter(words[1:]) for word in args: if word in GIT_VALUED: value = next(args, "") directory = resolved(directory, value, home) if word == "-C" else directory elif not word.startswith("-"): return word, list(args), directory return None def commit_message(args: list[str]) -> tuple[list[str], bool]: """git commit's messages, and whether it reads one from a file.""" messages = [] from_file = False words = iter(args) for word in words: if word == "--": break name, equals, value = word.partition("=") if name in ("--message", "--file"): given = value if equals else next(words, "") elif word.startswith("-") and not word.startswith("--") and (flags := [flag for flag in word[1:] if flag in "mF"]): # A cluster such as -am: the valued flag takes the rest of the word, or else the next word. name = "--message" if flags[0] == "m" else "--file" given = word[word.index(flags[0]) + 1:] or next(words, "") else: continue messages += [given] if name == "--message" else [] from_file = from_file or name == "--file" return messages, from_file