Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

27.3 KB
Raw Blame
"""Ownership resolution for a repo-relative path.

Walks from the repo root toward the path, collecting ``owners.yaml`` (or alias file)
contributions, honoring ``inherit: false`` as a hard cut, and merges them nearest-file-wins
per field. SPEC.md in this package defines the format.
"""

from __future__ import annotations

import sys
import stat
import subprocess
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import Literal, Protocol, TypedDict, cast, runtime_checkable

from .matcher import SEP, compile_pattern, normalize_path
from .schema import (
    OWNERS_FILENAME,
    UNSET,
    OwnersFile,
    Producer,
    RepoSettings,
    TeamEntry,
    _Unset,
    parse_alias_file_as_owners,
    parse_owners_file,
)


@dataclass(frozen=True)
class TeamChannel:
    """Where a team's Slack messages go, and how that was decided.

    ``declared`` separates an answer for this purpose and producer from the derived ``#<slug>``: a
    caller routing real messages usually treats a declaration as a decision to honor and a
    derivation as a guess to verify, and cannot tell them apart from ``channel`` alone.
    """

    channel: str | None
    declared: bool


# What a caller wants a channel for. Spelled out as a type rather than taken as a bare string, so
# a purpose this package has never heard of is a type error at the call site instead of silently
# resolving to the channel where people are.
Purpose = Literal["slack", "notifications"]
DEFAULT_PURPOSE: Purpose = "slack"


def team_channel(
    slug: str,
    teams: Mapping[str, TeamEntry],
    purpose: Purpose = DEFAULT_PURPOSE,
    producer: Producer | None = None,
) -> TeamChannel:
    """The Slack channel for a team slug and a purpose, else the derived ``#<slug>``.

    ``purpose`` is "slack" (where people are) or "notifications" (where automation posts).
    "notifications" falls back to "slack", so a team that never separates automation from people
    keeps one channel and one entry.

    ``producer`` names the automation asking, and only matters when the team declared a per-producer
    ``notifications`` mapping. A mapping that does not name the producer falls through to ``slack``,
    so silencing one bot leaves the others where they were.

    A declared ``false`` means the team has no channel for that purpose, which is different from
    having no entry. The first is an answer and stops the lookup; the second falls through.
    """
    entry = teams.get(slug)
    if entry is not None:
        candidates = (entry.notifications, entry.slack) if purpose == "notifications" else (entry.slack,)
        for candidate in candidates:
            if isinstance(candidate, Mapping):
                value = candidate.get(producer) if producer is not None else None
            else:
                value = candidate
            if value is not None:
                # Schema only admits `false`; any bool means "no channel".
                return TeamChannel(channel=value if isinstance(value, str) else None, declared=True)
    return TeamChannel(channel=f"#{slug}", declared=False)


def teams_registry(text: str) -> dict[str, TeamEntry]:
    """The root ``owners.yaml``'s ``teams:`` registry, from the file's raw contents.

    For callers holding the bytes rather than a checkout; ``OwnersResolver`` reads it off disk
    itself. An unusable document yields an empty registry rather than raising, so a malformed root
    file degrades to derived channels instead of declaring that no team has one.
    """
    parsed, _errors = parse_owners_file(text, path=Path(OWNERS_FILENAME), directory="")
    return dict(parsed.teams) if parsed is not None else {}


PathKind = Literal["dir", "file"]


@dataclass(frozen=True)
class Addition:
    """The new part of a path that the resolver's tree does not hold: the path nearest the root that
    the tree lacks, and the owners of additions at that part (SPEC section 3.6)."""

    path: str
    additions: list[str]


@dataclass
class Resolution:
    """The resolved ownership of a single path."""

    path: str
    owners: list[str] | None  # None for both explicit-null and no-contribution
    status: str
    slack: str | None
    source: str | None  # repo-relative path of the file that decided owners
    unowned_by_design: bool  # explicit `owners: null` exemption
    # The owners of additions at the path, separate from its owners. Every other field is nearest-
    # file-wins; this one collects every declaration on the walk, so a nested file cannot drop what
    # an ancestor set. `inherit: false` still cuts it like everything else.
    additions: list[str] = field(default_factory=list)
    # Set only when the resolver reads a tree and the path is not in it, such as a file that a change
    # adds when the tree is the version before the change.
    added: Addition | None = None
    sensitive: bool = False

    @property
    def is_owned(self) -> bool:
        return bool(self.owners)

    @property
    def is_unowned(self) -> bool:
        """Unowned and NOT exempt — what the coverage check fails on."""
        return not self.owners and not self.unowned_by_design


