Cotton code
106 lines · 3.6 KB · PythonRaw
#!/usr/bin/env python3"""Persistent review evidence and the shared refusal used by reclaimers."""import argparseimport osfrom pathlib import Pathimport shutilimport subprocessMARKER = '.cotton-evidence'def evidence_reason(path):    path = Path(path).absolute()    try:        # Both spellings matter: an alias into evidence is protected too.        for candidate in {path, path.resolve()}:            for parent in (candidate, *candidate.parents):                try:                    (parent / MARKER).lstat()                except (FileNotFoundError, NotADirectoryError):                    continue                return f'EVIDENCE marker at {parent / MARKER}'        if path.is_dir() and not path.is_symlink():            def failed(error):                raise error            for folder, dirs, files in os.walk(path, followlinks=False, onerror=failed):                if MARKER in files or MARKER in dirs:                    return f'EVIDENCE marker at {Path(folder) / MARKER}'    except OSError as error:        return f'EVIDENCE inspection failed ({type(error).__name__}); retained'    return Nonedef keep_evidence(path, *, file=None):    reason = evidence_reason(path)    if reason:        print(f'kept {path} — {reason}', file=file, flush=True)    return bool(reason)BACKUPS_FOLDER = 'CottonDB-backups'def holds_backups(path):    """RULE (architect, 21 Oct 2026): a backup copy never sits where a cleanup rule can reach it. The serving app's    daily copies live in a CottonDB-backups folder on a backup disk — the same disk the lanes live on — so no lane    cleanup removes that folder, anything in it, or anything holding it."""    path = Path(path)    if BACKUPS_FOLDER in path.parts:        return True    try:        if BACKUPS_FOLDER in path.resolve().parts:            return True    except OSError:        return True    return os.path.lexists(path / BACKUPS_FOLDER)def remove_regenerable(path):    path = Path(path)    home = Path.home().resolve()    resolved = path.resolve()    if resolved == home or resolved in home.parents or resolved == Path('/'):        raise ValueError('refusing to remove home or its ancestors')    if holds_backups(path):        raise ValueError(f'refusing to remove {path} — a backup disk\'s copies')    if keep_evidence(path):        return    if path.is_symlink() or path.is_file():        path.unlink()    elif path.is_dir():        shutil.rmtree(path)def begin(path):    path = Path(path).expanduser().absolute()    if '.cache' in path.parts or '.cache' in path.resolve().parts:        raise ValueError('evidence belongs in ~/cotton-captures, never in a cache')    ancestor = path    while not ancestor.exists():        ancestor = ancestor.parent    if subprocess.run(['git', '-C', str(ancestor), 'rev-parse', '--show-toplevel'],                      stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:        raise ValueError('evidence belongs in Cotton, never in a repository')    path.mkdir(parents=True, exist_ok=True)    (path / MARKER).touch(exist_ok=True)    return path.resolve()def main():    parser = argparse.ArgumentParser(description=__doc__)    parser.add_argument('mode', choices=('keep', 'remove', 'begin'))    parser.add_argument('paths', nargs='+', type=Path)    args = parser.parse_args()    if args.mode == 'keep':        return 0 if any(keep_evidence(path) for path in args.paths) else 1    for path in args.paths:        if args.mode == 'begin':            print(begin(path))        else:            remove_regenerable(path)    return 0if __name__ == '__main__':    raise SystemExit(main())