GitHub

command_line

API reference for command_line.

Command lines: the single strings a shell or a Windows program turns back into arguments, and argument lists from templates (Effect's CommandLine). Unrelated to pyfect.cli, which parses your own program's arguments.

The rules depend on what reads the string, not on the platform building it, so quote, join and display take a format:

  • "posix" (the default): sh, dash, bash and zsh; fish reads the quoted output the same way.
  • "powershell": PowerShell 7.3 or later.
  • "windows": the Microsoft C runtime rules most Windows programs split their command line with (not cmd.exe's).

Arguments can be Redacted strings: quote and join include their values, because their output is meant to run; display shows <redacted>::

command_line.join(["git", "commit", "-m", "fix: don't fail"])
# Ok("git commit -m 'fix: don'\\''t fail'")
command_line.template(t"git commit -m {msg} {files}")  # Python 3.14
command_line.template(["git commit -m ", " ", ""], msg, files)

A template is its literal text parts and the values between them, as a tagged template gives them (or a t-string on Python 3.14). The text is split into words as a POSIX shell does (quotes and backslash escapes removed); text that needs a shell (operators, expansions, globs, comments, a variable assignment) fails with UnsupportedSyntax; each value is one literal argument, or part of the surrounding one; a list adds one argument per item and must stand alone; an argument containing a Redacted value is Redacted as a whole. Error messages never include the input.

Types

TypeDefinitionDescription
Formattype Format = Literal['posix', 'powershell', 'windows']

The syntax a command line is read with.

Wordtype Word = str | Redacted[str]

One argument: a string, or a Redacted one kept out of logs.

TemplateExpressionItemtype TemplateExpressionItem = str | int | float | bool | Redacted[str]

One value of a template.

TemplateExpressiontype TemplateExpression = TemplateExpressionItem | Sequence[TemplateExpressionItem]

A value of a template: a list or tuple adds one argument per item.

TemplateStringstype TemplateStrings = list[str] | tuple[str, ...]

The text parts of a template, as a tagged template gets them (a str is not one, so make("ls", ...) cannot be read as a template).

Reasontype Reason = Literal['NulCharacter', 'InvalidArgument', 'InvalidEscape', 'UnterminatedQuote', 'UnsupportedSyntax']

Classes

Functions

quote

quote(word, *, format='posix') -> Result[str, CommandLineError]

word quoted so a program reading format sees exactly one argument (PowerShell never passes --% on, however quoted: join refuses it).

"posix" leaves words of letters, digits and _ @ + : , . / - as they are and single-quotes the rest, ' and \ written outside the quotes; "powershell" always single-quotes, doubling ' and the typographic single quotes; "windows" quotes words with a space, tab, line break or " by the C runtime's backslash rules. The result holds a Redacted argument's value: use display for logs.

ParameterTypeDescription
wordWord
formatFormat = 'posix'

Returns Result[str, CommandLineError]

def quote(word: Word, *, format: Format = "posix") -> Result[str, CommandLineError]:
    """``word`` quoted so a program reading ``format`` sees exactly one
    argument (PowerShell never passes ``--%`` on, however quoted: ``join``
    refuses it).

    ``"posix"`` leaves words of letters, digits and ``_ @ + : , . / -`` as
    they are and single-quotes the rest, ``'`` and ``\\`` written outside the
    quotes; ``"powershell"`` always single-quotes, doubling ``'`` and the
    typographic single quotes; ``"windows"`` quotes words with a space, tab,
    line break or ``"`` by the C runtime's backslash rules. The result holds
    a ``Redacted`` argument's value: use ``display`` for logs."""
    text = _unwrap(word)
    if "\0" in text:
        return _fail_nul("The argument")
    return Ok(_quote_word(format, text, program=False))

join

join(words, *, format='posix') -> Result[str, CommandLineError]

A command line running words[0] with the rest as its arguments, each quoted as quote does and separated by spaces; empty for no words. "posix" also quotes a program name a shell reads as a reserved word (if, time); "powershell" starts with the call operator &; "windows" quotes the program name without backslash escapes, and refuses one containing ". "powershell" refuses an argument --%. The result holds Redacted values: use display for logs.

ParameterTypeDescription
wordsSequence[Word]
formatFormat = 'posix'

Returns Result[str, CommandLineError]

def join(words: Sequence[Word], *, format: Format = "posix") -> Result[str, CommandLineError]:
    """A command line running ``words[0]`` with the rest as its arguments,
    each quoted as ``quote`` does and separated by spaces; empty for no
    words. ``"posix"`` also quotes a program name a shell reads as a
    reserved word (``if``, ``time``); ``"powershell"`` starts with the call
    operator ``&``; ``"windows"`` quotes the program name without backslash
    escapes, and refuses one containing ``"``. ``"powershell"`` refuses an
    argument ``--%``. The result holds ``Redacted`` values: use ``display``
    for logs."""
    texts: list[str] = []
    for i, word in enumerate(words):
        text = _unwrap(word)
        if "\0" in text:
            return _fail_nul(f"Argument {i}")
        texts.append(text)
    if not texts:
        return Ok("")
    if format == "powershell":
        if "--%" in texts[1:]:
            index = texts.index("--%", 1)
            return Err(
                CommandLineError(
                    "InvalidArgument",
                    f'Argument {index} is "--%", which PowerShell drops when it calls a program',
                )
            )
    elif format == "windows" and '"' in texts[0]:
        return Err(
            CommandLineError(
                "InvalidArgument", "A Windows program name cannot contain a double quote"
            )
        )
    return Ok(
        _join_words(
            format, [_quote_word(format, text, program=i == 0) for i, text in enumerate(texts)]
        )
    )

display

display(words, *, format='posix') -> str

words for logs and error messages: quoted as join does, with Redacted arguments as <redacted> and control characters and Unicode line separators as escapes (\n, \u001b). Never fails; the output is for reading, not running.

ParameterTypeDescription
wordsSequence[Word]
formatFormat = 'posix'

Returns str

def display(words: Sequence[Word], *, format: Format = "posix") -> str:
    """``words`` for logs and error messages: quoted as ``join`` does, with
    ``Redacted`` arguments as ``<redacted>`` and control characters and
    Unicode line separators as escapes (``\\n``, ``\\u001b``). Never fails;
    the output is for reading, not running."""
    if not words:
        return ""
    # Escaping after quoting keeps the escapes inside the quotes.
    return _join_words(
        format,
        [
            "<redacted>"
            if isinstance(word, Redacted)
            else _escape_control_characters(_quote_word(format, word, program=i == 0))
            for i, word in enumerate(words)
        ],
    )

template

template(strings, *values) -> Result[list[Word], CommandLineError]

The argument list of a template: its text parts strings and the values between them (one fewer), or a t-string alone. See the module docstring for the rules. Neither text nor values are checked for NUL: join and the spawner reject it.

ParameterTypeDescription
stringsTemplateStrings | TemplateLike
valuesTemplateExpression = ()

Returns Result[list[Word], CommandLineError]

def template(
    strings: TemplateStrings | TemplateLike, /, *values: TemplateExpression
) -> Result[list[Word], CommandLineError]:
    """The argument list of a template: its text parts ``strings`` and the
    ``values`` between them (one fewer), or a t-string alone. See the module
    docstring for the rules. Neither text nor values are checked for NUL:
    ``join`` and the spawner reject it."""
    if isinstance(strings, (list, tuple)):
        texts = tuple(strings)
        items: tuple[object, ...] = values
    else:
        if values:
            raise TypeError("a t-string carries its own values")
        texts = strings.strings
        items = tuple(i.value for i in strings.interpolations)
    if len(texts) != len(items) + 1:
        raise TypeError(
            f"a template needs one more text part than values, got {len(texts)} and {len(items)}"
        )
    return _Parser(texts, tuple(map(_expression, items))).parse()