class WireResolution(TypedDict):
    """The JSON wire shape shared by ``hogli owners:resolve --json`` and the
    dependency-light ``python -m owners_yaml`` entrypoint. Both emit
    exactly this dict per path so consumers see one format."""

    owners: list[str]
    status: str
    slack: str | None
    source: str | None
    additions: list[str]
    added: WireAddition | None
    sensitive: bool


class WireAddition(TypedDict):
    path: str
    additions: list[str]


def resolution_to_wire(r: Resolution) -> WireResolution:
    return {
        "owners": r.owners or [],
        "status": r.status,
        "slack": r.slack,
        "source": r.source,
        "additions": r.additions,
        "added": {"path": r.added.path, "additions": r.added.additions} if r.added is not None else None,
        "sensitive": r.sensitive,
    }


def read_stdin_paths() -> list[str]:
    """Newline-delimited repo-relative paths from stdin, blanks dropped."""
    return [line.strip() for line in sys.stdin.read().splitlines() if line.strip()]


@dataclass
class ParsedOwnershipFile:
    """One tracked ownership file, parsed once."""

    path: Path  # absolute
    rel_dir: str  # repo-relative posix dir ("" = root)
    name: str  # OWNERS_FILENAME or one of the configured alias file names
    parsed: OwnersFile | None
    errors: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)

    @property
    def is_alias(self) -> bool:
        return self.name != OWNERS_FILENAME


@dataclass
class _Merged:
    owners: list[str] | None | _Unset = UNSET
    status: str | _Unset = UNSET
    source: str | None = None
    additions: list[str] = field(default_factory=list)
    sensitive: bool | _Unset = UNSET


def _union(*groups: Iterable[str]) -> list[str]:
    """Every entry across ``groups``, first occurrence first, without duplicates."""
    return list(dict.fromkeys(item for group in groups for item in group))


class RepoRootNotFound(Exception):
    """No repo root was given and the working directory is not inside a git worktree."""


def _git_repo_root() -> Path:
    try:
        result = subprocess.run(
            ["git", "rev-parse", "--show-toplevel"],
            capture_output=True,
            text=True,
            check=True,
        )
    except (OSError, subprocess.CalledProcessError) as exc:
        raise RepoRootNotFound(
            "not inside a git worktree; pass --repo-root with the directory that holds the ownership files"
        ) from exc
    return Path(result.stdout.strip())


def _walk_files(root: Path, prefix: str | None) -> list[str]:
    """Repo-relative paths of every file under ``root``, for a tree that is not a git worktree."""
    start = root / prefix if prefix else root
    if start.is_file():
        return [start.relative_to(root).as_posix()]
    return sorted(
        path.relative_to(root).as_posix()
        for path in start.rglob("*")
        if path.is_file() and ".git" not in path.relative_to(root).parts
    )


class OwnershipSource(Protocol):
    """An ownership file's text by repo-relative path, or None when absent. Only ``resolve`` reads
    through this; lint and format still walk a real worktree."""

    def read(self, path: str) -> str | None: ...


@runtime_checkable
class BatchOwnershipSource(OwnershipSource, Protocol):
    """A source that pays per read, such as one that fetches over a network. ``read_all`` hands it
    every file a batch can need before the resolver reads any, so it can fetch them together.

    ``map`` calls it twice: once for the root ``owners.yaml`` alone, which names the alias files,
    then once for the whole batch. No file is read before a ``read_all`` that covers it."""

    def read_all(self, paths: list[str]) -> None: ...


@runtime_checkable
class TreeSource(OwnershipSource, Protocol):
    """A source that can also tell whether the tree holds a path, and as what. The resolver needs
    this to report a path that the tree does not hold (``Resolution.added``)."""

    def path_kind(self, path: str) -> PathKind | None: ...


