From 9247211a2dfcae29ad62df24c20cdb0d2e70a3fb Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 6 Dec 2026 05:06:32 -0600 Subject: [PATCH] scopes(fix): Deduplicate symlinked user configs why: Symlinking ~/.vcspull.yaml or ~/.config/vcspull into a dotfiles checkout caused resolve_sources() to re-discover the target file as an untrusted project config when running inside the dotfiles directory, and classify_scope() followed leaf symlinks before checking $HOME while omitting VCSPULL_CONFIGDIR and ~/.vcspull (#600). what: - Add expand_home(), resolve_home(), and user_config_dirs() in vcspull.util, ignoring blank VCSPULL_CONFIGDIR and XDG_CONFIG_HOME - Deduplicate resolved real paths across system, user, and project scopes in resolve_sources() - Match lexical candidates against symlink chains of user and system config roots in classify_scope() while keeping rogue project symlinks classified as project - Collapse symlinked $HOME realpaths in PrivatePath and cover dotfiles and rogue-symlink topologies in tests and docs --- CHANGES | 11 ++ docs/configuration/scopes.md | 7 +- src/vcspull/_internal/private_path.py | 22 +-- src/vcspull/_internal/scopes.py | 186 ++++++++++++++++++------ src/vcspull/config.py | 7 +- src/vcspull/util.py | 195 ++++++++++++++++++++++---- tests/cli/test_config.py | 27 ++++ tests/test_scopes.py | 123 ++++++++++++++++ tests/test_utils.py | 32 ++++- 9 files changed, 525 insertions(+), 85 deletions(-) diff --git a/CHANGES b/CHANGES index 1a5a16f8c..7281d1653 100644 --- a/CHANGES +++ b/CHANGES @@ -38,6 +38,17 @@ $ uvx --from 'vcspull' --prerelease allow vcspull _Notes on upcoming releases will be added here_ +### Fixes + +#### Symlinked user configuration deduplication (#600) + +{ref}`Configuration scope resolution ` now deduplicates resolved +paths across `system`, `user`, and `project` scopes so symlinked user dotfiles +(`~/.vcspull.yaml`, `~/.config/vcspull`, `$VCSPULL_CONFIGDIR`, or `~/.vcspull` +pointing into a dotfiles checkout) stay in the `user` scope and are not +re-discovered as `project` configurations when running inside the dotfiles +directory (#600). + ## vcspull v1.72.0 (2026-12-05) vcspull v1.72.0 excludes archived and deletion-scheduled GitLab groups and diff --git a/docs/configuration/scopes.md b/docs/configuration/scopes.md index ecd551de6..8c9646347 100644 --- a/docs/configuration/scopes.md +++ b/docs/configuration/scopes.md @@ -24,8 +24,11 @@ named by more than one scope comes from the strongest. | project | `.vcspull.{yaml,yml,json}` in each ancestor of your working directory, outermost first | gated | Passing `-f/--file` replaces that entire stack with the one file you name, so -existing scripts and CI jobs behave exactly as they always have. When write -commands classify a target path, files under `/etc/vcspull` or +existing scripts and CI jobs behave exactly as they always have. Symlinked user +configurations — such as `~/.vcspull.yaml` or `~/.config/vcspull/` pointing into +a dotfiles checkout — keep their `user` scope and are not loaded a second time +as `project` configurations when you work inside that dotfiles directory. When +write commands classify a target path, files under `/etc/vcspull` or `$XDG_CONFIG_DIRS/vcspull` (`/etc/xdg/vcspull` when `XDG_CONFIG_DIRS` is unset) are also treated as `system` scope. diff --git a/src/vcspull/_internal/private_path.py b/src/vcspull/_internal/private_path.py index b67540f16..26babcc00 100644 --- a/src/vcspull/_internal/private_path.py +++ b/src/vcspull/_internal/private_path.py @@ -45,22 +45,28 @@ def __new__( @classmethod def _collapse_home(cls, value: str) -> str: - """Collapse the user's home directory to ``~`` in ``value``.""" + """Collapse the user's home directory (and its realpath) to ``~``.""" if value.startswith("~"): return value - home = str(pathlib.Path.home()) - if value == home: - return "~" + target_home = pathlib.Path.home().expanduser() + candidates = tuple( + dict.fromkeys((str(target_home), os.path.realpath(target_home))), + ) separators = {os.sep} if os.altsep: separators.add(os.altsep) - for sep in separators: - home_with_sep = home + sep - if value.startswith(home_with_sep): - return "~" + value[len(home) :] + for candidate in candidates: + if not candidate or candidate == os.sep: + continue + if value == candidate: + return "~" + for sep in separators: + home_with_sep = candidate + sep + if value.startswith(home_with_sep): + return "~" + value[len(candidate) :] return value diff --git a/src/vcspull/_internal/scopes.py b/src/vcspull/_internal/scopes.py index e131700e5..88ca514c5 100644 --- a/src/vcspull/_internal/scopes.py +++ b/src/vcspull/_internal/scopes.py @@ -25,7 +25,7 @@ import pathlib import typing as t -from ..util import get_config_dir +from ..util import expand_home, get_config_dir, resolve_home, user_config_dirs if t.TYPE_CHECKING: from collections.abc import Iterable, Mapping @@ -42,6 +42,11 @@ PROJECT_CONFIG_STEM: t.Final = ".vcspull" """Basename of a project configuration, before its suffix.""" +_PROJECT_FILENAMES: t.Final = frozenset( + f"{PROJECT_CONFIG_STEM}{suffix}" for suffix in CONFIG_SUFFIXES +) +_HOME_DOTFILE_NAMES: t.Final = (".vcspull.yaml", ".vcspull.json") + _TRUTHY: t.Final = frozenset({"1", "true", "yes", "on"}) @@ -274,7 +279,9 @@ def resolve_sources( Returns ------- tuple of ConfigSource - Existing files only, ordered weakest to strongest. + Existing files only, ordered weakest to strongest, deduplicated by + resolved target path so symlinked user dotfiles are never re-added as + project configurations. Raises ------ @@ -300,37 +307,87 @@ def resolve_sources( """ from ..config import find_home_config_files - home = (home or pathlib.Path.home()).expanduser() + resolved_home = resolve_home(home, environ) sources: list[ConfigSource] = [] - - sources.extend( - ConfigSource("system", path, SYSTEM_CONFIG_DIR) - for path in _config_files_in(SYSTEM_CONFIG_DIR) - ) - - user_dir = get_config_dir() - sources.extend( - ConfigSource("user", path, user_dir) for path in _config_files_in(user_dir) - ) + seen: set[pathlib.Path] = set() + + def _append_source( + scope: ConfigScope, + path: pathlib.Path, + trust_root: pathlib.Path, + ) -> None: + real_path = _real(path) + if real_path in seen: + return + seen.add(real_path) + sources.append(ConfigSource(scope, path, trust_root)) + + for path in _config_files_in(SYSTEM_CONFIG_DIR): + _append_source("system", path, SYSTEM_CONFIG_DIR) + + user_dir = get_config_dir(home=resolved_home, environ=environ) + for path in _config_files_in(user_dir): + _append_source("user", path, user_dir) # Delegated rather than reimplemented so that owning two home dotfiles # still raises MultipleConfigError, as it did before scopes existed. - sources.extend( - ConfigSource("user", path, path.parent) - for path in find_home_config_files(home=home) - ) + for path in find_home_config_files(home=resolved_home): + _append_source("user", path, path.parent) if include_project and not env_flag("VCSPULL_NO_PROJECT", environ): - ceilings = ceiling_paths(environ, home=home) + ceilings = ceiling_paths(environ, home=resolved_home) for directory in project_dirs(cwd, ceilings=ceilings): - sources.extend( - ConfigSource("project", path, directory) - for path in _project_files_in(directory) - ) + for path in _project_files_in(directory): + _append_source("project", path, directory) return tuple(sources) +def _lexical_norm(path: pathlib.Path) -> pathlib.Path: + """Collapse ``.`` and ``..`` segments in *path* without following symlinks.""" + base = path if path.is_absolute() else pathlib.Path.cwd() / path + stack: list[str] = [] + for part in base.parts[1:]: + if part in {"", "."}: + continue + if part == "..": + if stack: + stack.pop() + else: + stack.append(part) + return pathlib.Path(base.anchor, *stack) + + +def _follow_hops( + path: pathlib.Path, + *, + raw_home: pathlib.Path, + real_home: pathlib.Path, +) -> tuple[pathlib.Path, ...]: + """Return lexical, intermediate symlink, and resolved paths for *path*.""" + hops: list[pathlib.Path] = [] + visited: set[pathlib.Path] = set() + cur = _lexical_norm(path) + + for _ in range(40): + if cur in visited: + break + visited.add(cur) + hops.append(cur) + if raw_home != real_home and _is_within(cur, raw_home): + hops.append(real_home / cur.relative_to(raw_home)) + if not cur.is_symlink(): + break + try: + target = cur.readlink() + except OSError: + break + cur = _lexical_norm(target if target.is_absolute() else cur.parent / target) + + hops.append(_real(path)) + return tuple(dict.fromkeys(hops)) + + def classify_scope( config_path: pathlib.Path, *, @@ -342,8 +399,8 @@ def classify_scope( Unlike :func:`resolve_sources`, this answers the question for a path the caller already holds — a ``--file`` argument, or the file a write command - is about to touch. A path that is neither user, system, nor inside the - working directory is ``external``. + is about to touch. A path that is neither user, system, nor inside an + active project directory is ``external``. Parameters ---------- @@ -375,36 +432,79 @@ def classify_scope( ... ) 'external' """ - resolved = _real(config_path) - home = _real(home) - cwd = _real(cwd) - - if resolved.parent == home and resolved.name in { - f"{PROJECT_CONFIG_STEM}{suffix}" for suffix in CONFIG_SUFFIXES - }: - return "user" - - xdg_config_home = _real( - pathlib.Path(environ.get("XDG_CONFIG_HOME", home / ".config")), + raw_home = _lexical_norm(resolve_home(home, environ)) + real_home = _real(raw_home) + lexical_cwd = _lexical_norm(expand_home(cwd, raw_home)) + expanded = expand_home(config_path, raw_home) + if not expanded.is_absolute(): + expanded = lexical_cwd / expanded + + lexical = _lexical_norm(expanded) + candidates: tuple[pathlib.Path, ...] = ( + (lexical, real_home / lexical.relative_to(raw_home)) + if raw_home != real_home and _is_within(lexical, raw_home) + else (lexical,) ) - if _is_within(resolved, xdg_config_home / "vcspull"): + + if any( + cand.parent in {raw_home, real_home} and cand.name in _PROJECT_FILENAMES + for cand in candidates + ): return "user" - xdg_config_dirs = environ.get("XDG_CONFIG_DIRS") + for user_base in user_config_dirs(home=raw_home, environ=environ): + for hop in _follow_hops(user_base, raw_home=raw_home, real_home=real_home): + if any(_is_within(cand, hop) for cand in candidates): + return "user" + + for dotfile_name in _HOME_DOTFILE_NAMES: + dotfile = raw_home / dotfile_name + if dotfile.is_file(): + hops = _follow_hops(dotfile, raw_home=raw_home, real_home=real_home) + if any(cand in hops for cand in candidates): + return "user" + + active_user_dir = get_config_dir(home=raw_home, environ=environ) + for user_file in _config_files_in(active_user_dir): + hops = _follow_hops(user_file, raw_home=raw_home, real_home=real_home) + if any(cand in hops for cand in candidates): + return "user" + + xdg_config_dirs = environ.get("XDG_CONFIG_DIRS", "").strip() system_bases = [SYSTEM_CONFIG_DIR] if xdg_config_dirs: system_bases.extend( - pathlib.Path(entry) / "vcspull" + expand_home(pathlib.Path(entry.strip()), raw_home) / "vcspull" for entry in xdg_config_dirs.split(os.pathsep) - if entry + if entry.strip() ) else: system_bases.append(pathlib.Path("/etc/xdg/vcspull")) for base in system_bases: - if _is_within(resolved, _real(base)): - return "system" - - return "project" if _is_within(resolved, cwd) else "external" + for hop in _follow_hops(base, raw_home=raw_home, real_home=real_home): + if any(_is_within(cand, hop) for cand in candidates): + return "system" + for sys_file in _config_files_in(base): + hops = _follow_hops(sys_file, raw_home=raw_home, real_home=real_home) + if any(cand in hops for cand in candidates): + return "system" + + real_cwd = _real(lexical_cwd) + entry_dir = _real(expanded.parent) + ceilings = ceiling_paths(environ, home=real_home) + active_project_dirs = { + _real(directory) for directory in project_dirs(lexical_cwd, ceilings=ceilings) + } + is_ancestor_project_config = ( + expanded.name in _PROJECT_FILENAMES and entry_dir in active_project_dirs + ) + return ( + "project" + if is_ancestor_project_config + or _is_within(entry_dir, real_cwd) + or _is_within(lexical.parent, lexical_cwd) + else "external" + ) def _is_within(path: pathlib.Path, directory: pathlib.Path) -> bool: diff --git a/src/vcspull/config.py b/src/vcspull/config.py index 27b61b9a9..2e474d83f 100644 --- a/src/vcspull/config.py +++ b/src/vcspull/config.py @@ -2246,18 +2246,19 @@ def ensure_config_trusted( True """ cwd = cwd or pathlib.Path.cwd() - if explicit or not config_path.is_file(): + anchor = config_path if config_path.is_absolute() else cwd / config_path + if explicit or not anchor.is_file(): return True scope = scopes.classify_scope( - config_path, + anchor, cwd=cwd, home=pathlib.Path.home(), ) if scope != "project": return True - source = scopes.ConfigSource("project", config_path, config_path.parent) + source = scopes.ConfigSource("project", anchor, anchor.parent) escaping = source_escapes(source, cwd=cwd) if not escaping: return True diff --git a/src/vcspull/util.py b/src/vcspull/util.py index d23e4ee11..123d0eb8f 100644 --- a/src/vcspull/util.py +++ b/src/vcspull/util.py @@ -2,52 +2,185 @@ from __future__ import annotations +import collections.abc import os import pathlib import typing as t -from collections.abc import Mapping, MutableMapping LEGACY_CONFIG_DIR = pathlib.Path("~/.vcspull/").expanduser() # remove dupes of this -def get_config_dir() -> pathlib.Path: +def expand_home(path: pathlib.Path, home: pathlib.Path) -> pathlib.Path: + """Expand leading ``~`` or ``~/...`` in *path* against *home*. + + Parameters + ---------- + path : pathlib.Path + Path that may begin with ``~``. + home : pathlib.Path + Directory to substitute for ``~``. + + Returns + ------- + pathlib.Path + Path with leading ``~`` replaced by *home*, or *path* unchanged. + + Examples + -------- + >>> expand_home(pathlib.Path("~/.vcspull.yaml"), pathlib.Path("/home/u")) + PosixPath('/home/u/.vcspull.yaml') + >>> expand_home(pathlib.Path("~"), pathlib.Path("/home/u")) + PosixPath('/home/u') + >>> expand_home(pathlib.Path("/etc/vcspull"), pathlib.Path("/home/u")) + PosixPath('/etc/vcspull') """ - Return vcspull configuration directory. + raw = str(path) + if raw == "~": + return home + for sep in (os.sep, *([os.altsep] if os.altsep else [])): + prefix = f"~{sep}" + if raw.startswith(prefix): + return home / raw[len(prefix) :] + return path + + +def resolve_home( + home: pathlib.Path | None = None, + environ: collections.abc.Mapping[str, str] | None = None, +) -> pathlib.Path: + """Resolve the effective user home directory from *home* or *environ*. - ``VCSPULL_CONFIGDIR`` environmental variable has precedence if set. We also - evaluate XDG default directory from XDG_CONFIG_HOME environmental variable - if set or its default. Then the old default ~/.vcspull is returned for - compatibility. + Parameters + ---------- + home : pathlib.Path, optional + Explicit home directory override. + environ : Mapping[str, str], optional + Environment mapping inspected when *home* is ``None``. Returns ------- pathlib.Path - Expanded path to the vcspull configuration directory. + Expanded home directory path. + + Examples + -------- + >>> resolve_home(pathlib.Path("/custom/home")) + PosixPath('/custom/home') + >>> resolve_home(None, {"HOME": "/env/home"}) + PosixPath('/env/home') + """ + if home is not None: + return home.expanduser() + if environ is not None: + env_home = environ.get("HOME", "").strip() + if env_home: + return pathlib.Path(env_home).expanduser() + return pathlib.Path.home().expanduser() + + +def user_config_dirs( + *, + home: pathlib.Path | None = None, + environ: collections.abc.Mapping[str, str] | None = None, +) -> tuple[pathlib.Path, ...]: + """Return ordered candidate user configuration directories. + + Empty or whitespace-only ``VCSPULL_CONFIGDIR`` and ``XDG_CONFIG_HOME`` + values are ignored so ``Path("")`` never resolves to the working directory. + + Parameters + ---------- + home : pathlib.Path, optional + Home directory to resolve ``~`` and default config locations against. + environ : Mapping[str, str], optional + Environment mapping to inspect. Defaults to :data:`os.environ`. + + Returns + ------- + tuple of pathlib.Path + Ordered candidate directories: optional ``VCSPULL_CONFIGDIR``, + ``XDG_CONFIG_HOME/vcspull`` (or ``~/.config/vcspull``), and + ``~/.vcspull``. + + Examples + -------- + >>> user_config_dirs( + ... home=pathlib.Path("/home/u"), + ... environ={"VCSPULL_CONFIGDIR": "", "XDG_CONFIG_HOME": " "}, + ... ) + (PosixPath('/home/u/.config/vcspull'), PosixPath('/home/u/.vcspull')) + >>> user_config_dirs( + ... home=pathlib.Path("/home/u"), + ... environ={"VCSPULL_CONFIGDIR": "~/c", "XDG_CONFIG_HOME": "/x"}, + ... ) + (PosixPath('/home/u/c'), PosixPath('/x/vcspull'), PosixPath('/home/u/.vcspull')) """ - paths: list[pathlib.Path] = [] - if "VCSPULL_CONFIGDIR" in os.environ: - paths.append(pathlib.Path(os.environ["VCSPULL_CONFIGDIR"])) - if "XDG_CONFIG_HOME" in os.environ: - paths.append(pathlib.Path(os.environ["XDG_CONFIG_HOME"]) / "vcspull") + env = os.environ if environ is None else environ + resolved_home = resolve_home(home, environ) + + dirs: list[pathlib.Path] = [] + vcspull_configdir = env.get("VCSPULL_CONFIGDIR", "").strip() + if vcspull_configdir: + dirs.append(expand_home(pathlib.Path(vcspull_configdir), resolved_home)) + + xdg_config_home = env.get("XDG_CONFIG_HOME", "").strip() + if xdg_config_home: + dirs.append( + expand_home(pathlib.Path(xdg_config_home), resolved_home) / "vcspull", + ) else: - paths.append(pathlib.Path("~/.config/vcspull/")) - paths.append(LEGACY_CONFIG_DIR) + dirs.append(resolved_home / ".config" / "vcspull") + + dirs.append(resolved_home / ".vcspull") + return tuple(dirs) + - for path in paths: - path = path.expanduser() +def get_config_dir( + *, + home: pathlib.Path | None = None, + environ: collections.abc.Mapping[str, str] | None = None, +) -> pathlib.Path: + """Return the active user configuration directory. + + Checks ``VCSPULL_CONFIGDIR`` first, then ``XDG_CONFIG_HOME/vcspull`` (or + ``~/.config/vcspull`` when ``XDG_CONFIG_HOME`` is unset), and finally + ``~/.vcspull``, returning the first directory that exists or ``~/.vcspull`` + when none exist yet. + + Parameters + ---------- + home : pathlib.Path, optional + Home directory to resolve default config directories against. + environ : Mapping[str, str], optional + Environment mapping to inspect. Defaults to :data:`os.environ`. + + Returns + ------- + pathlib.Path + Expanded path to the vcspull configuration directory. + + Examples + -------- + >>> xdg = tmp_path / "xdg" + >>> (xdg / "vcspull").mkdir(parents=True) + >>> get_config_dir(home=tmp_path, environ={"XDG_CONFIG_HOME": str(xdg)}) == ( + ... xdg / "vcspull" + ... ) + True + """ + candidates = user_config_dirs(home=home, environ=environ) + for path in candidates: if path.is_dir(): return path - - # Return last path as default if none of the previous ones matched - return LEGACY_CONFIG_DIR.expanduser() + return candidates[-1] -T = t.TypeVar("T", bound=MutableMapping[str, object]) +T = t.TypeVar("T", bound=collections.abc.MutableMapping[str, object]) def update_dict( d: T, - u: Mapping[str, object], + u: collections.abc.Mapping[str, object], ) -> T: """Return updated dict. @@ -66,14 +199,20 @@ def update_dict( Thanks: http://stackoverflow.com/a/3233356 """ for k, v in u.items(): - if isinstance(v, Mapping): + if isinstance(v, collections.abc.Mapping): current = d.get(k) - if isinstance(current, MutableMapping): - r = update_dict(current, t.cast("Mapping[str, object]", v)) - elif isinstance(current, Mapping): - r = update_dict(dict(current), t.cast("Mapping[str, object]", v)) + if isinstance(current, collections.abc.MutableMapping): + r = update_dict( + current, + t.cast("collections.abc.Mapping[str, object]", v), + ) + elif isinstance(current, collections.abc.Mapping): + r = update_dict( + dict(current), + t.cast("collections.abc.Mapping[str, object]", v), + ) else: - r = update_dict({}, t.cast("Mapping[str, object]", v)) + r = update_dict({}, t.cast("collections.abc.Mapping[str, object]", v)) d[k] = r else: d[k] = v diff --git a/tests/cli/test_config.py b/tests/cli/test_config.py index 7aeeb1a3d..644fb6a5d 100644 --- a/tests/cli/test_config.py +++ b/tests/cli/test_config.py @@ -339,3 +339,30 @@ def test_config_ls_audits_shared_kept_ignored_lost_and_dropped_aliases( in out ) assert "alias 'dropped-handle' dropped from 'dup_repo'" in out + + +def test_config_ls_in_dotfiles_repo_lists_symlinked_user_config_once( + tmp_path: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Running ``vcspull config ls`` inside ~/.dot-config shows one user row (#600).""" + home = tmp_path / "home" + dotfiles = home / ".dot-config" + dotfiles.mkdir(parents=True) + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("XDG_CONFIG_HOME", str(home / ".config")) + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) + monkeypatch.delenv("VCSPULL_CEILING_PATHS", raising=False) + monkeypatch.delenv("VCSPULL_NO_PROJECT", raising=False) + monkeypatch.chdir(dotfiles) + + manifest = write_config( + dotfiles / ".vcspull.yaml", + "~/study/python/:\n libtmux: git+https://github.com/tmux-python/libtmux.git\n", + ) + (home / ".vcspull.yaml").symlink_to(manifest) + + cli(["config", "ls"]) + out = capsys.readouterr().out + assert out == "user ~/.vcspull.yaml 1 repo\n\n1 repository in effect.\n" diff --git a/tests/test_scopes.py b/tests/test_scopes.py index f2d6b8bf9..127742d22 100644 --- a/tests/test_scopes.py +++ b/tests/test_scopes.py @@ -686,3 +686,126 @@ def test_project_file_never_removes_or_replaces_user_or_system_alias( assert len(ignored) == 1 assert "alias 'hijack-docs' of the entry 'docs'" in ignored[0] assert "keeps its alias 'libtmux-docs'" in ignored[0] + + +def test_symlinked_home_dotfile_in_dotfiles_repo_loads_once_as_user( + tmp_path: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Symlinked ~/.vcspull.yaml -> ~/.dot-config/.vcspull.yaml is user-only (#600).""" + home = tmp_path / "home" + dotfiles = home / ".dot-config" + dotfiles.mkdir(parents=True) + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("XDG_CONFIG_HOME", str(home / ".config")) + monkeypatch.delenv("VCSPULL_CEILING_PATHS", raising=False) + + manifest = write_config( + dotfiles / ".vcspull.yaml", + "~/study/python/:\n libtmux: git+https://github.com/tmux-python/libtmux.git\n", + ) + user_link = home / ".vcspull.yaml" + user_link.symlink_to(manifest) + + sources = scopes.resolve_sources(cwd=dotfiles, home=home) + assert [(s.scope, s.path) for s in sources] == [("user", user_link)] + assert scopes.classify_scope(user_link, cwd=dotfiles, home=home) == "user" + assert scopes.classify_scope(manifest, cwd=dotfiles, home=home) == "user" + + repos = config.load_scoped_configs(cwd=dotfiles) + assert [repo["name"] for repo in repos] == ["libtmux"] + + +def test_symlinked_user_config_dirs_and_chained_dotfiles_classify_as_user( + tmp_path: pathlib.Path, +) -> None: + """Symlinked user dirs, VCSPULL_CONFIGDIR, ~/.vcspull, and chains stay user.""" + home = tmp_path / "home" + dotfiles = home / ".dot-config" + xdg_target = dotfiles / "vcspull-xdg" + custom_target = dotfiles / "vcspull-custom" + legacy_target = dotfiles / "vcspull-legacy" + for d in (xdg_target, custom_target, legacy_target): + d.mkdir(parents=True) + + xdg_root = home / ".config" + xdg_root.mkdir(parents=True) + (xdg_root / "vcspull").symlink_to(xdg_target, target_is_directory=True) + (home / ".vcspull").symlink_to(legacy_target, target_is_directory=True) + + chained_real = write_config( + dotfiles / "vcspull-base.yaml", + "~/work/:\n app: git+https://example.com/app.git\n", + ) + chained_mid = dotfiles / ".vcspull.yaml" + chained_mid.symlink_to(chained_real) + (home / ".vcspull.yaml").symlink_to(chained_mid) + + env = { + "HOME": str(home), + "XDG_CONFIG_HOME": str(xdg_root), + "VCSPULL_CONFIGDIR": str(custom_target), + } + + sources = scopes.resolve_sources(cwd=dotfiles, home=home, environ=env) + assert [(s.scope, s.path) for s in sources] == [("user", home / ".vcspull.yaml")] + + for user_path in ( + home / ".vcspull.yaml", + chained_mid, + chained_real, + xdg_root / "vcspull" / "new.yaml", + xdg_target / "new.yaml", + custom_target / "custom.yaml", + home / ".vcspull" / "legacy.yaml", + legacy_target / "legacy.yaml", + ): + assert ( + scopes.classify_scope(user_path, cwd=dotfiles, home=home, environ=env) + == "user" + ), f"expected user scope for {user_path}" + + +def test_rogue_project_symlinks_to_user_config_stay_project( + tmp_path: pathlib.Path, +) -> None: + """Project symlinks pointing at user configs or user dirs never classify as user.""" + home = tmp_path / "home" + xdg_vcspull = home / ".config" / "vcspull" + xdg_vcspull.mkdir(parents=True) + user_file = write_config( + home / ".vcspull.yaml", + "~/work/:\n safe: git+https://example.com/safe.git\n", + ) + write_config( + xdg_vcspull / "work.yaml", + "~/work/:\n xdg: git+https://example.com/xdg.git\n", + ) + + evil = home / "study" / "evil-repo" + evil_sub = evil / "nested" + evil_sub.mkdir(parents=True) + rogue_file_link = evil / ".vcspull.yaml" + rogue_file_link.symlink_to(user_file) + rogue_dir_link = evil / "cfg-link" + rogue_dir_link.symlink_to(xdg_vcspull, target_is_directory=True) + + env = {"HOME": str(home), "XDG_CONFIG_HOME": str(home / ".config")} + + sources = scopes.resolve_sources(cwd=evil_sub, home=home, environ=env) + assert [s.scope for s in sources] == ["user", "user"] + assert all(s.path != rogue_file_link for s in sources) + + assert ( + scopes.classify_scope(rogue_file_link, cwd=evil_sub, home=home, environ=env) + == "project" + ) + assert ( + scopes.classify_scope( + rogue_dir_link / "work.yaml", + cwd=evil, + home=home, + environ=env, + ) + == "project" + ) diff --git a/tests/test_utils.py b/tests/test_utils.py index f1875b984..49060892c 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -4,7 +4,8 @@ import typing as t -from vcspull.util import get_config_dir +from vcspull._internal.private_path import PrivatePath +from vcspull.util import expand_home, get_config_dir, resolve_home, user_config_dirs if t.TYPE_CHECKING: import pathlib @@ -38,3 +39,32 @@ def test_vcspull_configdir_no_xdg(monkeypatch: pytest.MonkeyPatch) -> None: """Test retrieving config directory without XDG_CONFIG_HOME set.""" monkeypatch.delenv("XDG_CONFIG_HOME") assert get_config_dir() + + +def test_user_config_dirs_ignores_empty_env_vars(tmp_path: pathlib.Path) -> None: + """Empty VCSPULL_CONFIGDIR and XDG_CONFIG_HOME do not resolve to cwd.""" + home = tmp_path / "home" + home.mkdir() + dirs = user_config_dirs( + home=home, + environ={"VCSPULL_CONFIGDIR": "", "XDG_CONFIG_HOME": " "}, + ) + assert dirs == (home / ".config" / "vcspull", home / ".vcspull") + assert resolve_home(None, {"HOME": str(home)}) == home + assert expand_home(tmp_path / "x", home) == tmp_path / "x" + + +def test_private_path_collapses_symlinked_home_realpath( + tmp_path: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """PrivatePath collapses both $HOME and its resolved realpath to ~.""" + real_home = tmp_path / "var" / "home" / "u" + real_home.mkdir(parents=True) + link_home = tmp_path / "home" / "u" + link_home.parent.mkdir(parents=True) + link_home.symlink_to(real_home, target_is_directory=True) + + monkeypatch.setenv("HOME", str(link_home)) + assert str(PrivatePath(link_home / ".vcspull.yaml")) == "~/.vcspull.yaml" + assert str(PrivatePath(real_home / ".vcspull.yaml")) == "~/.vcspull.yaml"