Files changed: - CHANGES.md - VERSION - docs/how-to/ingest-a-source.md - docs/reference/commands/README.md - docs/reference/commands/raw-material-and-uploads.md - instructions/wiki-ingest/SKILL.md - raw/CONTRACT.md - tools/CONTRACT.md - tools/chemenu/cli_contract.py - tools/chemenu/commands/raw/__init__.py - tools/chemenu/commands/raw/_common.py - tools/chemenu/commands/raw/clarify.py - tools/chemenu/commands/raw/pending.py - tools/chemenu/tests/test_raw_clarify.py - types/source.guidance.md Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015uxGFdBAmyA23g1isCtGEY
228 lines
9.6 KiB
Python
228 lines
9.6 KiB
Python
"""`wikitool raw pending` - `incoming/` read as a queue (Gitea #112): what
|
|
`wiki-ingest` without an argument works through, one candidate per run, oldest
|
|
first so that newer material builds on - or corrects - what the wiki already took
|
|
from older.
|
|
|
|
`raw pending` reads the same queue without changing it: the candidates in
|
|
`incoming/` oldest first, each judged by the very checks `raw accept` runs
|
|
before it moves anything (`_Refused` is how those checks report without
|
|
exiting).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import json
|
|
import os
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
import typer
|
|
|
|
from chemenu import cli_contract, repo_capture
|
|
from chemenu.commands._util import rel_path
|
|
from chemenu.commands.raw._common import (
|
|
LONG_TEXT_CHARS,
|
|
_Refused,
|
|
_check_files,
|
|
_derive_hint,
|
|
_incoming_dir,
|
|
_source_stem,
|
|
_plan_captured_folder,
|
|
_plan_file_moves,
|
|
_plan_folder,
|
|
_plain_text_length,
|
|
)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class _Candidate:
|
|
kind: str # file | bundle | folder
|
|
paths: tuple[Path, ...]
|
|
files: int
|
|
mtime_ns: int
|
|
reason: Optional[str] # None when `raw accept` would take it as it stands
|
|
hint: Optional[str] = None # the `raw derive` line for a lone file a filter reads
|
|
length: Optional[int] = None # characters of a lone text file over the length threshold
|
|
|
|
def label(self) -> str:
|
|
return ", ".join(rel_path(p) + ("/" if self.kind == "folder" else "") for p in self.paths)
|
|
|
|
def mtime_iso(self) -> str:
|
|
stamp = datetime.datetime.fromtimestamp(self.mtime_ns / 1e9).astimezone()
|
|
return stamp.isoformat(timespec="seconds")
|
|
|
|
|
|
def _refusal(fn, *args) -> Optional[str]:
|
|
try:
|
|
fn(*args)
|
|
except _Refused as exc:
|
|
return str(exc)
|
|
return None
|
|
|
|
|
|
def _folder_contents(folder: Path) -> tuple[int, int]:
|
|
"""How many non-directory entries sit below `folder`, and the newest
|
|
mtime among them - `lstat` only, no content read and no link followed."""
|
|
count, newest = 0, 0
|
|
for dirpath, dirnames, filenames in os.walk(folder, followlinks=False):
|
|
base = Path(dirpath)
|
|
for name in filenames + [d for d in dirnames if (base / d).is_symlink()]:
|
|
count += 1
|
|
newest = max(newest, (base / name).lstat().st_mtime_ns)
|
|
return count, newest
|
|
|
|
|
|
def _plain_files(paths: list[Path]) -> None:
|
|
_check_files(paths)
|
|
_plan_file_moves(paths, [], None)
|
|
|
|
|
|
def _pending_candidates() -> list[_Candidate]:
|
|
"""The candidates in `incoming/`, oldest first (Gitea #112 E1/E5).
|
|
|
|
Only top-level entries count; dotfiles and empty directories are none.
|
|
Top-level files sharing a stem are one `bundle` - a `raw fetch` pair, or a file with its
|
|
`<stem>.clarifications.md` (Gitea #241). A top-level folder is one `folder`, with every
|
|
file below it. A unit is as new as its newest part, so a bundle or folder
|
|
sorts by the newest mtime it holds; a tie goes by the path's bytes."""
|
|
incoming = _incoming_dir()
|
|
if not incoming.is_dir():
|
|
return []
|
|
candidates: list[_Candidate] = []
|
|
by_stem: dict[str, list[Path]] = {}
|
|
for entry in incoming.iterdir():
|
|
if entry.name.startswith("."):
|
|
continue
|
|
if entry.is_dir():
|
|
if entry.is_symlink():
|
|
count, newest = 1, entry.lstat().st_mtime_ns
|
|
else:
|
|
count, newest = _folder_contents(entry)
|
|
if count:
|
|
captured = (entry / repo_capture.MANIFEST_NAME).is_file() and not entry.is_symlink()
|
|
check = _plan_captured_folder if captured else _plan_folder
|
|
candidates.append(_Candidate(
|
|
"folder", (entry,), count, newest, _refusal(check, entry)
|
|
))
|
|
else:
|
|
by_stem.setdefault(_source_stem(entry), []).append(entry)
|
|
for paths in by_stem.values():
|
|
paths.sort(key=lambda p: os.fsencode(p.name))
|
|
candidates.append(_Candidate(
|
|
"file" if len(paths) == 1 else "bundle",
|
|
tuple(paths),
|
|
len(paths),
|
|
max(p.lstat().st_mtime_ns for p in paths),
|
|
_refusal(_plain_files, paths),
|
|
_derive_hint(paths[0]) if len(paths) == 1 else None,
|
|
_plain_text_length(paths[0]) if len(paths) == 1 else None,
|
|
))
|
|
candidates.sort(key=lambda c: (c.mtime_ns, os.fsencode(c.paths[0].name)))
|
|
return candidates
|
|
|
|
|
|
@cli_contract.record(cli_contract.CommandRecord(
|
|
path="raw pending",
|
|
summary="List what waits in `incoming/`, oldest first, and name the entry an ingest without "
|
|
"an argument takes next.",
|
|
synopsis=(cli_contract.Variant(usage="raw pending [--json]"),),
|
|
properties=cli_contract.Properties(
|
|
effect=cli_contract.Effect.READ,
|
|
idempotent=cli_contract.Idempotent.YES,
|
|
atomic="Read-only",
|
|
budget=cli_contract.Budget.COUNTED,
|
|
),
|
|
notes=(
|
|
"A candidate is a top-level entry of `incoming/`: a single `file`, a `bundle` of "
|
|
"top-level files sharing a stem (a `raw fetch` pair), or "
|
|
"a `folder` with every file below it. Dotfiles, empty directories and their contents "
|
|
"are none; `quarantine/` is outside `incoming/` and never listed.",
|
|
"Order: oldest first by modification time. A bundle or folder counts as new as its "
|
|
"newest file; a tie goes by name. The mtime is when a document last changed only if "
|
|
"it was copied with its timestamps kept (`cp -p`, `rsync -a`, an unpacked archive) - "
|
|
"for a download or a `raw fetch` it is merely when it was dropped.",
|
|
"Each candidate shows its path(s), kind, file count and mtime, and whether `raw "
|
|
"accept` would take it as it stands - the same checks, minus `--fidelity`/"
|
|
"`--authority`. One it would refuse is listed with the reason and skipped: it needs a "
|
|
"human.",
|
|
"The default is the first candidate `raw accept` would take, and the output names it.",
|
|
"`--json` prints the same candidates in the same order: `kind`, `paths`, `files`, "
|
|
"`mtime`, `acceptable`, `reason`, `default`, `hint`, `length`.",
|
|
"A lone file that a `raw derive` filter reads (a PDF, mail, Office file or web page) is "
|
|
"listed with the `raw derive` line for it, in text output and as `hint` in JSON "
|
|
"(`null` for every other candidate). The hint changes nothing about the order or the "
|
|
"default.",
|
|
"A lone `.md` or `.txt` file longer than the length threshold of `raw derive` and `raw "
|
|
"fetch` is listed with its length in characters, in text output and as `length` in "
|
|
"JSON (`null` for every other candidate) - that text reaches a session with no "
|
|
"derivation in front of it to print the length `CHECK`. Like the hint, it changes "
|
|
"nothing about the order or the default.",
|
|
"Reads directory listings and `lstat`, and a file's content only to measure a lone "
|
|
"`.md`/`.txt` whose size in bytes is over the threshold - a UTF-8 text has no more "
|
|
"characters than bytes; an empty `incoming/` is exit 0 with nothing to do.",
|
|
),
|
|
failures=(),
|
|
examples=(
|
|
"tools/wikitool raw pending",
|
|
"tools/wikitool raw pending --json",
|
|
),
|
|
see_also=(
|
|
"`wikitool raw accept` - promotes the chosen candidate",
|
|
"`instructions/wiki-ingest/SKILL.md` - ingest without an argument starts here",
|
|
"`raw/CONTRACT.md` \"Getting a file in: incoming/\" - candidates and order, and why",
|
|
),
|
|
))
|
|
def raw_pending_command(
|
|
json_out: bool = typer.Option(False, "--json", help="Print the candidates as JSON"),
|
|
):
|
|
"""List the candidates waiting in incoming/, oldest first, and name the
|
|
default. See raw/CONTRACT.md "Getting a file in: incoming/"."""
|
|
candidates = _pending_candidates()
|
|
default = next((c for c in candidates if c.reason is None), None)
|
|
|
|
if json_out:
|
|
typer.echo(json.dumps([
|
|
{
|
|
"kind": c.kind,
|
|
"paths": [rel_path(p) for p in c.paths],
|
|
"files": c.files,
|
|
"mtime": c.mtime_iso(),
|
|
"acceptable": c.reason is None,
|
|
"reason": c.reason,
|
|
"default": c is default,
|
|
"hint": c.hint,
|
|
"length": c.length,
|
|
}
|
|
for c in candidates
|
|
], indent=2, ensure_ascii=False))
|
|
return
|
|
|
|
if not candidates:
|
|
typer.echo("Nothing is waiting in incoming/.")
|
|
return
|
|
typer.echo(f"{len(candidates)} candidate(s) in incoming/, oldest first:")
|
|
for number, c in enumerate(candidates, 1):
|
|
marker = "*" if c is default else " "
|
|
typer.echo(f"{marker} {number}. {c.kind:<6} {c.label()} ({c.files} file(s), {c.mtime_iso()})")
|
|
if c.reason is not None:
|
|
first, *rest = c.reason.splitlines()
|
|
typer.echo(f" not acceptable: {first}")
|
|
for line in rest:
|
|
typer.echo(f" {line}")
|
|
if c.hint is not None:
|
|
typer.echo(f" text: {c.hint} (derives readable text, keeps the original)")
|
|
if c.length is not None:
|
|
typer.echo(
|
|
f" long: {c.length:,} characters, over the {LONG_TEXT_CHARS:,} one ingest "
|
|
"reads in one pass - read it in parts (instructions/ingest-large-tree.md)"
|
|
)
|
|
if default is None:
|
|
typer.echo("No candidate can be accepted as it stands - each needs a human (reasons above).")
|
|
return
|
|
waiting = len(candidates) - 1
|
|
typer.echo(
|
|
f"Default (*): {default.label()} - the oldest candidate raw accept would take; "
|
|
f"{waiting} more waiting after it."
|
|
)
|