@dataclass(frozen=True)
class DiskSource:
    """Ownership files read from a worktree."""

    repo_root: Path

    def read(self, path: str) -> str | None:
        file = self.repo_root / path
        return file.read_text() if file.is_file() else None

    def path_kind(self, path: str) -> PathKind | None:
        # lstat does not follow a symlink: git stores a symlink as a file, so a symlink to a
        # directory is a leaf of the tree, and a dangling link still counts as present.
        try:
            mode = (self.repo_root / path).lstat().st_mode
        except (FileNotFoundError, NotADirectoryError):
            return None
        return "dir" if stat.S_ISDIR(mode) else "file"


class GitRefSource:
    """Ownership files as a git ref holds them, for a check on what a push carries rather than the worktree."""

    def __init__(self, repo_root: Path, ref: str = "HEAD") -> None:
        self._git = ["git", "-C", str(repo_root)]
        self.ref = ref
        listing = subprocess.run(
            [*self._git, "ls-tree", "-r", "-z", "--name-only", ref], capture_output=True, text=True, check=True
        )
        self.files: frozenset[str] = frozenset(path for path in listing.stdout.split("\0") if path)
        self._texts_by_name: dict[str, dict[str, str]] = {}

    def read(self, path: str) -> str | None:
        if path not in self.files:
            return None
        name = path.rsplit(SEP, 1)[-1]
        if name not in self._texts_by_name:
            self._texts_by_name[name] = self._cat([p for p in self.files if p.rsplit(SEP, 1)[-1] == name])
        return self._texts_by_name[name][path]

    def _cat(self, paths: list[str]) -> dict[str, str]:
        """One ``git cat-file --batch`` per file name. The resolver asks for an ownership file per
        directory, and a ``git show`` for each takes seconds on this repo."""
        batch = subprocess.run(
            [*self._git, "cat-file", "--batch"],
            input="".join(f"{self.ref}:{path}\n" for path in paths).encode(),
            capture_output=True,
            check=True,
        ).stdout
        texts: dict[str, str] = {}
        position = 0
        for path in paths:
            header_end = batch.index(b"\n", position)
            size = int(batch[position:header_end].rsplit(b" ", 1)[-1])
            position = header_end + 1
            texts[path] = batch[position : position + size].decode()
            position += size + 1
        return texts


def first_new_path(path: str, path_kind: Callable[[str], PathKind | None]) -> str | None:
    """The part of ``path`` nearest the root that the tree does not hold, or None when the tree
    holds ``path``. An ancestor counts as new unless the tree holds it as a directory, so a change
    that replaces the file or symlink ``products/new`` with a directory adds ``products/new``. The
    walk checks the ancestors before the path, because a filesystem check of the full path follows
    a symlinked ancestor and would find a file that the tree does not hold."""
    if not path:
        return None
    parts = path.split(SEP)
    for depth in range(1, len(parts)):
        prefix = SEP.join(parts[:depth])
        if path_kind(prefix) != "dir":
            return prefix
    return None if path_kind(path) is not None else path


# Names a sourceless resolver's files, so a Resolution still reports the path that decided ownership.
VIRTUAL_ROOT = Path("/")


