diff --git a/AGENTS.md b/AGENTS.md index d8b130f..863bf11 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ language, same archive, same conventions where we can match them. | path | what | |---|---| -| `src/patchtrack/lore.py` | the only network code: public-inbox search export (`?x=m`) and thread `t.mbox.gz` | +| `src/patchtrack/lore.py` | the only network code: public-inbox search export (`?x=m`) and thread `t.mbox.gz`; `get_text` for one plain file (Next/Trees) | | `src/patchtrack/parse.py` | mail to facts: subject prefixes, trailers, "applied" evidence, b4 change-ids | | `src/patchtrack/thread.py` | `read`: reply order, depth, quote collapsing, patch and cover parts | | `src/patchtrack/tui.py` | the curses browser: `Model` (keys, views; no curses) and a thin `draw`/`run` | @@ -20,6 +20,7 @@ language, same archive, same conventions where we can match them. | `src/patchtrack/news.py` | what changed since you last looked: snapshots and their differences | | `src/patchtrack/local.py` | your own mail: Maildir, `.eml` directories, mbox; header-first filtering | | `src/patchtrack/trees.py` | git: fetch a tree, find posted patches in it (message-id trailer, patch-id, subject) | +| `src/patchtrack/maintainers.py` | `tree discover`: MAINTAINERS sections (`F:`/`X:`/`N:` as get_maintainer.pl), `T:` trees, branches from linux-next's `Next/Trees` | | `src/patchtrack/store.py` | SQLite of raw facts: messages, fetch times, trees and per-patch tree results | | `src/patchtrack/series.py` | messages to series, families and states | | `src/patchtrack/cli.py` | `patchtrack sync`, `list`, `show`, `people`, `board`, `tree`, `check` | @@ -28,6 +29,7 @@ language, same archive, same conventions where we can match them. | `docs/` | the Sphinx site: `conf.py` (generates the command pages), hand-written pages, `requirements.txt` | | `src/patchtrack/config.py` | the TOML config file; bot rules | | `tests/test_patchtrack.py` | unittest, synthetic mail only, no network | +| `tests/test_maintainers.py` | section matching, routes and branches, `tree discover` and `--add` against a throwaway repo | | `tests/test_trees.py` | matchers against a throwaway git repo; stage derivation | | `tests/test_sync.py` | what `sync` refetches and how it fails, against an in-memory fake archive | | `tests/test_thread.py` | quote collapsing, sign-offs, patch and cover parts, reply order | @@ -260,6 +262,37 @@ to follow" on a cover used to mark the whole series applied; such announcements are now partial (1 of 319 surveyed announcements matches, the one it was written for). +## Tree discovery (2026-11-11) + +Why: a maintainer applied a four-patch series without a reply, and with +no trees configured nothing showed it. The project's own files say where +patches go, so `tree discover` reads them rather than guessing: +MAINTAINERS `T:` lines, and linux-next's `Next/Trees` for the branch a +`T:` line omits. Run against one contributor's 18 open series, it +named a tree with a branch for 15; 1 had no section with a `T:` (hwrng's +section has none; that is MAINTAINERS' answer), 1 was a U-Boot series, +and 1 (mt76, `T: git https://github.com/nbd168/wireless`) has no branch +anywhere. That tree has `mt76`, `mt76-pending` and `pending`, and +"pending" means *not yet applied*, so the branch is never guessed: +`--add` lists the branches and asks in a terminal (Enter skips), and +prints a `tree add` command otherwise. Adding Felix's `mt76` +branch made the series `queued`, all four patches by message-id. + +- **Projects are told apart by lists, not people.** Matching on any + M:/R:/L: address put a U-Boot series through the kernel's file: one of + its reviewers also maintains something in the kernel. +- **`X:` follows get_maintainer.pl**, so an excluded vendor directory + (wireless excludes `mediatek/`) does not route to the parent tree, + even though its patches reach that tree through a pull. Following + pulls upward is not in MAINTAINERS. +- Mainline (`torvalds/linux`) is never proposed as a maintainer tree. +- **Defaults, so a kernel checkout needs no options**: MAINTAINERS from + `--maintainers`, else the mainline tree, else the current directory's + repository; Next/Trees from `--next-trees`, else the next tree's copy, + else linux-next's own (one request, and only when the MAINTAINERS is + the kernel's: it names `torvalds/linux`). `trees.remote_heads` is the + `ls-remote`; tests mock it and `lore.get_text`, so they stay offline. + ## Known gaps and next steps Done: sync that cannot silently miss mail, your own mailbox as a source, @@ -283,12 +316,15 @@ TUI. What is left, roughly in order of value: 4. **Other archives**: git's "What's cooking" is not parsed (use its branches as trees). Mailman and PostgreSQL archives are not public-inbox. DPDK's search is behind a bot check. -5. **Board**: per list works (`-l`); `--all-versions` does not exist yet. +5. **Patchwork** (`Q:` in MAINTAINERS) keeps an "Accepted" state for + some lists (linux-wireless, netdev); its REST API could be a third + applied signal, beside the mail and the trees. Not read yet. +6. **Board**: per list works (`-l`); `--all-versions` does not exist yet. The docs have a systemd timer for `sync && check --fetch; board` (`docs/scheduling.rst`). -6. **Old rows** stored before a migration lack its columns until they are +7. **Old rows** stored before a migration lack its columns until they are fetched again (`sync --full`, `check`). -7. **Releasing**: `.github/workflows/release.yml` publishes to PyPI when +8. **Releasing**: `.github/workflows/release.yml` publishes to PyPI when a GitHub release is published, through Trusted Publishing (no token). It refuses a tag that does not match `__version__`, runs the tests, and checks the build with `twine check --strict`. Publishing a release diff --git a/CHANGELOG.md b/CHANGELOG.md index 096b9d1..e43f2b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## Unreleased + +- **`tree discover`** finds the maintainer trees for your open series: + the MAINTAINERS sections covering their files (as get_maintainer.pl + reads them), their `T:` trees, and the branch from linux-next's + `Next/Trees` where `T:` names none. In a kernel checkout, + `tree discover --add` needs no options: MAINTAINERS comes from the + mainline tree or the current directory, Next/Trees from linux-next. For + a tree whose branch neither file names, it lists the branches and asks + which one (in a terminal), or prints the `tree add` command to finish. + ## 0.1.0 The first version. diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 824568f..9ab5919 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -33,6 +33,25 @@ check, in ``~/.config/patchtrack/config.toml``: :doc:`configuration` lists every key. +Which maintainer trees to check +------------------------------- + +A maintainer often applies a patch without replying. The tree check sees +it anyway, but only in a tree you named. For the kernel, let +``tree discover`` name them, from MAINTAINERS and linux-next's +``Next/Trees``. In your kernel checkout: + +.. code-block:: sh + + patchtrack tree discover # what it would add, series by series + patchtrack tree discover --add # add them + patchtrack check --fetch # fetch them and look for your patches + +Some trees name no branch anywhere, and only the maintainer knows which +one means "applied". ``--add`` lists their branches and asks; outside a +terminal it prints the :doc:`commands/tree` ``add`` command to finish by +hand. + The daily round --------------- diff --git a/src/patchtrack/cli.py b/src/patchtrack/cli.py index 8e46752..f387003 100644 --- a/src/patchtrack/cli.py +++ b/src/patchtrack/cli.py @@ -15,7 +15,7 @@ import urllib.parse import webbrowser -from . import __version__, b4local, board, config, local, lore, news, nudge, parse, pretty, series, store, thread, trees, vdiff +from . import __version__, b4local, board, config, local, lore, maintainers, news, nudge, parse, pretty, series, store, thread, trees, vdiff def cmd_sync(args, db): @@ -630,7 +630,28 @@ def cmd_tree(args, db): Trees can also be declared as ``[[trees]]`` in the config, which is then their source of truth (``tree rm`` refuses them). + + ``tree discover`` finds the trees for you. Run in a kernel checkout, + ``patchtrack tree discover --add`` is all it takes. For each open + series it reads the files the patches touch, finds the MAINTAINERS + sections that cover them (as ``get_maintainer.pl`` does) and lists + their ``T:`` trees. Where a ``T:`` line names no branch, linux-next's + ``Next/Trees`` supplies the one that feeds linux-next. A tree in + neither has no known branch, because which branch means "applied" is + the maintainer's choice: its branches are listed, and ``--add`` asks + which one when it runs in a terminal. ``--add`` adds the trees as + ``maintainer`` trees fetched into ``--repo`` (default: the repository + MAINTAINERS came from); then ``check --fetch`` looks in them. + + MAINTAINERS is read from ``--maintainers REPO[:REF]``, else the + ``mainline`` tree, else the repository in the current directory. + Next/Trees is read from ``--next-trees`` (a file or a URL; ``none`` + for none), else the ``next`` tree's copy, else, for the kernel's + MAINTAINERS, linux-next's own on git.kernel.org (one request). + Mainline itself is left out: add it with ``--role mainline``. """ + if args.action == "discover": + return _tree_discover(args, db) if args.action == "list": for t in db.trees(): src = f"{t.url} {t.branch}" if t.url else "local" @@ -651,6 +672,181 @@ def cmd_tree(args, db): return 0 +def _git_file(repo, ref, path): + return trees.git(repo, "show", f"{ref}:{path}") + + +def _maintainers_source(args, known): + """(repo, ref) to read MAINTAINERS from: --maintainers, else the mainline + tree, else the repository in the current directory.""" + if args.maintainers: + repo, _, ref = args.maintainers.partition(":") + return os.path.abspath(os.path.expanduser(repo)), ref or "HEAD" + main = next((t for t in known if t.role == "mainline"), None) + if main: + return main.repo, main.ref + try: + top = trees.git(os.getcwd(), "rev-parse", "--show-toplevel").strip() + except trees.GitError: + sys.exit("no MAINTAINERS: run this in a kernel checkout, pass --maintainers REPO[:REF], " + "or add a mainline tree") + return top, "HEAD" + + +def _next_trees(args, known, kernel): + """(text, where from) of linux-next's Next/Trees: --next-trees (a file, a + URL or "none"), else the next tree's copy, else linux-next's own, for the + kernel's MAINTAINERS only.""" + src = args.next_trees + if src == "none": + return "", None + if src and not re.match(r"^https?://", src): + with open(os.path.expanduser(src), encoding="utf-8", errors="replace") as f: + return f.read(), src + if not src: + nt = next((t for t in known if t.role == "next"), None) + if nt: + try: + return _git_file(nt.repo, nt.ref, "Next/Trees"), f"{nt.name}:Next/Trees" + except trees.GitError: + pass + if not kernel: + return "", None + src = maintainers.NEXT_TREES_URL + try: + return lore.get_text(src), src + except lore.LoreError as e: + print(f"Next/Trees: {e}", file=sys.stderr) + return "", None + + +def _choose_branch(name, url, heads): + """Ask which branch of a tree means "applied"; None to skip it.""" + print(f"\n{name} ({url}) names no branch. Which one does the maintainer apply to?") + for i, h in enumerate(heads, 1): + print(f" {i}) {h}") + while True: + try: + ans = input("number or name, Enter to skip: ").strip() + except EOFError: + return None + if not ans: + return None + if ans.isdigit() and 1 <= int(ans) <= len(heads): + return heads[int(ans) - 1] + if ans in heads: + return ans + print(" not one of the branches above") + + +def _tree_discover(args, db): + known = db.trees() + repo, ref = _maintainers_source(args, known) + try: + text = _git_file(repo, ref, "MAINTAINERS") + except trees.GitError as e: + sys.exit(f"MAINTAINERS: {e}") + sections, routed_to = maintainers.parse(text), maintainers.addresses(text) + next_text, next_from = _next_trees(args, known, maintainers.is_kernel(text)) + next_trees = maintainers.parse_next_trees(next_text) + if next_from and not next_trees: + print(f"Next/Trees: nothing read from {next_from}", file=sys.stderr) + print(f"MAINTAINERS from {repo} {ref}; Next/Trees from {next_from or 'nowhere'}\n", file=sys.stderr) + + by_key = {(maintainers.normalize_url(t.url), t.branch): t for t in known if t.url} + checked_urls = {} + for (u, _), t in by_key.items(): + checked_urls.setdefault(u, []).append(t.name) + msgs = {m["msgid"]: m for m in db.messages()} + found = _load(args, db) + heads, to_add, open_ends, elsewhere = {}, {}, {}, [] + for fam in series.families(found, db.closed()): + if fam.closed is not None or (not args.all and fam.state in series.DONE): + continue + s = fam.head + if not routed_to & {a.lower() for a in s.to}: + elsewhere.append(s) + continue + paths = sorted({f for i, mid in s.patches.items() if i and mid in msgs + for pair in trees.DIFF_RE.findall(msgs[mid]["body"]) for f in pair + if f != "/dev/null"}) + print(f"{s.label()} [{fam.state}]") + rs = maintainers.routes(sections, paths, next_trees) + if not rs: + print(" no tree: no MAINTAINERS section covering its files names one\n") + continue + last = None + for r in rs: + if r.section != last: + print(f" {r.section}") + last = r.section + have = by_key.get(r.key) + if r.branch: + tag = f"checked as {have.name}" if have else f"new: {maintainers.tree_name(r)}" + print(f" {r.url} {r.branch} (from {r.source}; {tag})") + if not have: + to_add.setdefault(r.key, r) + continue + nurl = maintainers.normalize_url(r.url) + mine = checked_urls.get(nurl) + print(f" {r.url} (no branch: its T: line names none, and it is not in Next/Trees" + + (f"; checked as {', '.join(mine)})" if mine else ")")) + if mine: + continue + if args.ls_remote and r.url not in heads: + heads[r.url] = trees.remote_heads(r.url) + if heads.get(r.url) is not None: + print(f" branches: {' '.join(heads[r.url])}") + open_ends.setdefault(nurl, r) + print() + if elsewhere: + print(f"Not sent to any list in this MAINTAINERS (another project's series): {len(elsewhere)}") + for s in elsewhere: + print(f" {s.label()}") + print() + + into = os.path.abspath(os.path.expanduser(args.repo)) if args.repo else repo + if not args.add: + if to_add: + print("Trees with a known branch that are not checked yet (`tree discover --add` adds them):") + for r in to_add.values(): + print(f" {maintainers.tree_name(r)} {r.url} {r.branch}") + if open_ends: + print("Trees whose branch only the maintainer knows (`--add` asks; or add one by hand):") + for r in open_ends.values(): + print(f" patchtrack tree add {maintainers.tree_name(r)} --repo {shlex.quote(into)} " + f"--url {r.url} --branch BRANCH") + return 0 + + if open_ends and sys.stdin.isatty(): + for nurl, r in open_ends.items(): + hs = heads.get(r.url) + if not hs: + continue + b = _choose_branch(maintainers.tree_name(r), r.url, hs) + if b: + picked = maintainers.Route(r.section, r.url, b, "you") + to_add.setdefault(picked.key, picked) + print() + elif open_ends: + print("Not added, their branch is the maintainer's choice (run in a terminal to be asked):") + for r in open_ends.values(): + print(f" patchtrack tree add {maintainers.tree_name(r)} --repo {shlex.quote(into)} " + f"--url {r.url} --branch BRANCH") + names = {t.name for t in known} + for r in to_add.values(): + name = maintainers.tree_name(r) + while name in names: + name += "_" + names.add(name) + db.add_tree(trees.Tree(name, into, f"refs/patchtrack/{name}", r.url, r.branch, "maintainer")) + print(f"added {name}: {r.url} {r.branch} into {into}") + db.commit() + if to_add: + print("\nNext: `patchtrack check --fetch` fetches them and looks for your patches.") + return 0 + + def cmd_check(args, db): """Look for every posted patch in the trees. @@ -937,7 +1133,7 @@ def command(name, func, helptext): sp.set_defaults(func=cmd_config) sp = command("tree", cmd_tree, "the git trees `check` looks in") - sp.add_argument("action", choices=("add", "list", "rm")) + sp.add_argument("action", choices=("add", "list", "rm", "discover")) sp.add_argument("name", nargs="?") sp.add_argument("--repo", help="local repository (fetches go into it)") sp.add_argument("--ref", help="a ref already in the repository") @@ -945,6 +1141,18 @@ def command(name, func, helptext): sp.add_argument("--branch", help="the branch to fetch from --url") sp.add_argument("--role", choices=trees.ROLES, default="maintainer", help="maintainer: queued; next: in-next; mainline: merged") + sp.add_argument("--maintainers", metavar="REPO[:REF]", + help="discover: read MAINTAINERS here (default: the mainline tree, else the " + "current directory's repository)") + sp.add_argument("--next-trees", metavar="FILE|URL|none", + help="discover: linux-next's Next/Trees (default: the next tree's copy, else " + "linux-next's own on git.kernel.org)") + sp.add_argument("--no-ls-remote", dest="ls_remote", action="store_false", + help="discover: do not list the branches of trees whose branch is unknown") + sp.add_argument("--add", action="store_true", help="discover: add the trees whose branch is known") + sp.add_argument("--all", action="store_true", help="discover: applied and merged series too") + sp.add_argument("-a", "--author", action="append", help="discover: default: every author synced") + sp.add_argument("-l", "--list", help="discover: only series found by a sync of this inbox") sp.set_defaults(func=cmd_tree) sp = command("check", cmd_check, "look for every posted patch in the trees") @@ -995,7 +1203,7 @@ def command(name, func, helptext): def main(argv=None): p = build_parser() args = p.parse_args(argv) - if args.cmd == "tree" and args.action != "list" and not args.name: + if args.cmd == "tree" and args.action in ("add", "rm") and not args.name: p.error("tree add/rm need a NAME") if args.cmd == "tree" and args.action == "add" and not args.repo: p.error("tree add needs --repo") diff --git a/src/patchtrack/lore.py b/src/patchtrack/lore.py index 0b7d6a3..e8cfddd 100644 --- a/src/patchtrack/lore.py +++ b/src/patchtrack/lore.py @@ -1,7 +1,9 @@ """Read-only access to a public-inbox archive such as lore.kernel.org. -Only two endpoints are used: the search export (``?x=m``, the same request -``lei q -I`` makes) and a thread's ``t.mbox.gz``. Requests identify the tool +Only two archive endpoints are used: the search export (``?x=m``, the +same request ``lei q -I`` makes) and a thread's ``t.mbox.gz``; besides +them, ``get_text`` reads one plain file (linux-next's Next/Trees) when +asked to. Requests identify the tool honestly and are spaced out; nothing here ever sends mail. """ @@ -89,6 +91,12 @@ def thread(self, msgid): return parse_mbox(self._get(f"{self.base}/all/{mid}/t.mbox.gz")) +def get_text(url, opener=urllib.request.urlopen): + """A plain-text file over HTTP(S), such as linux-next's Next/Trees, with + the same honest User-Agent and retries as the archive requests.""" + return Lore(opener=opener, delay=0)._get(url).decode("utf-8", "replace") + + def windowed(search, query, since, until, days=30, split_at=SPLIT_AT, progress=None): """Every message for query between two epoch times, searched window by window. diff --git a/src/patchtrack/maintainers.py b/src/patchtrack/maintainers.py new file mode 100644 index 0000000..d4f8a01 --- /dev/null +++ b/src/patchtrack/maintainers.py @@ -0,0 +1,179 @@ +"""Which maintainer trees a posted patch goes to, from the project's own files. + +Two files say it, both read from git, never guessed: + +- **MAINTAINERS** (the kernel's, and U-Boot's, which has the same format). + A section's ``F:``, ``N:`` and ``X:`` lines say which files it covers, + as ``scripts/get_maintainer.pl`` reads them, and its ``T:`` lines name + its trees: ``T: git URL [BRANCH]``. Many omit the branch. +- **linux-next's Next/Trees**: every tree merged into linux-next, as + ``NAME URL#BRANCH``. It gives the branch a ``T:`` line leaves out, for the + trees that feed linux-next. + +A tree in neither with a branch stays without one: the branch it is +applied on is the maintainer's choice (Felix Fietkau's mt76 tree has +``mt76``, ``mt76-pending`` and ``pending``; "pending" means *not yet +applied*). ``tree discover`` lists the branches to choose from, and asks +which one when it runs in a terminal with ``--add``. +""" + +import re +from dataclasses import dataclass, field + +# linux-next's list of the trees it merges, read when no other copy is given +NEXT_TREES_URL = "https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/plain/Next/Trees" + +# Mainline is a role of its own (`merged`), not a maintainer's queue. +MAINLINE_URLS = {"git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux", + "github.com/torvalds/linux"} + + +@dataclass +class Section: + name: str + files: list = field(default_factory=list) # F: + excludes: list = field(default_factory=list) # X: + regexes: list = field(default_factory=list) # N: + trees: list = field(default_factory=list) # (url, branch or None) from T: git + + +@dataclass +class Route: + section: str + url: str + branch: str | None + source: str # "T:" or "Next/Trees" + next_name: str | None = None + + @property + def key(self): + return (normalize_url(self.url), self.branch) + + +ADDR_RE = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+") + + +def addresses(text): + """Every list on an L: line. A series sent to none of them went to + another project: people can be in two projects' files (a U-Boot + custodian who maintains something in the kernel), lists are not.""" + return {a.lower() for line in text.splitlines() if re.match(r"^L:", line) + for a in ADDR_RE.findall(line)} + + +def parse(text): + """Sections of a MAINTAINERS file, in order; the preamble is skipped.""" + sections, cur = [], None + for line in text.splitlines(): + m = re.match(r"^([A-Z]):\s*(.*?)\s*$", line) + if not line.strip(): + cur = None + continue + if m is None: + # a title line starts a section (the preamble has no tag lines) + cur = Section(line.strip()) + sections.append(cur) + continue + if cur is None: + continue + tag, value = m.groups() + if tag == "F": + cur.files.append(value) + elif tag == "X": + cur.excludes.append(value) + elif tag == "N": + try: + cur.regexes.append(re.compile(value, re.X)) + except re.error: + pass + elif tag == "T": + parts = value.split() + if len(parts) >= 2 and parts[0] == "git": + rest = [p for p in parts[2:] if p != "-b"] + cur.trees.append((parts[1], rest[0] if rest else None)) + return [s for s in sections if s.files or s.regexes] + + +def _pattern(pat): + """get_maintainer.pl's F:/X: matching: a prefix match, with * and ? as + wildcards that may cross '/'; a pattern ending in '/' covers the whole + directory below it.""" + rx = re.escape(pat).replace(r"\*", ".*").replace(r"\?", ".") + return re.compile("^" + rx) + + +def _file_match(pat, path): + if not _pattern(pat).match(path): + return False + # Without a trailing '/' or a wildcard, a pattern names a file or a + # directory: "drivers/foo" must not cover "drivers/foobar.c". + if pat.endswith("/") or "*" in pat or "?" in pat: + return True + return path == pat or path.startswith(pat + "/") + + +def covers(section, path): + if any(_file_match(x, path) for x in section.excludes): + return False + return any(_file_match(f, path) for f in section.files) or any(r.search(path) for r in section.regexes) + + +def normalize_url(url): + """The same tree under its different spellings: scheme, .git, trailing /.""" + u = re.sub(r"^[a-z+]+://", "", url.strip().lower()) + u = re.sub(r"^[^@/]+@", "", u) + return re.sub(r"(\.git)?/*$", "", u) + + +def parse_next_trees(text): + """{normalized url: [(name, url, branch)]} from linux-next's Next/Trees.""" + out = {} + for line in text.splitlines(): + parts = line.split() + if len(parts) < 2 or "#" not in parts[-1] or "://" not in parts[-1]: + continue + url, branch = parts[-1].split("#", 1) + out.setdefault(normalize_url(url), []).append((parts[0], url, branch)) + return out + + +def routes(sections, paths, next_trees=None): + """Every tree the sections covering paths name, with a branch where one is + known. Mainline is left out.""" + next_trees = next_trees or {} + found, seen = [], set() + for s in sections: + if not s.trees or not any(covers(s, p) for p in paths): + continue + for url, branch in s.trees: + nurl = normalize_url(url) + if nurl in MAINLINE_URLS: + continue + if branch: + known = next((n for n, _, b in next_trees.get(nurl, ()) if b == branch), None) + cands = [Route(s.name, url, branch, "T:", known)] + elif nurl in next_trees: + cands = [Route(s.name, url, b, "Next/Trees", name) for name, _, b in next_trees[nurl]] + else: + cands = [Route(s.name, url, None, "T:")] + for r in cands: + if r.key not in seen: + seen.add(r.key) + found.append(r) + return found + + +def is_kernel(text): + """Whether a MAINTAINERS file is the Linux kernel's (so linux-next's + Next/Trees applies to it).""" + return "torvalds/linux" in text + + +def tree_name(route): + """A name for `tree add`: Next/Trees' own, else the URL's last two parts + and the branch.""" + if route.next_name: + return route.next_name + parts = [p for p in normalize_url(route.url).split("/") if p][-2:] + name = "-".join(parts + ([route.branch] if route.branch else [])) + return re.sub(r"[^A-Za-z0-9._-]+", "-", name) diff --git a/src/patchtrack/trees.py b/src/patchtrack/trees.py index 18caf5f..0c610a7 100644 --- a/src/patchtrack/trees.py +++ b/src/patchtrack/trees.py @@ -62,6 +62,21 @@ def fetch(tree): git(tree.repo, "fetch", "--quiet", "--no-tags", tree.url, f"+{tree.branch}:{tree.ref}") +def remote_heads(url, timeout=120): + """The branch names at url (`git ls-remote --heads`), or None if it + cannot be read. GitHub's dependency-bot branches are left out: they + are never anyone's queue.""" + try: + p = subprocess.run(["git", "ls-remote", "--heads", url], capture_output=True, text=True, + timeout=timeout, stdin=subprocess.DEVNULL) + except subprocess.TimeoutExpired: + return None + if p.returncode: + return None + heads = (line.split("refs/heads/", 1)[1] for line in p.stdout.splitlines() if "refs/heads/" in line) + return sorted(h for h in heads if not h.startswith("dependabot/")) + + def is_shallow(repo): return git(repo, "rev-parse", "--is-shallow-repository").strip() == "true" diff --git a/tests/test_lore.py b/tests/test_lore.py index bfa56bd..4f832a0 100644 --- a/tests/test_lore.py +++ b/tests/test_lore.py @@ -28,6 +28,23 @@ def http_error(code, retry_after=None): return urllib.error.HTTPError("u", code, "x", headers, io.BytesIO()) +class GetText(unittest.TestCase): + def test_plain_file(self): + seen = [] + + def opener(req, timeout): + seen.append(req.get_header("User-agent")) + return Response(b"net\thttps://example.org/net.git#main\n", "text/plain; charset=UTF-8") + self.assertEqual(lore.get_text("https://example.org/Trees", opener=opener), + "net\thttps://example.org/net.git#main\n") + self.assertEqual(seen, [lore.USER_AGENT]) + + def test_bot_check_page_is_an_error(self): + with self.assertRaises(lore.LoreError): + lore.get_text("https://example.org/Trees", + opener=lambda req, timeout: Response(b"", "text/html")) + + class Retries(unittest.TestCase): def client(self, outcomes): self.sleeps = [] diff --git a/tests/test_maintainers.py b/tests/test_maintainers.py new file mode 100644 index 0000000..91c648d --- /dev/null +++ b/tests/test_maintainers.py @@ -0,0 +1,263 @@ +import io +import os +import subprocess +import tempfile +import unittest +from unittest import mock + +from patchtrack import cli, maintainers, store +from test_patchtrack import ME, mail +from test_trees import ENV + +MAINTAINERS = """\ +List of maintainers +=================== + +Descriptions of section entries and preferred order +--------------------------------------------------- + +\tM: *Mail* patches to: FullName
+\tT: *SCM* tree type and location. + +FOO NET DRIVERS +M:\tNet Maint