Files

63 lines
2.2 KiB
Python

import dataclasses
from command_lines.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 CommitCall:
"""A `git commit` a shell command runs: the directory it runs in, its messages, whether it reads its message from a file, and whether it amends."""
directory: str
messages: list[str]
from_file: bool
amends: bool
def commits(simples: list[Simple], home: str) -> list[CommitCall]:
found = []
for simple in simples:
invoked = git_subcommand(simple.words, simple.directory, home)
if invoked and invoked[0] == "commit":
found.append(CommitCall(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, bool]:
"""git commit's messages, whether it reads one from a file, and whether it amends."""
messages = []
from_file = False
amends = False
words = iter(args)
for word in words:
if word == "--":
break
amends = amends or word == "--amend"
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, amends