Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,28 @@ $ uv add libvcs --prerelease allow
_Notes on the upcoming release will go here._
<!-- END PLACEHOLDER - ADD NEW CHANGELOG ENTRIES BELOW THIS LINE -->

### Fixes

#### Non-interactive Git prompts and ANSI-free list parsers (#568)

{meth}`~libvcs.cmd.git.Git.run` defaults `GIT_TERMINAL_PROMPT=0` unless
`GIT_TERMINAL_PROMPT` is already set in `env` or the process environment, so
unauthenticated HTTPS remotes fail immediately instead of prompting on a
controlling terminal. {meth}`~libvcs.cmd.git.GitBranchManager.ls`,
{meth}`~libvcs.cmd.git.GitReflogManager.ls`, and
{meth}`~libvcs.cmd.git.GitStashManager.ls` pass `--no-color` so `color.ui`
settings do not inject ANSI escape sequences into parsed fields.

#### Multi-byte UTF-8 progress decoding and `GitSync` fetch streaming (#569)

Subprocess `stderr` streaming decodes multi-byte UTF-8 sequences incrementally
across pipe reads instead of escaping split code points, while still replacing
invalid byte sequences via `backslashreplace`.
{meth}`~libvcs.sync.git.GitSync.update_repo` and
{meth}`~libvcs.sync.git.GitSync.create_worktree` now stream `git fetch
--progress` output when `progress_callback` is configured, and
{meth}`~libvcs.cmd.git.Git.fetch` forwards `log_in_real_time`.

## libvcs 0.48.0 (2026-11-29)

