51 lines
1.8 KiB
Python
51 lines
1.8 KiB
Python
"""The files a shell command reads, and the worktrees it adds, as absolute paths."""
|
|
import dataclasses
|
|
import posixpath
|
|
import re
|
|
|
|
from command_lines.shell_command import resolved, simple_commands
|
|
|
|
NOT_A_PATH = re.compile(r"[*?\[\]{}$\\'\",=()<>|;&]|://|^\d+$")
|
|
# Their first operand is a pattern or a program, unless -e or -f gives it.
|
|
PATTERN_FIRST = {"awk", "egrep", "grep", "rg", "sed"}
|
|
READERS = {"awk", "bat", "cat", "egrep", "grep", "head", "less", "more", "nl", "rg", "sed", "tail", "wc"}
|
|
WORKTREE_OPTIONS_WITH_VALUE = {"-b", "-B", "--reason"}
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Reads:
|
|
read: list[str]
|
|
added: list[str]
|
|
|
|
|
|
def shell_reads(command: str, cwd: str, home: str) -> Reads:
|
|
read: list[str] = []
|
|
added: list[str] = []
|
|
for simple in simple_commands(command, cwd, home):
|
|
read += [resolved(simple.directory, word, home) for word in operands(simple.words)]
|
|
added += [resolved(simple.directory, path, home) for path in worktree_added(simple.words)]
|
|
return Reads(read, added)
|
|
|
|
|
|
def operands(words: list[str]) -> list[str]:
|
|
program = posixpath.basename(words[0])
|
|
if program not in READERS or (program == "sed" and any(word.startswith("-i") for word in words)):
|
|
return []
|
|
given = [word for word in words[1:] if not word.startswith("-")]
|
|
if program in PATTERN_FIRST and not {"-e", "-f"} & set(words):
|
|
given = given[1:]
|
|
return [word for word in given if ("/" in word or re.search(r"\.[A-Za-z0-9]+$", word)) and not NOT_A_PATH.search(word)]
|
|
|
|
|
|
# git worktree add [-b <branch>] <path> [<commit>]
|
|
def worktree_added(words: list[str]) -> list[str]:
|
|
if words[:1] != ["git"] or "worktree" not in words or words[words.index("worktree") + 1:][:1] != ["add"]:
|
|
return []
|
|
after = iter(words[words.index("worktree") + 2:])
|
|
for word in after:
|
|
if word in WORKTREE_OPTIONS_WITH_VALUE:
|
|
next(after, None)
|
|
elif not word.startswith("-"):
|
|
return [word]
|
|
return []
|