class OwnersResolver:
    """Resolves ownership by reading ``owners.yaml`` and alias files through an ``OwnershipSource``.

    Reads a worktree by default, locating the repo root via ``git rev-parse`` (override with
    ``repo_root`` for testing). Pass ``source`` to resolve without one. Parsed files are cached per
    directory.

    ``purpose`` and ``producer`` decide which channel a resolution reports; ``team_channel``
    documents how they select one.
    """

    def __init__(
        self,
        repo_root: Path | None = None,
        purpose: Purpose = DEFAULT_PURPOSE,
        source: OwnershipSource | None = None,
        producer: Producer | None = None,
    ) -> None:
        self.repo_root = (repo_root or (VIRTUAL_ROOT if source is not None else _git_repo_root())).resolve()
        self.source = source if source is not None else DiskSource(self.repo_root)
        self.purpose = purpose
        self.producer = producer
        self._dir_cache: dict[str, OwnersFile | None] = {}
        # The worktree is treated as immutable for the resolver's lifetime.
        self._tracked_cache: dict[str | None, list[str]] = {}
        self._parsed_ownership: list[ParsedOwnershipFile] | None = None
        self._teams_cache: dict[str, TeamEntry] | None = None
        # Files in one directory share every ancestor, so a full-tree run asks about each
        # directory thousands of times.
        self._path_kind_cache: dict[str, PathKind | None] = {}

    def alias_files(self) -> tuple[str, ...]:
        """The alias file names the root file declares, in the order that decides a tie."""
        return self.settings().alias_files

    def ownership_filenames(self) -> tuple[str, ...]:
        """Every file name that counts as an ownership file, ``owners.yaml`` first."""
        return (OWNERS_FILENAME, *self.alias_files())

    def _load_dir_file(self, directory: str) -> OwnersFile | None:
        """Ownership file for a repo-relative directory ("" = root), or None."""
        if directory in self._dir_cache:
            return self._dir_cache[directory]

        prefix = f"{directory}/" if directory else ""
        result: OwnersFile | None = None

        owners_rel = f"{prefix}{OWNERS_FILENAME}"
        owners_text = self.source.read(owners_rel)
        if owners_text is not None:
            parsed, _errors = parse_owners_file(owners_text, path=self.repo_root / owners_rel, directory=directory)
            result = parsed

        # An alias only applies when there is no owners.yaml (a directory with both is a lint
        # error; resolve prefers owners.yaml). The root directory is skipped because the alias
        # names come from the root owners.yaml, which is the file an alias there would replace.
        if result is None and directory:
            for name in self.alias_files():
                alias_rel = f"{prefix}{name}"
                alias_text = self.source.read(alias_rel)
                if alias_text is None:
                    continue
                result = parse_alias_file_as_owners(alias_text, path=self.repo_root / alias_rel, directory=directory)
                if result is not None:
                    break

        self._dir_cache[directory] = result
        return result

    def _ancestor_dirs(self, path: str) -> list[str]:
        """Repo-relative dirs from root ("") down to the path's parent, outermost first."""
        dirs = [""]
        parts = path.split("/")[:-1]  # drop the filename
        acc: list[str] = []
        for part in parts:
            acc.append(part)
            dirs.append("/".join(acc))
        return dirs

    def _collect_files(self, path: str) -> list[OwnersFile]:
        """Ownership files on the walk to ``path``, outermost first. ``inherit``
        cuts are NOT applied here: a matched rule may override the file-level
        flag either way, so the cut must happen per contribution in ``resolve``,
        after rule overrides are folded in."""
        collected: list[OwnersFile] = []
        for directory in self._ancestor_dirs(path):
            f = self._load_dir_file(directory)
            if f is not None:
                collected.append(f)
        return collected

    def _file_contribution(self, f: OwnersFile, path: str) -> OwnersFile:
        """A shallow copy of the file's fields with every matching rule applied in order.
        Each rule replaces only the fields it sets, so a later rule that sets only ``status``
        keeps the ``owners`` an earlier rule set. Returns the file itself if no rule matches."""
        rel = path[len(f.directory) + 1 :] if f.directory else path
        matched = [rule for rule in f.rules if compile_pattern(rule.match).test(rel)]
        if not matched:
            return f

        contrib = OwnersFile(
            path=f.path,
            directory=f.directory,
            owners=f.owners,
            status=f.status,
            inherit=f.inherit,
            is_alias=f.is_alias,
            additions=_union(f.additions, *(rule.additions for rule in matched)),
            sensitive=f.sensitive,
        )
        for rule in matched:
            if not isinstance(rule.owners, _Unset):
                contrib.owners = rule.owners
            if not isinstance(rule.status, _Unset):
                contrib.status = rule.status
            if not isinstance(rule.inherit, _Unset):
                contrib.inherit = rule.inherit
            if not isinstance(rule.sensitive, _Unset):
                contrib.sensitive = rule.sensitive
        return contrib

    def ownership_file_paths(self, paths: list[str]) -> list[str]:
        """Every ownership file that could decide any of ``paths``. A source that fetches over the
        network reads this first, so it can fetch the batch's files together."""
        directories = {d for path in paths for d in self._ancestor_dirs(normalize_path(path))}
        filenames = self.ownership_filenames()
        # No alias applies in the root directory (see _load_dir_file), so none is listed there.
        return sorted(
            {OWNERS_FILENAME} | {f"{directory}/{name}" for directory in directories if directory for name in filenames}
        )

    def _merge(self, norm: str) -> _Merged:
        merged = _Merged()

        for f in self._collect_files(norm):
            contrib = self._file_contribution(f, norm)

            # The single `set noparent` site: contrib.inherit is the file-level
            # flag with any matched rule's override folded in, so a file-level
            # `inherit: false` cuts here, and a rule-level `inherit: true` can
            # restore ancestors for its paths.
            if not contrib.inherit:
                merged = _Merged()

            # Owners: an explicit list (non-empty) or explicit null overrides; an
            # empty list is "no contribution here" and falls through.
            if contrib.owners is None:
                merged.owners = None
                merged.source = self._rel(contrib.path)
            elif contrib.owners:
                merged.owners = list(contrib.owners)
                merged.source = self._rel(contrib.path)

            if not isinstance(contrib.status, _Unset):
                merged.status = contrib.status

            if not isinstance(contrib.sensitive, _Unset):
                merged.sensitive = contrib.sensitive

            if contrib.additions:
                merged.additions = _union(merged.additions, contrib.additions)

        return merged

    def _path_kind(self, path: str) -> PathKind | None:
        if path not in self._path_kind_cache:
            self._path_kind_cache[path] = cast(TreeSource, self.source).path_kind(path)
        return self._path_kind_cache[path]

    def _added(self, path: str) -> Addition | None:
        if not isinstance(self.source, TreeSource):
            return None
        new_path = first_new_path(path, self._path_kind)
        if new_path is None:
            return None
        return Addition(path=new_path, additions=self._merge(new_path).additions)

    def resolve(self, path: str) -> Resolution:
        norm = normalize_path(path)
        return self._build_resolution(norm, self._merge(norm), self._added(norm))

    def _teams_registry(self) -> dict[str, TeamEntry]:
        """The root file's ``teams:`` Slack registry (team slug -> its declared channels),
        loaded once. Empty when there is no root file or it declares none."""
        if self._teams_cache is None:
            root = self._load_dir_file("")
            self._teams_cache = dict(root.teams) if root is not None else {}
        return self._teams_cache

    def settings(self) -> RepoSettings:
        """Repo-wide settings from the root ``owners.yaml``. Defaults when there is no root file,
        so a repo without one still reads the default alias files."""
        root = self._load_dir_file("")
        return root.settings if root is not None else RepoSettings()

    def producer_error(self) -> str | None:
        """Why this resolver's ``producer`` cannot be honored, or None when it can.

        A name the root file does not declare would fall through to the people channel, which is
        the one place automation must not post, so an entrypoint reports this instead of resolving.
        A repo that declares no ``producers`` accepts any name.
        """
        if self.producer is None:
            return None
        if not self.producer:
            return "producer name must not be empty"
        declared = self.settings().producers
        if declared is None or self.producer in declared:
            return None
        return f"unknown producer '{self.producer}' (declared in 'producers': {', '.join(sorted(declared))})"

    def _effective_slack(self, owners: list[str] | None) -> str | None:
        """The Slack channel for a path: the registry entry for the primary owner
        (team slugs only), then the derived ``#<slug>``, else None. Only a team slug
        (not an ``@handle``) carries a channel."""
        if owners and not owners[0].startswith("@"):
            return team_channel(owners[0], self._teams_registry(), self.purpose, self.producer).channel
        return None

    def _build_resolution(self, path: str, merged: _Merged, added: Addition | None) -> Resolution:
        unowned_by_design = merged.owners is None
        owners: list[str] | None = None if isinstance(merged.owners, _Unset) else merged.owners

        status = "active" if isinstance(merged.status, _Unset) else merged.status

        slack = self._effective_slack(owners)

        return Resolution(
            path=path,
            owners=owners,
            status=status,
            slack=slack,
            source=merged.source,
            unowned_by_design=unowned_by_design,
            additions=merged.additions,
            added=added,
            sensitive=merged.sensitive is True,
        )

    def _rel(self, path: Path) -> str:
        return path.relative_to(self.repo_root).as_posix()

    def map(self, paths: list[str]) -> dict[str, Resolution]:
        if isinstance(self.source, BatchOwnershipSource):
            # Two fetches, because the root file names the alias files the batch needs. A source
            # whose read() only serves what read_all fetched has nothing to answer with otherwise.
            self.source.read_all([OWNERS_FILENAME])
            self.source.read_all(self.ownership_file_paths(paths))
        return {p: self.resolve(p) for p in paths}

    def unowned(self, paths: list[str]) -> list[str]:
        """The subset of ``paths`` that resolve to unowned (and not exempt)."""
        return [p for p in paths if self.resolve(p).is_unowned]

    def tracked_files(self, prefix: str | None = None) -> list[str]:
        """Repo-relative paths from ``git ls-files``, optionally under ``prefix``.

        A root that is not a git worktree, such as an unpacked export, falls back to every file on
        disk. Cached per prefix, because the tree is treated as immutable per run.
        """
        if prefix in self._tracked_cache:
            return self._tracked_cache[prefix]
        args = ["git", "-C", str(self.repo_root), "ls-files", "-z"]
        if prefix:
            args.append(prefix)
        try:
            result = subprocess.run(args, capture_output=True, text=True, check=True)
            paths = [p for p in result.stdout.split("\0") if p]
        except (OSError, subprocess.CalledProcessError):
            paths = _walk_files(self.repo_root, prefix)
        self._tracked_cache[prefix] = paths
        return paths

    def parsed_ownership_files(self) -> list[ParsedOwnershipFile]:
        """Every tracked ownership file, parsed exactly once (cached). This is the
        single parse pass consumers (lint, fmt) should thread through instead of
        re-reading and re-parsing the same YAML per concern."""
        if self._parsed_ownership is not None:
            return self._parsed_ownership
        entries: list[ParsedOwnershipFile] = []
        filenames = self.ownership_filenames()
        for rel in self.tracked_files():
            name = rel.rsplit("/", 1)[-1]
            if name not in filenames:
                continue
            rel_dir = rel.rsplit("/", 1)[0] if "/" in rel else ""
            # No alias applies in the root directory (see _load_dir_file), so listing one would
            # hand consumers a file resolution never reads.
            if not rel_dir and name != OWNERS_FILENAME:
                continue
            abs_path = self.repo_root / rel
            errors: list[str] = []
            warnings: list[str] = []
            if name != OWNERS_FILENAME:
                parsed = parse_alias_file_as_owners(abs_path.read_text(), path=abs_path, directory=rel_dir)
            else:
                parsed, errors = parse_owners_file(
                    abs_path.read_text(), path=abs_path, directory=rel_dir, warnings=warnings
                )
            entries.append(
                ParsedOwnershipFile(
                    path=abs_path, rel_dir=rel_dir, name=name, parsed=parsed, errors=errors, warnings=warnings
                )
            )
        self._parsed_ownership = entries
        return entries

    def effective_ownership_files(self) -> list[ParsedOwnershipFile]:
        """The one file per directory that ``resolve`` reads there, ordered by directory.

        ``parsed_ownership_files`` lists every tracked ownership file, including the ones a
        directory's ``owners.yaml`` or an earlier alias shadows. A consumer that models resolution
        must see the same precedence, or it models a file the resolver never reads. Lint is the
        exception: reporting the shadowed file is its job.
        """
        rank = {name: index for index, name in enumerate(self.ownership_filenames())}
        chosen: dict[str, ParsedOwnershipFile] = {}
        for entry in self.parsed_ownership_files():
            if entry.parsed is None:
                continue
            current = chosen.get(entry.rel_dir)
            if current is None or rank[entry.name] < rank[current.name]:
                chosen[entry.rel_dir] = entry
        return [chosen[directory] for directory in sorted(chosen)]