libvcs 0.48.0 parses Git version and build metadata into typed models, renames
Expand Down
9 changes: 9 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ dev = [
"sphinx-autobuild",
# Testing
"gp-libs>=0.0.19",
"libvt[pytest,syrupy]>=0.0.1a5,<0.1; python_version >= '3.12'",
"syrupy>=7.0.3; python_version >= '3.12'",
"pytest",
"pytest-asyncio",
"pytest-rerunfailures",
Expand All @@ -93,6 +95,8 @@ docs = [
]
testing = [
"gp-libs>=0.0.19",
"libvt[pytest,syrupy]>=0.0.1a5,<0.1; python_version >= '3.12'",
"syrupy>=7.0.3; python_version >= '3.12'",
"pytest",
"pytest-asyncio",
"pytest-rerunfailures",
Expand Down Expand Up @@ -127,6 +131,7 @@ ty = false
# committing a date that would age into the lockfile. Mirrors the
# pattern at vcspull/pyproject.toml for libvcs.
gp-libs = false
libvt = false
gp-furo-theme = false
gp-sphinx = false
sphinx-autodoc-api-style = false
Expand All @@ -144,6 +149,10 @@ sphinx-gp-theme = false
sphinx-ux-autodoc-layout = false
sphinx-ux-badges = false

[tool.ty.analysis]
# libvt and syrupy are Python 3.12+ test dependencies, absent in Python 3.11 environments
allowed-unresolved-imports = ["libvt", "libvt.**", "syrupy", "syrupy.**"]

[tool.ty.environment]
python-version = "3.11"

Expand Down
72 changes: 57 additions & 15 deletions src/libvcs/_internal/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

from __future__ import annotations

import codecs
import contextlib
import datetime
import functools
import logging
import os
import selectors
Expand Down Expand Up @@ -39,6 +41,26 @@ def console_to_str(s: bytes) -> str:
return str(s)


@functools.lru_cache(maxsize=8)
def _stderr_decoder_factory(
encoding: str | None,
) -> t.Callable[..., codecs.IncrementalDecoder]:
"""Return a cached :class:`codecs.IncrementalDecoder` class for *encoding*."""
enc = encoding or console_encoding or "utf-8"
try:
codec_name = codecs.lookup(enc).name
except LookupError:
codec_name = "utf-8"
if encoding is None and codec_name == "ascii":
codec_name = "utf-8"
return codecs.getincrementaldecoder(codec_name)


def _make_stderr_decoder(encoding: str | None) -> codecs.IncrementalDecoder:
"""Build an incremental stderr decoder with ``backslashreplace`` fallback."""
return _stderr_decoder_factory(encoding)(errors="backslashreplace")


if t.TYPE_CHECKING:
_LoggerAdapter = logging.LoggerAdapter[logging.Logger]
else:
Expand Down Expand Up @@ -282,6 +304,7 @@ def progress_cb(output: t.AnyStr, timestamp: datetime.datetime) -> None:
timeout=timeout,
callback=callback,
cmd=_stringify_command(normalized_args),
encoding=encoding,
)
except BaseException:
try:
Expand Down Expand Up @@ -338,6 +361,7 @@ def _wait_with_deadline(
timeout: float | None,
callback: ProgressCallbackProtocol | None,
cmd: str | list[str],
encoding: str | None = None,
) -> tuple[int, bytes | None, bytes | None]:
"""Drain child pipes while waiting, enforcing an optional wall-clock deadline.

Expand Down Expand Up @@ -374,6 +398,8 @@ def _wait_with_deadline(
buffers: dict[t.IO[bytes], list[bytes]] = {}
registered: set[t.IO[bytes]] = set()
fds_to_restore: list[int] = []
has_callback = callback is not None and callable(callback)
stderr_decoder: codecs.IncrementalDecoder | None = None

for stream in (proc.stdout, proc.stderr):
if stream is None:
Expand Down Expand Up @@ -402,13 +428,18 @@ def _wait_with_deadline(
trailing = _drain_stream(stream)
if trailing:
buffers[stream].append(trailing)
if (
stream is proc.stderr
and callback is not None
and callable(callback)
):
if (
stream is proc.stderr
and has_callback
and callback is not None
and (trailing or stderr_decoder is not None)
):
if stderr_decoder is None:
stderr_decoder = _make_stderr_decoder(encoding)
decoded_tail = stderr_decoder.decode(trailing, final=True)
if decoded_tail:
callback(
output=console_to_str(trailing),
output=decoded_tail,
timestamp=datetime.datetime.now(tz=datetime.UTC),
)
break
Expand Down Expand Up @@ -465,17 +496,28 @@ def _wait_with_deadline(
# it so the loop doesn't spin on an always-readable fd.
sel.unregister(stream)
registered.discard(stream)
if (
stream is proc.stderr
and stderr_decoder is not None
and callback is not None
):
flushed = stderr_decoder.decode(b"", final=True)
if flushed:
callback(
output=flushed,
timestamp=datetime.datetime.now(tz=datetime.UTC),
)
continue
buffers[stream].append(chunk)
if (
stream is proc.stderr
and callback is not None
and callable(callback)
):
callback(
output=console_to_str(chunk),
timestamp=datetime.datetime.now(tz=datetime.UTC),
)
if stream is proc.stderr and has_callback and callback is not None:
if stderr_decoder is None:
stderr_decoder = _make_stderr_decoder(encoding)
decoded = stderr_decoder.decode(chunk, final=False)
if decoded:
callback(
output=decoded,
timestamp=datetime.datetime.now(tz=datetime.UTC),
)
finally:
# Restore blocking mode so any subsequent read by the caller behaves
# as expected; ignore failures (fd already closed, Windows pipe).
Expand Down
76 changes: 72 additions & 4 deletions src/libvcs/cmd/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
import re
import shlex
import string
import sys
import typing as t
from collections.abc import Mapping, Sequence

from libvcs._internal.query_list import QueryList
from libvcs._internal.run import (
_ENV,
ProgressCallbackProtocol,
_normalize_command_args,
reject_option_like,
Expand All @@ -32,6 +34,65 @@
_CMD = StrOrBytesPath | Sequence[StrOrBytesPath]
GitConfigValue: t.TypeAlias = bool | int | float | StrPath

_CONTROLLING_TTY_CACHE: tuple[int, bool] | None = None


def _has_controlling_tty() -> bool:
"""Return ``True`` when this process owns a controlling terminal.

On POSIX, Git's ``git_terminal_prompt()`` opens ``/dev/tty`` directly; when
no controlling terminal is attached, ``open("/dev/tty", O_RDWR)`` fails
immediately with ``ENXIO``, so ``subprocess.Popen`` can keep ``env=None``
and avoid copying and encoding ``os.environ`` on every invocation.
"""
global _CONTROLLING_TTY_CACHE
if sys.platform == "win32":
return True
pid = os.getpid()
if _CONTROLLING_TTY_CACHE is not None and _CONTROLLING_TTY_CACHE[0] == pid:
return _CONTROLLING_TTY_CACHE[1]
try:
fd = os.open("/dev/tty", os.O_RDONLY | os.O_NOCTTY)
except OSError:
has_tty = False
else:
os.close(fd)
has_tty = True
_CONTROLLING_TTY_CACHE = (pid, has_tty)
return has_tty


if sys.platform != "win32":

def _is_bytes_env(
env: Mapping[bytes, StrOrBytesPath] | Mapping[str, StrOrBytesPath],
) -> t.TypeGuard[Mapping[bytes, StrOrBytesPath]]:
return bool(env) and all(isinstance(key, bytes) for key in env)


def _default_git_env(env: _ENV | None) -> _ENV | None:
"""Default ``GIT_TERMINAL_PROMPT=0`` unless already set by caller or host."""
if env is None:
if "GIT_TERMINAL_PROMPT" in os.environ or not _has_controlling_tty():
return None
if sys.platform != "win32":
return {**os.environb, b"GIT_TERMINAL_PROMPT": b"0"}
return {**os.environ, "GIT_TERMINAL_PROMPT": "0"}
prompt_default = os.environ.get("GIT_TERMINAL_PROMPT", "0")
if sys.platform == "win32":
if "GIT_TERMINAL_PROMPT" in env:
return env
return {**env, "GIT_TERMINAL_PROMPT": prompt_default}
if _is_bytes_env(env):
if b"GIT_TERMINAL_PROMPT" in env:
return env
return {**env, b"GIT_TERMINAL_PROMPT": os.fsencode(prompt_default)}
str_env = {os.fsdecode(key): value for key, value in env.items()}
if "GIT_TERMINAL_PROMPT" in str_env:
return env
str_env["GIT_TERMINAL_PROMPT"] = prompt_default
return str_env


def _filter_flags(
value: GitFilterInput | None,
Expand Down Expand Up @@ -311,6 +372,10 @@ def run(
if "cwd" not in kwargs:
kwargs["cwd"] = self.path if cwd is None else cwd

resolved_env = _default_git_env(kwargs.get("env"))
if resolved_env is not None:
kwargs["env"] = resolved_env

#
# Print-and-exit
#
Expand Down Expand Up @@ -565,8 +630,10 @@ def fetch(
no_show_forced_updates: bool | None = None,
negotiate_only: bool | None = None,
_filter: GitFilterInput | None = None,
# libvcs special behavior
# Pass-through to run
config: Mapping[str, GitConfigValue] | None = None,
log_in_real_time: bool = False,
# libvcs special behavior
check_returncode: bool | None = None,
**kwargs: t.Any,
) -> str:
Expand Down Expand Up @@ -691,6 +758,7 @@ def fetch(
["fetch", *local_flags, "--", *required_flags],
config=config,
check_returncode=check_returncode,
log_in_real_time=log_in_real_time,
)

def rebase(
Expand Down Expand Up @@ -5489,7 +5557,7 @@ def _ls(self) -> list[str]:
>>> GitStashManager(path=example_git_repo.path)._ls()
[]
"""
result = self.run("list")
result = self.run("list", local_flags=["--no-color"])
if not result:
return []
return result.splitlines()
Expand Down Expand Up @@ -6069,7 +6137,7 @@ def _ls(
>>> '* master' in branches or 'master' in str(branches)
True
"""
flags = ["--list"]
flags = ["--list", "--no-color"]
if local_flags:
flags.extend(local_flags)
return self.run(local_flags=flags).splitlines()
Expand Down Expand Up @@ -8426,7 +8494,7 @@ def _ls(
>>> len(entries) > 0
True
"""
local_flags: list[str] = []
local_flags: list[str] = ["--no-color"]

if number is not None:
local_flags.extend(["-n", str(number)])
Expand Down
Loading
Loading