From 0959ae9fbd24361fe776ac1bb406fd2dff3134f2 Mon Sep 17 00:00:00 2001 From: adamXbot <111877622+adamXbot@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:47:54 +1100 Subject: [PATCH 1/2] Keep the original chrome/ and the person's own files through every path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seven ways install, upgrade, adopt and uninstall could lose or overwrite something that was not fxcss's to touch. The four checked against 0.25.0 (the original backup, the hook, pins and OS litter) happen there too, so these are not regressions. - A second `fxcss install` recorded the previous theme's backup as the original, so three upgrades later the real original was pruned and `uninstall` restored a theme. The origin is now carried from the install being replaced, followed back to the real original when an older manifest names a theme's backup, and repaired after a rollback renames it. Only backups holding an fxcss manifest are ever pruned. - The customChrome.css placeholder was recorded as a theme file. Once filled in it blocked upgrades, and --force wrote a fresh placeholder over it. A filled-in hook is now the person's file and is carried. - A bare `upgrade` on a --ref pin re-downloaded and reinstalled the same ref and spent a backup doing it. It now says it is pinned and stops. - .DS_Store, Thumbs.db and desktop.ini in chrome/ stopped `uninstall` restoring the original. - After `adopt`, files the matched version does not ship were recorded as the theme's and dropped by the next upgrade. They are recorded as the person's own. - A stray BEGIN marker in user.js claimed a later block's END and took the lines between with it. - The pref names shown before confirming stopped at five, missed `user_pref ("x", …)` written with a space, and passed control characters to the terminal. Co-Authored-By: Claude Fable 5.2 --- fxcss/checklist.py | 30 +- fxcss/cli.py | 9 + fxcss/install.py | 217 ++++++++++++-- tests/test_data_safety.py | 612 ++++++++++++++++++++++++++++++++++++++ tests/test_units.py | 10 +- 5 files changed, 842 insertions(+), 36 deletions(-) create mode 100644 tests/test_data_safety.py diff --git a/fxcss/checklist.py b/fxcss/checklist.py index ee33148..5a6ea86 100644 --- a/fxcss/checklist.py +++ b/fxcss/checklist.py @@ -26,7 +26,7 @@ import re from pathlib import Path -from .install import PREF_NAME_RE, _strip_js_comments +from .install import PREF_NAME_RE, _printable, _strip_js_comments from .style import plural as _pl MAX_README_BYTES = 512 * 1024 @@ -104,11 +104,15 @@ def _read(path, limit): def pref_names_in(path): - """Pref names a JavaScript preference file sets, in order, deduplicated.""" + """Pref names a JavaScript preference file sets, in order, deduplicated. + + The names come from a theme and are shown in a terminal, so anything + unprintable in one is escaped rather than replayed. + """ code = _strip_js_comments(_read(path, MAX_PREF_FILE_BYTES)) names = [] for match in PREF_NAME_RE.finditer(code): - name = match.group(2) + name = _printable(match.group(2)) if name not in names: names.append(name) return names @@ -200,13 +204,16 @@ def build(repo_root, theme_root=None, plan=None, applied_pref_files=()): state = "required" elif any(OPTIONAL_WORD_RE.search(s) for s in hits): state = "optional" - preview = ", ".join(entry["names"][:5]) + (" …" if entry["count"] > 5 else "") + # What fxcss is about to write into user.js is named in full: five + # names and an ellipsis would let the sixth change a profile unseen. + shown = entry["names"] if state == "applied" else entry["names"][:5] + preview = ", ".join(shown) + (" …" if len(shown) < entry["count"] else "") items.append({ - "item": f"preferences in {entry['path']} ({_pl(entry['count'], 'pref')}: {preview})", + "item": f"preferences in {_printable(entry['path'])} ({_pl(entry['count'], 'pref')}: {preview})", "state": state, "evidence": entry["path"], "note": ("fxcss writes these into its own block of user.js" if state == "applied" else - f"not applied; `--prefs {entry['path']}` adds them to the managed block"), + f"not applied; `--prefs {_printable(entry['path'])}` adds them to the managed block"), "pref_file": entry["path"], "names": entry["names"], }) @@ -318,7 +325,7 @@ def render(items, indent=" "): head = f"{' ' * pad}{style.status(word, role, width=width)}" text_indent = pad + width names = item.get("names") if item.get("pref_file") else None - text = (f"{_pl(len(names), 'pref')} in {item['pref_file']}" if names + text = (f"{_pl(len(names), 'pref')} in {_printable(item['pref_file'])}" if names else item["item"]) note = item.get("note") if names and item["state"] == "applied": @@ -329,9 +336,12 @@ def render(items, indent=" "): lines.append(head + wrapped[0].lstrip()) lines.extend(wrapped[1:]) if names: - shown = f" {style.DOT} ".join(names[:5]) - if len(names) > 5: - shown += f" {style.DOT} {style.ELLIPSIS} and {len(names) - 5} more" + # Every pref fxcss will write is named; files it only reports + # are summarised. + listed = names if item["state"] == "applied" else names[:5] + shown = f" {style.DOT} ".join(listed) + if len(names) > len(listed): + shown += f" {style.DOT} {style.ELLIPSIS} and {len(names) - len(listed)} more" lines.extend(style.muted(line) for line in style.wrap(shown, indent=text_indent)) if note: lines.extend(style.muted(line) for line in style.wrap(note, indent=text_indent)) diff --git a/fxcss/cli.py b/fxcss/cli.py index 879fa26..6bcc03a 100644 --- a/fxcss/cli.py +++ b/fxcss/cli.py @@ -1897,6 +1897,15 @@ def cmd_upgrade(args): print("\n Already up to date. Pass --ref to move somewhere else " "anyway.") return 0 + if (state["state"] == "pinned" and remote and not args.ref + and not args.commit and not setup_requested): + # A pin is a decision not to move. Fetching the same ref again would + # reinstall what is already there and spend a backup doing it, and + # for a branch name it would quietly move the install after all. + print(f"\n Pinned to {source.get('ref')} with --ref, so it stays " + "where it is.\n `fxcss upgrade --ref ` " + "moves it; `--commit`\n follows the default branch instead.") + return 0 workdir = Path(tempfile.mkdtemp(prefix="fxcss-upgrade-")) keep_pin = (source.get("ref_kind") == "explicit" and not args.ref and not args.commit diff --git a/fxcss/install.py b/fxcss/install.py index 29c46a6..f3a187d 100644 --- a/fxcss/install.py +++ b/fxcss/install.py @@ -62,6 +62,20 @@ MAX_SHEET_DEPENDENCIES = 256 MAX_SHEET_DEPENDENCY_BYTES = 32 * 1024 * 1024 +# What fxcss writes at chrome/customChrome.css when a theme @imports that +# file without shipping it. The file is the person's hook for their own +# rules: once it holds anything else it is theirs, however it got there. +PLACEHOLDER_TEXT = "/* placeholder created by fxcss */\n" +# Text mode wrote \r\n on Windows, so both forms are the placeholder. +PLACEHOLDER_DIGESTS = frozenset( + hashlib.sha256(text.encode("utf-8")).hexdigest() + for text in (PLACEHOLDER_TEXT, PLACEHOLDER_TEXT.replace("\n", "\r\n"))) + +# Files an operating system drops into any folder it shows. Nobody wrote +# them, so they are neither a person's addition nor a reason to hold back +# the chrome/ an uninstall would otherwise restore. +OS_LITTER = frozenset({".ds_store", "thumbs.db", "desktop.ini", "ehthumbs.db"}) + class CollisionError(RuntimeError): """An upgrade would put an upstream file where the user added their own. @@ -358,7 +372,10 @@ def strip_user_js_block(text): A BEGIN marker without its END is left completely alone: deleting to the end of the file could take a line the user wrote, and a duplicated pref is - harmless where a lost one is not. + harmless where a lost one is not. An END belongs to the nearest BEGIN + above it -- fxcss never writes a marker inside its own block -- so a + stray BEGIN higher up cannot claim a later block's END and take the + lines between them with it. """ out = [] lines = _lines(text) @@ -366,6 +383,11 @@ def strip_user_js_block(text): while i < len(lines): if lines[i].strip() == BLOCK_BEGIN: for j in range(i + 1, len(lines)): + if lines[j].strip() == BLOCK_BEGIN: + # This BEGIN never closed; the next one starts afresh. + out.append(lines[i]) + i += 1 + break if lines[j].strip() == BLOCK_END: # Older Windows installs wrote the separator and markers # with CRLF. Match the marker's ending so a new LF block @@ -456,8 +478,10 @@ def safe_theme_path(theme_root, relative): return candidate +# Whitespace (a newline included) may sit between the function name and its +# parenthesis; Firefox reads `user_pref ("x", 1);` as readily as the usual form. PREF_NAME_RE = re.compile( - r"""\b(?:user_pref|pref|sticky_pref|lockPref)\(\s*(["'])(.+?)\1""") + r"""\b(?:user_pref|pref|sticky_pref|lockPref)\s*\(\s*(["'])(.+?)\1""") def theme_pref_names(theme_root): @@ -709,6 +733,13 @@ def drift(profile, manifest=None): chrome/ the manifest does not list -- which is how a hand-added sheet shows up, and why `uninstall` never deletes by wildcard. + The customChrome.css placeholder fxcss writes for a theme that imports + one without shipping it is the person's hook, not the theme's file. Once + it holds anything but the placeholder it is reported under `extra`, like + any other file they added, so an upgrade carries it across instead of + refusing over it or writing a fresh placeholder on top. Operating-system + litter (.DS_Store and the like) is nobody's and is not reported at all. + A schema-1 manifest carries no digests, so nothing can be said about modification; `checked` is 0 in that case and `modified` is empty. That is a real "don't know", and callers must not render it as "unchanged". @@ -725,10 +756,14 @@ def drift(profile, manifest=None): for path in _manifest_paths(profile, manifest): relative = path.relative_to(profile).as_posix() recorded.add(relative) + expected = digests.get(relative) + if isinstance(expected, str) and expected in PLACEHOLDER_DIGESTS: + if path.is_file() and _digest(path) not in PLACEHOLDER_DIGESTS: + result["extra"].append(relative) + continue if not path.is_file(): result["missing"].append(relative) continue - expected = digests.get(relative) if not isinstance(expected, str): continue result["checked"] += 1 @@ -741,7 +776,8 @@ def drift(profile, manifest=None): if not path.is_file(): continue relative = path.relative_to(profile).as_posix() - if relative not in recorded and path.name != MANIFEST_NAME: + if relative not in recorded and path.name != MANIFEST_NAME \ + and path.name.lower() not in OS_LITTER: result["extra"].append(relative) for key in ("modified", "missing", "extra"): result[key].sort() @@ -782,6 +818,8 @@ def preservation_plan(profile, additions, staged_chrome): paths the new version now ships with exactly the user's bytes (upstream adopted the file -- nothing to carry); `collisions` are paths where the new version ships different bytes, which no rule can settle silently. + A staged file that is only fxcss's own customChrome.css placeholder is + not the theme shipping anything, so the person's file is carried over it. Nothing is copied here; this is the reviewable part. """ profile, staged_chrome = Path(profile), Path(staged_chrome) @@ -792,6 +830,8 @@ def preservation_plan(profile, additions, staged_chrome): if staged.is_file(): if staged.read_bytes() == profile.joinpath(*Path(relative).parts).read_bytes(): plan["identical"].append(relative) + elif _digest(staged) in PLACEHOLDER_DIGESTS: + plan["carry"].append(relative) else: plan["collisions"].append(relative) elif staged.exists() or staged.is_symlink() or any( @@ -848,6 +888,11 @@ def adopt_theme(profile, theme_id, source, match, stamp=None): is evidently already set -- the theme is working -- and writing an fxcss block to say so again would edit a file for no gain. The next upgrade writes one properly, from the theme it fetches. + + Files the matched version does not contain (`match["extra"]`) are not + recorded as the theme's. Whoever put them there, upstream did not, so + they are treated as the person's own: listed under `user_files`, carried + across upgrades, and never removed by uninstall. """ from . import __version__ @@ -861,9 +906,12 @@ def adopt_theme(profile, theme_id, source, match, stamp=None): backup = _spare_name(profile, f"chrome.backup-{stamp or _timestamp()}") shutil.copytree(chrome, backup) - files = sorted(p.relative_to(profile).as_posix() - for p in chrome.rglob("*") - if p.is_file() and ".git" not in p.relative_to(chrome).parts) + present = sorted(p.relative_to(profile).as_posix() + for p in chrome.rglob("*") + if p.is_file() and ".git" not in p.relative_to(chrome).parts) + extra = {"chrome/" + entry for entry in (match.get("extra") or []) + if isinstance(entry, str)} + files = [name for name in present if name not in extra] manifest = { "schema": MANIFEST_SCHEMA, "fxcss": __version__, @@ -881,6 +929,8 @@ def adopt_theme(profile, theme_id, source, match, stamp=None): "digests": {name: digest for name, digest in ((name, _digest(profile / name)) for name in files) if digest}, + "user_files": [name for name in present if name in extra + and Path(name).name.lower() not in OS_LITTER], } (chrome / MANIFEST_NAME).write_text( json.dumps(manifest, indent=1) + "\n", encoding="utf-8") @@ -915,8 +965,7 @@ def _prepare_chrome(theme_root, chrome, sheets, notes=None, repo_root=None): entry = chrome / "userChrome.css" if not placeholder.exists() and entry.is_file() and "customChrome.css" in \ entry.read_text(encoding="utf-8", errors="replace"): - placeholder.write_text("/* placeholder created by fxcss */\n", - encoding="utf-8") + placeholder.write_text(PLACEHOLDER_TEXT, encoding="utf-8") if sheets and not entry.exists(): # A userContent.css-only theme has nothing to layer optional sheets # onto; an empty entry gives the wrapper below something to import. @@ -998,8 +1047,12 @@ def install_theme(theme_root, profile, theme_id, sheets=(), stamp=None, failure before that point leaves the original prefs unchanged. `origin_backup` is carried through upgrades, including None for a profile - that originally had no chrome/. `source` records how to fetch the theme - again; older callers can still supply that information in `theme_id`. + that originally had no chrome/. Left unset, it is taken from the manifest + of the managed chrome/ being replaced, so installing over an fxcss + install never mistakes that theme's backup for the original; only a + chrome/ fxcss does not manage becomes a new origin. `source` records how + to fetch the theme again; older callers can still supply that information + in `theme_id`. When the active chrome/ is one fxcss manages, files the person added to it are carried into the new tree so they stay active (`user_files` in @@ -1060,10 +1113,14 @@ def install_theme(theme_root, profile, theme_id, sheets=(), stamp=None, if not created: shutil.copy2(user_js, staged_prefs) write_prefs(staged_prefs, user_js_with_block(existing, block)) - # Whether fxcss created user.js is part of the original state, - # not something an upgrade should reset just because it exists. - if origin_backup is not _UNSET and previous: + # Whether fxcss created user.js, and which backup holds the + # chrome/ from before fxcss ran here, describe the original + # state. Replacing one managed install with another -- an + # upgrade, or `fxcss install` run a second time -- resets neither. + if previous: created = previous.get("user_js_created", created) + if origin_backup is _UNSET: + origin_backup = previous.get("origin_backup") manifest = { "schema": MANIFEST_SCHEMA, "fxcss": __version__, @@ -1131,8 +1188,36 @@ def read_manifest(profile): so each field is only accepted when it has the right type. A manifest someone has mangled degrades to "fxcss cannot say", never to a confident wrong answer. + + `origin_backup` is followed to the real original. Releases up to 0.25 + recorded the *previous theme's* backup as the origin when `fxcss install` + ran over an existing install, which let the true original be pruned and + made uninstall "restore" a theme. A backup with a manifest inside is + never an original, and its own manifest says what came before it. """ - return _read_manifest(Path(profile) / "chrome" / MANIFEST_NAME) + data = _read_manifest(Path(profile) / "chrome" / MANIFEST_NAME) + if data: + data["origin_backup"] = _original_backup(profile, data.get("origin_backup")) + return data + + +def _original_backup(profile, recorded): + """`recorded`, or the origin its own manifest names when it holds a theme. + + Only direct ``chrome.backup-*`` children are ever opened, and a name seen + twice ends the walk, so a mangled manifest cannot lead it anywhere. + """ + profile = Path(profile) + seen = set() + while True: + name = safe_backup_name(recorded) + if not name or name in seen: + return recorded + seen.add(name) + inner = _read_manifest(profile / name / MANIFEST_NAME) + if inner is None: + return recorded + recorded = inner.get("origin_backup") def _read_manifest(path): @@ -1355,10 +1440,64 @@ def rollback_to(profile, backup, stamp=None): summary["user_js"] = "unknown" if (profile / "chrome").exists() or (profile / "chrome").is_symlink(): summary["moved_aside"] = moved.name - _swap_profile(profile, target, moved, prefs, work) + origin = _origin_after_rollback(profile, name, restored, outgoing, + summary["moved_aside"]) + recorded = target / MANIFEST_NAME + before = recorded.read_bytes() if origin else None + if origin: + _replace_bytes(recorded, _with_origin(before, origin)) + try: + _swap_profile(profile, target, moved, prefs, work) + except BaseException: + # Nothing moved, so the backup's manifest goes back as it was too. + if before is not None and recorded.is_file(): + with contextlib.suppress(OSError): + _replace_bytes(recorded, before) + raise return summary +def _origin_after_rollback(profile, target, restored, outgoing, moved_aside): + """The origin a restored theme should record, or None to leave it alone. + + The manifest in a backup names the original as it was called when that + theme was active. A rollback to the original renames it (it becomes + chrome/, and is moved aside under a new name when a theme comes back), so + the recorded name can point at nothing while the original sits beside it. + When that has happened, the original is whichever of these still exists: + the person's own chrome/ this rollback is moving aside, or the origin the + outgoing install knows about. + """ + if restored is None: + return None + known = safe_backup_name(_original_backup(profile, restored.get("origin_backup"))) + if known and (profile / known).is_dir(): + return None + if outgoing is None: + return moved_aside + theirs = safe_backup_name(outgoing.get("origin_backup")) + if theirs and theirs != target and (profile / theirs).is_dir(): + return theirs + return None + + +def _with_origin(manifest_bytes, name): + data = json.loads(manifest_bytes.decode("utf-8")) + data["origin_backup"] = name + return (json.dumps(data, indent=1) + "\n").encode("utf-8") + + +def _replace_bytes(path, data): + """Write `data` to `path` through a sibling file, so it is never half there.""" + staged = path.with_name(path.name + ".fxcss-tmp") + try: + staged.write_bytes(data) + staged.replace(path) + finally: + with contextlib.suppress(OSError): + staged.unlink() + + def prune_backups(profile, keep, protect=()): """Delete all but the newest `keep` backups. Returns the names removed. @@ -1367,12 +1506,18 @@ def prune_backups(profile, keep, protect=()): `keep` -- that is how the origin backup survives any number of upgrades without using up the allowance the caller asked for. `keep=None` prunes nothing at all. + + Only a backup with an fxcss manifest inside is ever pruned. One without + is a chrome/ fxcss did not write: the original, a hand-made copy that + happens to share the name, or the person's own chrome/ that a rollback + moved aside. Those are not counted and not deleted, whatever the manifest + of the day says the origin is. """ if keep is None: return [] protected = {name for name in protect if name} candidates = [b for b in list_backups(profile) - if b["name"] not in protected] + if b["name"] not in protected and b["manifest"] is not None] removed = [] for backup in candidates[max(keep, 0):]: shutil.rmtree(backup["path"], ignore_errors=True) @@ -1394,12 +1539,33 @@ def _prune_empty_dirs(chrome): pass +def _restorable(path, staged, origin): + """Would restoring `origin` lose nothing this leftover holds?""" + if path.is_symlink(): + return False + if path.name.lower() in OS_LITTER: + return True + if origin is None: + return False + twin = origin / path.relative_to(staged) + try: + return (twin.is_file() and not twin.is_symlink() + and twin.read_bytes() == path.read_bytes()) + except OSError: + return False + + def uninstall_theme(profile, stamp=None): """Prepare removal without touching active files, then swap atomically. Only unchanged, digest-verified files are removed. Added, edited and unverifiable files remain, and block restoration of the origin backup. A failed swap restores both directories and leaves preferences unchanged. + + Two kinds of leftover do not count as the person's work, provided nothing + else is left: operating-system litter (.DS_Store and the like), and a + file byte-identical to the one at the same path in the origin backup -- + restoring that backup puts the very same file back. """ profile = Path(profile) chrome = profile / "chrome" @@ -1439,17 +1605,22 @@ def uninstall_theme(profile, stamp=None): path.unlink() summary["removed"] += 1 (staged / MANIFEST_NAME).unlink() + recorded = safe_backup_name(manifest.get("origin_backup")) + origin = profile / recorded if recorded else None + if origin is not None and (not origin.is_dir() or origin.is_symlink()): + origin = None + leftovers = [p for p in staged.rglob("*") if p.is_file() or p.is_symlink()] + if all(_restorable(p, staged, origin) for p in leftovers): + for path in leftovers: + path.unlink() _prune_empty_dirs(staged) replacement = staged if staged.exists() else None if replacement: summary["kept"] = sorted( p.relative_to(work).as_posix() for p in staged.rglob("*") if p.is_file() or p.is_symlink()) - recorded = safe_backup_name(manifest.get("origin_backup")) - if replacement is None and recorded: - backup = profile / recorded - if backup.is_dir() and not backup.is_symlink(): - replacement = backup - summary["restored"] = recorded + if replacement is None and origin is not None: + replacement = origin + summary["restored"] = recorded _swap_profile(profile, replacement, outgoing, prefs, work) return summary diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py new file mode 100644 index 0000000..7ebbbb7 --- /dev/null +++ b/tests/test_data_safety.py @@ -0,0 +1,612 @@ +"""What belongs to the person stays theirs through every maintenance path. + +Each class is one way a real profile used to lose something: the chrome/ +from before fxcss was pruned after a second install or a pair of rollbacks; +the customChrome.css hook was treated as the theme's file; a pinned install +was re-fetched on every upgrade; a .DS_Store blocked uninstall from restoring +the original; files beside an adopted theme were dropped by the next +upgrade; a stray marker in user.js cost the lines under it; and prefs a theme +sets could be written without being named first. +""" + +import contextlib +import hashlib +import io +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from fxcss import adopt, checklist, cli, fetch, install + + +ORIGINAL = b"/* my own chrome, from before fxcss */\r\n" + + +def _write(root, files): + for relative, data in files.items(): + path = Path(root) / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data if isinstance(data, bytes) else data.encode("utf-8")) + return Path(root) + + +def _tree(root): + root = Path(root) + return {p.relative_to(root).as_posix(): p.read_bytes() + for p in root.rglob("*") if p.is_file()} + + +def _stamps(): + """Distinct, increasing backup stamps, so order never depends on the clock.""" + number = 0 + while True: + number += 1 + yield f"202601{number:02d}000000" + + +def run_cli(*argv): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \ + mock.patch.dict(os.environ, {"CI": "1"}): + code = cli.main(list(argv)) + return code, out.getvalue(), err.getvalue() + + +class _Profile(unittest.TestCase): + """A profile with the person's own chrome/, and a theme to put in it.""" + + theme_files = {"chrome/userChrome.css": "#nav-bar { color: red }\n"} + profile_files = {"prefs.js": "", "chrome/userChrome.css": ORIGINAL} + + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.theme = _write(self.root / "theme", self.theme_files) + self.profile = _write(self.root / "profile", self.profile_files) + self.stamps = _stamps() + + def install(self, version="v1", **kwargs): + return install.install_theme(self.theme, self.profile, f"o/n@{version}", + stamp=next(self.stamps), **kwargs) + + def upgrade(self, version, keep=3, **kwargs): + """What `fxcss upgrade` does with the library: install, then prune.""" + manifest = install.read_manifest(self.profile) + result = self.install(version, origin_backup=manifest["origin_backup"], **kwargs) + install.prune_backups(self.profile, keep, + protect=[manifest["origin_backup"]]) + return result + + def original_copies(self): + return sorted(p.relative_to(self.profile).as_posix() + for p in self.profile.rglob("userChrome.css") + if p.read_bytes() == ORIGINAL) + + +class OriginalChromeTests(_Profile): + """The chrome/ from before fxcss is never pruned, and uninstall finds it.""" + + def test_a_second_install_keeps_the_first_origin(self): + first = self.install() + second = self.install("v2") + self.assertEqual(second["origin_backup"], first["backup"]) + self.assertNotEqual(second["backup"], first["backup"]) + self.assertTrue(second["user_js_created"]) + for version in ("v3", "v4", "v5", "v6"): + self.upgrade(version) + self.assertEqual(self.original_copies(), [f"{first['backup']}/userChrome.css"]) + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["restored"], first["backup"]) + self.assertEqual((self.profile / "chrome" / "userChrome.css").read_bytes(), ORIGINAL) + # fxcss made user.js on the first install, so it leaves with the theme. + self.assertFalse((self.profile / "user.js").exists()) + + def test_install_twice_then_three_upgrades_from_the_command_line(self): + _write(self.profile, {"user.js": b'user_pref("mine", 1);\r\n'}) + for _ in range(2): + code, _, err = run_cli("install", str(self.theme), "--profile", + str(self.profile), "--yes") + self.assertEqual(code, 0, err) + for number in range(3): + _write(self.theme, {"chrome/userChrome.css": f"#nav-bar {{ order: {number} }}\n"}) + code, out, err = run_cli("upgrade", "--profile", str(self.profile), "--yes") + self.assertEqual(code, 0, err) + self.assertIn("pruned 1 older backup", out) + self.assertEqual(len(self.original_copies()), 1) + code, out, err = run_cli("uninstall", "--profile", str(self.profile), "--yes") + self.assertEqual(code, 0, err) + self.assertEqual((self.profile / "chrome" / "userChrome.css").read_bytes(), ORIGINAL) + self.assertEqual((self.profile / "user.js").read_bytes(), b'user_pref("mine", 1);\r\n') + + def test_an_origin_recorded_by_an_older_fxcss_is_followed_to_the_original(self): + """0.25 recorded the previous *theme's* backup as the origin here.""" + first = self.install() + second = self.install("v2") + path = self.profile / "chrome" / install.MANIFEST_NAME + data = json.loads(path.read_text(encoding="utf-8")) + data["origin_backup"] = second["backup"] + path.write_text(json.dumps(data), encoding="utf-8") + + self.assertEqual(install.read_manifest(self.profile)["origin_backup"], + first["backup"]) + for version in ("v3", "v4", "v5", "v6"): + self.upgrade(version) + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["restored"], first["backup"]) + self.assertEqual((self.profile / "chrome" / "userChrome.css").read_bytes(), ORIGINAL) + + def test_a_profile_that_began_without_chrome_ends_without_it(self): + import shutil + shutil.rmtree(self.profile / "chrome") + first = self.install() + self.assertIsNone(first["origin_backup"]) + second = self.install("v2") + self.assertIsNone(second["origin_backup"]) + # The same profile as 0.25 left it: the first theme named as origin. + path = self.profile / "chrome" / install.MANIFEST_NAME + data = json.loads(path.read_text(encoding="utf-8")) + data["origin_backup"] = second["backup"] + path.write_text(json.dumps(data), encoding="utf-8") + self.assertIsNone(install.read_manifest(self.profile)["origin_backup"]) + summary = install.uninstall_theme(self.profile) + self.assertIsNone(summary["restored"]) + self.assertFalse((self.profile / "chrome").exists()) + + def test_a_manifest_chain_that_loops_ends(self): + first = self.install() + second = self.install("v2") + inner = self.profile / second["backup"] / install.MANIFEST_NAME + data = json.loads(inner.read_text(encoding="utf-8")) + data["origin_backup"] = second["backup"] + inner.write_text(json.dumps(data), encoding="utf-8") + active = self.profile / "chrome" / install.MANIFEST_NAME + data = json.loads(active.read_text(encoding="utf-8")) + data["origin_backup"] = second["backup"] + active.write_text(json.dumps(data), encoding="utf-8") + self.assertEqual(install.read_manifest(self.profile)["origin_backup"], + second["backup"]) + self.assertTrue((self.profile / first["backup"]).is_dir()) + + def test_rolling_back_twice_then_upgrading_keeps_the_original(self): + first = self.install() + install.rollback_to(self.profile, first["origin_backup"], stamp=next(self.stamps)) + self.assertEqual((self.profile / "chrome" / "userChrome.css").read_bytes(), ORIGINAL) + theme_backup = install.list_backups(self.profile)[0]["name"] + summary = install.rollback_to(self.profile, theme_backup, stamp=next(self.stamps)) + # The original now lives under the name the second rollback gave it, + # and the restored manifest says so instead of naming a folder that + # no longer exists. + manifest = install.read_manifest(self.profile) + self.assertEqual(manifest["origin_backup"], summary["moved_aside"]) + for version in ("v2", "v3", "v4", "v5"): + self.upgrade(version) + self.assertEqual(self.original_copies(), + [f"{summary['moved_aside']}/userChrome.css"]) + done = install.uninstall_theme(self.profile) + self.assertEqual(done["restored"], summary["moved_aside"]) + self.assertEqual((self.profile / "chrome" / "userChrome.css").read_bytes(), ORIGINAL) + + def test_rollback_leaves_a_recorded_origin_that_still_exists_alone(self): + first = self.install() + second = self.upgrade("v2") + # The person replaces chrome/ by hand, then rolls back to the theme. + import shutil + shutil.rmtree(self.profile / "chrome") + _write(self.profile, {"chrome/userChrome.css": "/* by hand */\n"}) + install.rollback_to(self.profile, second["backup"], stamp=next(self.stamps)) + self.assertEqual(install.read_manifest(self.profile)["origin_backup"], + first["origin_backup"]) + + def test_rollback_to_an_older_theme_borrows_the_origin_the_newer_one_knows(self): + first = self.install() + install.rollback_to(self.profile, first["origin_backup"], stamp=next(self.stamps)) + theme_backup = install.list_backups(self.profile)[0]["name"] + # A fresh install over the restored original records it under a new name… + again = self.install("v2") + self.assertNotEqual(again["origin_backup"], first["origin_backup"]) + # …which the older theme's manifest, written before any of this, cannot know. + install.rollback_to(self.profile, theme_backup, stamp=next(self.stamps)) + manifest = install.read_manifest(self.profile) + self.assertEqual(manifest["theme"], "o/n@v1") + self.assertEqual(manifest["origin_backup"], again["origin_backup"]) + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["restored"], again["origin_backup"]) + self.assertEqual((self.profile / "chrome" / "userChrome.css").read_bytes(), ORIGINAL) + + def test_a_rollback_that_fails_leaves_the_backups_manifest_as_it_was(self): + first = self.install() + install.rollback_to(self.profile, first["origin_backup"], stamp=next(self.stamps)) + theme_backup = install.list_backups(self.profile)[0]["name"] + before = _tree(self.profile) + rename = Path.rename + + def fail(path, target): + if path == self.profile / theme_backup: + raise PermissionError("simulated: the backup cannot be activated") + return rename(path, target) + + with mock.patch.object(Path, "rename", fail), self.assertRaises(RuntimeError): + install.rollback_to(self.profile, theme_backup, stamp=next(self.stamps)) + self.assertEqual(_tree(self.profile), before) + + def test_a_backup_without_a_manifest_is_never_pruned(self): + self.install() + _write(self.profile, {"chrome.backup-20200101000000/userChrome.css": "/* hand-made */\n", + "chrome.backup-20200102000000/notes.css": "/* also mine */\n"}) + for version in ("v2", "v3", "v4", "v5", "v6"): + self.upgrade(version, keep=1) + self.assertTrue((self.profile / "chrome.backup-20200101000000").is_dir()) + self.assertTrue((self.profile / "chrome.backup-20200102000000").is_dir()) + themes = [b for b in install.list_backups(self.profile) if b["manifest"]] + self.assertEqual(len(themes), 1) + self.assertEqual(install.prune_backups(self.profile, 0), [themes[0]["name"]]) + self.assertEqual(len(install.list_backups(self.profile)), 3) + + +class CustomChromeHookTests(_Profile): + """customChrome.css is the person's hook once they put anything in it.""" + + theme_files = {"chrome/userChrome.css": '@import "customChrome.css";\n#nav-bar { }\n'} + MINE = b"/* MY CUSTOMISATIONS */\r\n#nav-bar { color: blue }\r\n" + + def setUp(self): + super().setUp() + self.first = self.install() + self.hook = self.profile / "chrome" / "customChrome.css" + + def test_an_untouched_placeholder_is_neither_edit_nor_addition(self): + self.assertEqual(self.hook.read_text(encoding="utf-8"), install.PLACEHOLDER_TEXT) + got = install.drift(self.profile) + self.assertEqual((got["modified"], got["missing"], got["extra"]), ([], [], [])) + self.assertEqual(install.user_additions(self.profile)["files"], []) + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["restored"], self.first["origin_backup"]) + self.assertEqual(summary["kept"], []) + + def test_a_filled_in_hook_is_the_persons_file_not_an_edit(self): + self.hook.write_bytes(self.MINE) + got = install.drift(self.profile) + self.assertEqual(got["modified"], []) + self.assertEqual(got["extra"], ["chrome/customChrome.css"]) + self.assertEqual(install.local_changes(self.profile), []) + self.assertEqual(install.user_additions(self.profile)["files"], + ["chrome/customChrome.css"]) + + def test_a_deleted_placeholder_does_not_count_as_a_deleted_theme_file(self): + self.hook.unlink() + self.assertEqual(install.drift(self.profile)["missing"], []) + + def test_upgrade_keeps_the_hook_with_and_without_force(self): + self.hook.write_bytes(self.MINE) + for version, on_collision in (("v2", "stop"), ("v3", "theme"), ("v4", "stop")): + with self.subTest(version=version, on_collision=on_collision): + result = self.upgrade(version, on_collision=on_collision) + self.assertEqual(self.hook.read_bytes(), self.MINE) + self.assertEqual(result["user_files"], ["chrome/customChrome.css"]) + self.assertEqual(result["displaced"], []) + + def test_uninstall_leaves_a_filled_in_hook_in_place(self): + self.hook.write_bytes(self.MINE) + self.upgrade("v2") + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["kept"], ["chrome/customChrome.css"]) + self.assertEqual(self.hook.read_bytes(), self.MINE) + + def test_a_placeholder_written_with_crlf_is_still_the_placeholder(self): + """Text mode wrote \\r\\n on Windows; the manifest recorded that digest.""" + crlf = install.PLACEHOLDER_TEXT.replace("\n", "\r\n").encode("utf-8") + self.hook.write_bytes(crlf) + path = self.profile / "chrome" / install.MANIFEST_NAME + data = json.loads(path.read_text(encoding="utf-8")) + data["digests"]["chrome/customChrome.css"] = hashlib.sha256(crlf).hexdigest() + path.write_text(json.dumps(data), encoding="utf-8") + self.assertEqual(install.drift(self.profile)["extra"], []) + self.hook.write_bytes(self.MINE) + self.assertEqual(install.drift(self.profile)["extra"], ["chrome/customChrome.css"]) + self.assertEqual(install.drift(self.profile)["modified"], []) + + def test_a_version_that_starts_shipping_the_file_is_a_real_collision(self): + self.hook.write_bytes(self.MINE) + _write(self.theme, {"chrome/customChrome.css": "/* the theme's own now */\n"}) + with self.assertRaises(install.CollisionError) as caught: + self.upgrade("v2") + self.assertEqual(caught.exception.collisions, ["chrome/customChrome.css"]) + self.assertEqual(self.hook.read_bytes(), self.MINE) + result = self.upgrade("v2", on_collision="theme") + self.assertEqual(result["displaced"], ["chrome/customChrome.css"]) + self.assertEqual((self.profile / result["backup"] / "customChrome.css").read_bytes(), + self.MINE) + + def test_fxcss_upgrade_does_not_refuse_over_a_filled_in_hook(self): + code, _, err = run_cli("install", str(self.theme), "--profile", + str(self.profile), "--yes") + self.assertEqual(code, 0, err) + self.hook.write_bytes(self.MINE) + _write(self.theme, {"chrome/userChrome.css": + '@import "customChrome.css";\n#nav-bar { order: 2 }\n'}) + code, out, err = run_cli("upgrade", "--profile", str(self.profile), "--yes") + self.assertEqual(code, 0, err) + self.assertNotIn("edited since install", out) + self.assertIn("1 file you added will stay active", out) + self.assertEqual(self.hook.read_bytes(), self.MINE) + _write(self.theme, {"chrome/userChrome.css": + '@import "customChrome.css";\n#nav-bar { order: 3 }\n'}) + code, out, err = run_cli("upgrade", "--profile", str(self.profile), "--yes", "--force") + self.assertEqual(code, 0, err) + self.assertEqual(self.hook.read_bytes(), self.MINE) + + +class PinnedUpgradeTests(unittest.TestCase): + """A --ref install does not move, or spend a backup, unless told to.""" + + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.profile = _write(self.root / "profile", {"prefs.js": ""}) + self.downloaded = [] + info = {"owner": "o", "name": "n", "host": "github.com", "kind": "github", + "default_branch": "main", "release": None, "tracked": None, + "commit": {"full_sha": "b" * 40, "sha": "b" * 7, + "date": "2026-01-01", "message": "m"}, + "description": "", "stars": 0, "licence": None} + + def download(owner, name, revision, dest, **kwargs): + self.downloaded.append(revision) + return _write(dest, {"chrome/userChrome.css": f"/* {revision} */\n"}) + + for target, replacement in (("resolve", lambda *a, **k: dict(info)), + ("download", download)): + patcher = mock.patch.object(fetch, target, side_effect=replacement) + patcher.start() + self.addCleanup(patcher.stop) + + def pin(self, ref): + code, _, err = run_cli("install", "o/n", "--ref", ref, "--profile", + str(self.profile), "--yes") + self.assertEqual(code, 0, err) + self.assertEqual(install.read_manifest(self.profile)["source"]["ref_kind"], "explicit") + + def test_a_bare_upgrade_of_a_pinned_install_changes_nothing(self): + for ref in ("v1.0", "main"): + with self.subTest(ref=ref): + self.downloaded.clear() + self.pin(ref) + before = _tree(self.profile) + for _ in range(2): + code, out, err = run_cli("upgrade", "--profile", str(self.profile), "--yes") + self.assertEqual(code, 0, err) + self.assertIn(f"Pinned to {ref} with --ref", out) + self.assertNotIn("upgraded to", out) + self.assertEqual(self.downloaded, [ref]) + self.assertEqual(_tree(self.profile), before) + code, _, _ = run_cli("uninstall", "--profile", str(self.profile), "--yes") + self.assertEqual(code, 0) + + def test_an_explicit_ref_still_moves_a_pinned_install(self): + self.pin("v1.0") + code, out, err = run_cli("upgrade", "--profile", str(self.profile), "--yes", + "--ref", "v1.1") + self.assertEqual(code, 0, err) + self.assertEqual(self.downloaded, ["v1.0", "v1.1"]) + self.assertEqual((self.profile / "chrome" / "userChrome.css").read_text(), + "/* v1.1 */\n") + manifest = install.read_manifest(self.profile) + self.assertEqual((manifest["source"]["ref"], manifest["source"]["ref_kind"]), + ("v1.1", "explicit")) + + def test_commit_takes_a_pinned_install_off_its_pin(self): + self.pin("v1.0") + code, _, err = run_cli("upgrade", "--profile", str(self.profile), "--yes", "--commit") + self.assertEqual(code, 0, err) + self.assertEqual(self.downloaded, ["v1.0", "b" * 40]) + self.assertEqual(install.read_manifest(self.profile)["source"]["ref_kind"], "branch") + + +class LitterTests(_Profile): + """Files the operating system drops are not the person's work.""" + + def test_litter_alone_does_not_stop_uninstall_restoring_the_original(self): + for name in (".DS_Store", "Thumbs.db", "desktop.ini"): + with self.subTest(name=name): + first = self.install() + _write(self.profile, {f"chrome/{name}": b"\x00\x01", + f"chrome/icons/{name}": b"\x00\x02"}) + self.assertEqual(install.drift(self.profile)["extra"], []) + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["restored"], first["origin_backup"]) + self.assertEqual(summary["kept"], []) + self.assertEqual(_tree(self.profile / "chrome"), + {"userChrome.css": ORIGINAL}) + + def test_litter_is_not_carried_into_an_upgrade_as_the_persons_file(self): + self.install() + _write(self.profile, {"chrome/.DS_Store": b"\x00"}) + result = self.upgrade("v2") + self.assertEqual(result["user_files"], []) + self.assertFalse((self.profile / "chrome" / ".DS_Store").exists()) + + def test_litter_beside_real_work_is_left_where_it_is(self): + self.install() + _write(self.profile, {"chrome/.DS_Store": b"\x00", "chrome/mine.css": "#mine { }\n"}) + summary = install.uninstall_theme(self.profile) + self.assertIsNone(summary["restored"]) + self.assertEqual(summary["kept"], ["chrome/.DS_Store", "chrome/mine.css"]) + + def test_a_copy_of_an_original_file_does_not_block_restoring_it(self): + _write(self.profile, {"chrome/mine.css": "#mine { }\n"}) + first = self.install() + _write(self.profile, {"chrome/mine.css": "#mine { }\n"}) + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["restored"], first["origin_backup"]) + self.assertEqual(_tree(self.profile / "chrome"), + {"userChrome.css": ORIGINAL, "mine.css": b"#mine { }\n"}) + + def test_an_edited_copy_of_an_original_file_still_blocks(self): + _write(self.profile, {"chrome/mine.css": "#mine { }\n"}) + self.install() + _write(self.profile, {"chrome/mine.css": "#mine { color: red }\n"}) + summary = install.uninstall_theme(self.profile) + self.assertIsNone(summary["restored"]) + self.assertEqual(summary["kept"], ["chrome/mine.css"]) + + +class AdoptedExtrasTests(unittest.TestCase): + """Files beside an adopted theme that upstream never shipped are kept.""" + + UPSTREAM = b"#a { }\n" + + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.profile = _write(self.root / "profile", { + "prefs.js": "", "chrome/userChrome.css": self.UPSTREAM, + "chrome/my-tweaks.css": "/* MINE */\n", "chrome/.DS_Store": b"\x00"}) + self.before = _tree(self.profile / "chrome") + best = adopt.compare(self.profile / "chrome", + {"chrome/userChrome.css": adopt.blob_sha(self.UPSTREAM)}) + self.assertEqual(best["extra"], [".DS_Store", "my-tweaks.css"]) + self.source = {"kind": "github", "host": "github.com", "owner": "o", "name": "n", + "ref": "v1", "ref_kind": "release", "resolved": "v1", "path": None} + match = dict({key: best[key] for key in ("matched", "files", "score", "differing", + "missing", "extra", "eol")}, ref="v1") + self.manifest = install.adopt_theme(self.profile, "o/n@v1", self.source, match, + stamp="20260101000000") + self.newer = _write(self.root / "v2", {"chrome/userChrome.css": "#a { }\n#new { }\n"}) + + def upgrade(self, **kwargs): + return install.install_theme(self.newer, self.profile, "o/n@v2", + source=dict(self.source, ref="v2"), + origin_backup=self.manifest["origin_backup"], + stamp="20260102000000", **kwargs) + + def test_only_the_matched_versions_files_are_recorded_as_the_themes(self): + self.assertEqual(self.manifest["files"], ["chrome/userChrome.css"]) + self.assertEqual(self.manifest["user_files"], ["chrome/my-tweaks.css"]) + self.assertEqual(install.user_additions(self.profile)["files"], + ["chrome/my-tweaks.css"]) + self.assertEqual(install.local_changes(self.profile), []) + + def test_the_next_upgrade_keeps_them_active(self): + for on_collision in ("stop", "theme"): + with self.subTest(on_collision=on_collision): + result = self.upgrade(on_collision=on_collision) + self.assertEqual(result["user_files"], ["chrome/my-tweaks.css"]) + self.assertEqual((self.profile / "chrome" / "my-tweaks.css").read_bytes(), + b"/* MINE */\n") + + def test_uninstall_straight_after_adopting_puts_everything_back(self): + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["restored"], self.manifest["origin_backup"]) + self.assertEqual(_tree(self.profile / "chrome"), self.before) + + def test_uninstall_after_an_upgrade_restores_the_adopted_chrome(self): + self.upgrade() + summary = install.uninstall_theme(self.profile) + self.assertEqual(summary["restored"], self.manifest["origin_backup"]) + self.assertEqual(_tree(self.profile / "chrome"), self.before) + + def test_an_extra_edited_since_is_kept_rather_than_replaced(self): + self.upgrade() + _write(self.profile, {"chrome/my-tweaks.css": "/* MINE, and newer */\n"}) + summary = install.uninstall_theme(self.profile) + self.assertIsNone(summary["restored"]) + self.assertEqual(summary["kept"], ["chrome/my-tweaks.css"]) + self.assertTrue((self.profile / self.manifest["origin_backup"]).is_dir()) + + +class StrayMarkerTests(_Profile): + """A BEGIN marker with no END of its own never claims a later block's.""" + + ORPHAN = (b'user_pref("a", 1);\n/* >>> fxcss install >>> */\n' + b'user_pref("mine.one", 1);\nuser_pref("mine.two", 2);\n') + + def test_strip_leaves_the_lines_under_an_orphan_marker(self): + text = self.ORPHAN.decode() + self.assertEqual(install.strip_user_js_block(text), text) + with_block = install.user_js_with_block(text, install.STYLESHEET_PREF) + self.assertEqual(install.strip_user_js_block(with_block), text) + self.assertEqual(install.user_js_with_block(with_block, install.STYLESHEET_PREF), + with_block) + + def test_two_well_formed_blocks_are_both_removed(self): + block = f"{install.BLOCK_BEGIN}\nuser_pref(\"x\", 1);\n{install.BLOCK_END}\n" + self.assertEqual(install.strip_user_js_block(f"a\n\n{block}b\n\n{block}"), "a\nb\n") + + def test_install_reinstall_and_uninstall_return_user_js_byte_for_byte(self): + _write(self.profile, {"user.js": self.ORPHAN}) + self.install() + self.install("v2") + text = (self.profile / "user.js").read_bytes() + self.assertIn(b'user_pref("mine.one", 1);\nuser_pref("mine.two", 2);\n', text) + self.assertEqual(text.count(install.BLOCK_END.encode()), 1) + install.uninstall_theme(self.profile) + self.assertEqual((self.profile / "user.js").read_bytes(), self.ORPHAN) + + +class PrefNamesTests(unittest.TestCase): + """Every pref a theme is about to set is named before it is set.""" + + SPACED = ('user_pref("a.one", 1);\n' + 'user_pref ("network.proxy.autoconfig_url", "https://example.invalid/p.pac");\n' + 'user_pref\n("network.proxy.type", 2);\n' + 'user_pref/* c */("browser.startup.homepage", "about:blank");\n' + 'pref\t( \'sticky.one\' , true);\n') + NAMES = ["a.one", "network.proxy.autoconfig_url", "network.proxy.type", + "browser.startup.homepage", "sticky.one"] + + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + + def test_whitespace_before_the_parenthesis_does_not_hide_a_pref(self): + theme = _write(self.root, {"chrome/userChrome.css": "#a { }\n", + "configuration/user.js": self.SPACED}) + self.assertEqual(install.theme_pref_names(theme), self.NAMES) + self.assertEqual(checklist.pref_names_in(theme / "configuration" / "user.js"), + self.NAMES) + + def test_a_longer_function_name_is_not_mistaken_for_one(self): + theme = _write(self.root, {"chrome/userChrome.css": "#a { }\n", + "configuration/user.js": 'my_user_pref_helper ("x", 1);\n' + 'defaultPref("y", 1);\n'}) + self.assertEqual(install.theme_pref_names(theme), []) + + def test_control_characters_in_a_name_are_escaped(self): + theme = _write(self.root, {"chrome/userChrome.css": "#a { }\n", + "configuration/user.js": + 'user_pref("evil\x1b[2Jname\x07", 1);\n'}) + for names in (install.theme_pref_names(theme), + checklist.pref_names_in(theme / "configuration" / "user.js")): + self.assertEqual(names, ["evil\\x1b[2Jname\\x07"]) + rendered = "\n".join(checklist.render(checklist.build(theme, theme))) + self.assertNotIn("\x1b[2J", rendered) + self.assertNotIn("\x07", rendered) + + def test_prefs_fxcss_will_write_are_all_named_and_others_are_summarised(self): + many = "".join(f'user_pref("theme.pref.{n}", true);\n' for n in range(8)) + theme = _write(self.root, {"chrome/userChrome.css": "#a { }\n", + "configuration/user.js": many, + "prefs/optional.js": many.replace("theme.", "other.")}) + items = checklist.build(theme, theme) + by_file = {item["pref_file"]: item for item in items if item.get("pref_file")} + self.assertEqual(by_file["configuration/user.js"]["state"], "applied") + self.assertNotEqual(by_file["prefs/optional.js"]["state"], "applied") + with mock.patch.dict(os.environ, {"NO_COLOR": "1", "COLUMNS": "100"}): + rendered = " ".join(" ".join(checklist.render(items)).split()) + for number in range(8): + self.assertIn(f"theme.pref.{number}", rendered) + self.assertIn(f"theme.pref.{number}", by_file["configuration/user.js"]["item"]) + self.assertIn("other.pref.4", rendered) + self.assertNotIn("other.pref.5", rendered) + self.assertIn("and 3 more", rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_units.py b/tests/test_units.py index 8a7a911..456e91a 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -2488,10 +2488,10 @@ def test_edits_additions_and_deletions_are_each_named(self): "/* edited by hand */\n", encoding="utf-8") (profile / "chrome" / "mine.css").write_text("#a{}\n", encoding="utf-8") - (profile / "chrome" / "customChrome.css").unlink() + (profile / "chrome" / "WhiteSur" / "theme.css").unlink() got = drift(profile) self.assertEqual(got["modified"], ["chrome/userChrome.css"]) - self.assertEqual(got["missing"], ["chrome/customChrome.css"]) + self.assertEqual(got["missing"], ["chrome/WhiteSur/theme.css"]) self.assertEqual(got["extra"], ["chrome/mine.css"]) def test_the_manifest_itself_is_not_an_addition(self): @@ -2807,8 +2807,12 @@ def test_a_backup_outside_the_profile_is_refused(self): class PruneBackupsTests(unittest.TestCase): def _stack(self, profile, count): + """Backups of themes fxcss installed: each holds that install's manifest.""" for i in range(count): - (profile / f"chrome.backup-2026081412000{i}").mkdir(parents=True) + backup = profile / f"chrome.backup-2026081412000{i}" + backup.mkdir(parents=True) + (backup / "fxcss-install.json").write_text( + json.dumps({"theme": f"o/n@v{i}"}), encoding="utf-8") def test_keeps_the_newest_and_never_the_protected_one(self): from fxcss.install import prune_backups From 49f77d3e1dc4d9f021a03b4f8bbb6134cddf153e Mon Sep 17 00:00:00 2001 From: adamXbot <111877622+adamXbot@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:48:04 +1100 Subject: [PATCH 2/2] Finish the terminal polish and bring the README in line with it Menus, output and wording left over from the terminal work, and the README samples that still showed the old format. - A menu whose prompt wraps is redrawn where it was. The way back to the top was counted in rows, not terminal lines, so a 60-column terminal, or a dozen typed characters at 80, left every earlier frame on screen. - upgrade, rollback, adopt, uninstall and init open with a title and aligned rows and close with a tick, as install does. `upgrade --no-colour` now holds for the whole command. - `fxcss doctor` outside a theme folder reports on Firefox alone instead of stopping with "no userChrome.css anywhere"; the installer and the docs send people to it first. - Output in a code page with no arrow or tick in it gets an ASCII stand-in instead of a UnicodeEncodeError. - Colour on a Windows console first asks it to act on the codes, and is left off where it will not. - `init` warns that its pin must be published on PyPI only when this copy did not come from PyPI. - "1 element matches", "1 token out of reach", no heading over nothing in the audit, "under 1 KB" rather than "0 KB", and a yes/no question no longer sits a column to the right when it opens with a blank line. - Tests no longer depend on FORCE_COLOR being unset. - README: the try, version prompt, profiles, adopt, upgrade, rollback and audit samples are real 0.26 output, and the notes on pins, hooks, backups and doctor describe what now happens. Co-Authored-By: Claude Fable 5.2 --- README.md | 172 +++++++++++------ fxcss/audit.py | 17 +- fxcss/cli.py | 345 ++++++++++++++++++++++++---------- fxcss/probe.py | 2 +- fxcss/prompt.py | 46 +++-- fxcss/style.py | 63 ++++++- tests/test_data_safety.py | 6 +- tests/test_maintenance_cli.py | 26 ++- tests/test_prompt.py | 90 +++++++++ tests/test_terminal_style.py | 37 ++++ tests/test_units.py | 81 +++++++- tests/test_welcome_context.py | 63 +++++++ 12 files changed, 752 insertions(+), 196 deletions(-) diff --git a/README.md b/README.md index 7b912a2..610ef8b 100644 --- a/README.md +++ b/README.md @@ -84,24 +84,40 @@ is never touched — close the window and nothing remains. It reports what it found before doing anything: ``` - adamxweb/whitesurfirefoxthememacos ★614 MIT - MacOS Big Sur like theme for Firefox on MacOS & Windows. - latest release v1.6.3 (2025-07-26) - latest commit b10c574 (2025-07-26) Merge pull request #167 … + fxcss try AdamXweb/WhiteSurFirefoxThemeMacOS - fetching release v1.6.3 … - theme found at the repository root (39 stylesheets, 134 KB) + AdamXweb/WhiteSurFirefoxThemeMacOS ★619 MIT + MacOS Big Sur like theme for Firefox on MacOS & Windows. Make your Firefox look like Safari. + latest release v2.1.0 (2026-10-28) + latest commit 68f8699 (2026-11-10) fix: align the toolbar and close the tab bar gap … - This theme ships install.sh. fxcss does not run it — - it installs the files itself, which is all those scripts do. + fetching release v2.1.0 … - Options its README documents: - -c Left hand side tab close button - -p Makes tabs height compact like current Safari + layout chrome/ at the repository root 72 stylesheets, 377 KB + loads 35 stylesheets 29 browser-window, 2 web-content, 4 shared + user hook customChrome.css not shipped, as intended + installer install.sh fxcss copies the files itself and never runs it + + Optional stylesheets 30 · layer any on with --with name,name + Tweaks + compact-tabs hideextension increase-contrast singletabhidden tabs-swapclose + enabletabview highlight-tab noidentity standard-urlbar windows-swapclose + + Colour schemes · pick one + theme-ayu-mirage theme-github-dark theme-nord + theme-catppuccin-frappe theme-gruvbox-dark theme-one-dark … - Optional stylesheets you can layer on with --with: - compact-tabs, hideextension, noidentity, tabs-swapclose, … + Setup beyond the files 1 automatic · 3 to check + ✓ automatic 3 prefs in configuration/user.js in fxcss's own block + ! check Firefox's native vertical tabs + a setting in Firefox's own sidebar options + … + + README install flags as the README words them, for its own script; fxcss never runs it + -c Left hand side tab close button -v Re-enables the tabview button + -p Makes tabs height compact like… -t Colour theme (see Colour themes below) + … ``` Releases are preferred over branch tips, since that is what the author blessed; @@ -345,10 +361,11 @@ looking for, and equally the branch can be mid-rewrite, so neither is right to assume: ``` - The default branch has moved on since the latest release: - 1. release v2.0 2025-01-03 what the author last published (Enter) - 2. latest commit on master 2026-08-14 newer than the release — fix tab colours - Install [1-2]: + Which version? the default branch has moved on since the latest release + 1. release v2.0 2025-01-03 what the author last published (Enter) + 2. latest commit on master 2026-08-14 newer than the release — fix tab colours + + Which one? 1-2 [1] ``` Scripts and CI never see any of these prompts: without a terminal the release @@ -421,17 +438,30 @@ guess — it is the same bytes: ```console $ fxcss adopt AdamXweb/WhiteSurFirefoxThemeMacOS - profile: default-release (~/Library/…/8f2h1kqp.default-release) + fxcss adopt default-release + + profile default-release + ~/Library/Application Support/Firefox/Profiles/8f2h1kqp.default-release - comparing 148 file(s) against AdamXweb/WhiteSurFirefoxThemeMacOS … + comparing 148 files against AdamXweb/WhiteSurFirefoxThemeMacOS … v2.0.0: 129/135 files match, 6 edited, 7 added v1.6.3: 114/132 files match, 18 edited, 10 added best match: v2.0.0: 129/135 files match, 6 edited, 7 added Recorded as that version plus local differences, so an upgrade knows not to overwrite them without being told. + + backup the theme as it is now, kept as chrome.backup-20260817014143 + yours 7 files that version does not ship, kept as your own across upgrades + + ✓ Recorded 135 files as AdamXweb/WhiteSurFirefoxThemeMacOS@v2.0.0 + fxcss upgrade can now update it, and fxcss uninstall puts this back. ``` +Files in `chrome/` that the matched version does not contain are recorded as +yours, not the theme's: upgrades carry them across and `uninstall` leaves them +where they are. + Comparison uses GitHub's git-tree API rather than downloading anything, so checking ten versions costs ten small requests instead of ten archives — and archives are the first thing GitHub rate-limits. @@ -484,22 +514,23 @@ names: ```console $ fxcss profiles --check - Firefox profiles on this machine + fxcss profiles - ● default-release [Release] - ~/Library/Application Support/Firefox/Profiles/8f2h1kqp.default-release - theme AdamXweb/WhiteSurFirefoxThemeMacOS @ v1.0.0 - installed 2026-08-14 09:12:44 (tracking the release) - sheets theme-nord - files 137 file(s), 1 edited since install, 1 added by hand - update v2.0.0 available — 2026-08-16 + Firefox profiles + 2 in ~/Library/Application Support/Firefox/Profiles - dev-edition-default [Developer Edition] - ~/Library/Application Support/Firefox/Profiles/p93kd0zx.dev-edition-default - chrome/ 41 file(s), not installed by fxcss - `fxcss install` here would back this up first + ● default-release Release 8f2h1kqp.default-release + theme AdamXweb/WhiteSurFirefoxThemeMacOS @ v2.0.0 + installed 2026-08-14 09:12 tracking the release + sheets theme-nord + files 145 ! 1 edited since install, 1 added by hand + update v2.1.0 available 2026-10-28 - ● the profile Firefox opens by default + dev-edition-default Developer Edition p93kd0zx.dev-edition-default + theme ! installed by hand chrome/ holds 41 files + fxcss adopt takes it over; fxcss install would replace it, backing it up first + + ● opens by default: the profile Firefox opens on its own ``` Three states, kept distinct on purpose: a profile fxcss installed into and can @@ -545,7 +576,9 @@ It stops rather than surprise you, in four places: them until `--force`. - **Files you added.** A stylesheet you dropped into `chrome/` — imported from `customChrome.css`, say — is carried into the new tree so it stays - *active*, not merely kept in the backup where it would stop applying. The + *active*, not merely kept in the backup where it would stop applying. + `customChrome.css` itself counts as yours once you have written in it, even + though fxcss created the empty file. The manifest lists them under `user_files`. If the new version ships a file at the same path with different contents, that is a collision: the upgrade stops before anything moves and lists the paths; `--force` installs the @@ -588,19 +621,24 @@ one taken from `src/userChrome-WhiteSur.css` from the same edition. ```console $ fxcss upgrade - profile: default-release (~/Library/…/8f2h1kqp.default-release) - installed: AdamXweb/WhiteSurFirefoxThemeMacOS @ v1.6.3 - upstream: v2.0.0 — 2026-08-16 + fxcss upgrade default-release + + profile default-release + ~/Library/Application Support/Firefox/Profiles/8f2h1kqp.default-release + installed AdamXweb/WhiteSurFirefoxThemeMacOS @ v1.6.3 + upstream v2.0.0 2026-08-16 fetching v2.0.0 … - keeping optional sheets: theme-nord + layout chrome/ at the repository root 72 stylesheets, 377 KB + loads 35 stylesheets 29 browser-window, 2 web-content, 4 shared + sheets keeping theme-nord Upgrade to v2.0.0? [Y/n] - upgraded to v2.0.0 - the previous version is kept as chrome.backup-20260817014202 + backup the previous version, kept as chrome.backup-20260817014202 - Restart Firefox to see it. `fxcss rollback` puts the previous version back. + ✓ Upgraded to v2.0.0 + Restart Firefox to see it; fxcss rollback puts the previous version back. ``` ### fxcss rollback @@ -620,12 +658,19 @@ list can show what each one holds: ```console $ fxcss rollback --list - Backups, newest first: + fxcss rollback default-release + profile default-release + ~/Library/Application Support/Firefox/Profiles/8f2h1kqp.default-release + installed AdamXweb/WhiteSurFirefoxThemeMacOS @ v2.0.0 + + Backups newest first chrome.backup-20260817014202 AdamXweb/WhiteSurFirefoxThemeMacOS@v1.6.3 - chrome.backup-20260817014143 (the original) + chrome.backup-20260817014143 the original your own chrome/, from before fxcss + + fxcss rollback --to restores one of these. ``` `fxcss rollback` restores the most recent, or `--to ` any of them. @@ -639,7 +684,8 @@ That original is the reason upgrades chain rather than stack blindly. After five upgrades the newest backup holds *the theme*, not your files, so the manifest carries the original's name forward and `fxcss uninstall` still restores what you had before you ever ran fxcss. `--keep N` (default 3) prunes -older backups; the original is never one of them. +older backups; the original is never one of them, and neither is any +`chrome.backup-*` folder that holds no fxcss install record. ### fxcss uninstall @@ -1252,20 +1298,21 @@ class your CSS mentions, resolves each against a running Firefox, and shows what to change — with the real line from your file and the replacement applied: ``` - 14 selectors need attention - - RENAMED #urlbar-background → .urlbar-background - same name, now a class rather than an id - - chrome/parts/headerbar-urlbar.css:52 - - #urlbar-background { - + .urlbar-background { + ✗ 14 selectors need attention - SIMILAR #appMenu-fullscreen-button → #appMenu-fullscreen-button2 (a guess, not applied) - no exact match; closest live name is #appMenu-fullscreen-button2 + ✗ RENAMED #urlbar-background → .urlbar-background + same name, now a class rather than an id + chrome/parts/headerbar-urlbar.css:52 + - #urlbar-background { + + .urlbar-background { - chrome/parts/icons.css:198 - #appMenu-fullscreen-button { + ! SIMILAR #appMenu-fullscreen-button → #appMenu-fullscreen-button2 a guess, not applied + no exact match; closest live name is #appMenu-fullscreen-button2 + #appMenu-fullscreen-button2 belongs to browser.xhtml + check what reads that name before using it: a close + spelling can belong to an unrelated element + chrome/parts/icons.css:198 + #appMenu-fullscreen-button { ``` These examples come from findings in a long-running theme. The @@ -1402,11 +1449,12 @@ generated workflows cannot select them yet; lay the theme out as Existing files are preserved unless you pass `--force`; review regenerated files before committing, especially if you have customised them. Generation pins the installed fxcss version. These layout, trigger and patch-mapping -changes need fxcss **0.26.0 or later**; a PyPI pin only works after that -version is published. -Before release, use `fxcss init --toolkit-ref ` -to install the reviewed toolkit commit directly in generated workflows. This -does not publish a release. The preview +changes need fxcss **0.26.0 or later**. +To try an fxcss commit that is not released yet, use +`fxcss init --toolkit-ref `: the generated +workflows then install that commit directly instead of a PyPI version. `init` +says so when the copy you are running did not come from PyPI, since a pin to +an unpublished version cannot install. The preview publisher validates variant filenames and PNG headers, including options added by later PRs. Updating fxcss locally does not update workflows already in a repository. @@ -1716,7 +1764,9 @@ fxcss doctor Reports your Firefox version, whether `userChrome.css` is enabled, whether context menus are themeable on your platform, how many stylesheets your theme has — and **every Gecko build installed on the machine**, with versions. Start -here if something isn't behaving. +here if something isn't behaving. Run outside a theme folder, it reports on +Firefox alone, so it also works as a first check straight after installing +fxcss. ### Requirements diff --git a/fxcss/audit.py b/fxcss/audit.py index 45c74ca..cf3b0ef 100644 --- a/fxcss/audit.py +++ b/fxcss/audit.py @@ -732,8 +732,7 @@ def print_context(rows, show_all, on, hint=None): for kind, label in _KINDS: group = [r for r in rows if r.get("kind") == kind] if group: - noun = label.split()[0] - parts.append(f"{sum(r['count'] for r in group):,} {noun} {short[kind]}") + parts.append(f"{style.plural(sum(r['count'] for r in group), kind)} {short[kind]}") parts += [f"{r['count']:,} {r['text']}" for r in rows if r.get("kind") not in dict(_KINDS)] for line in style.rows([("not counted", f" {style.DOT} ".join(parts) + " (--all explains)")], @@ -1117,12 +1116,17 @@ def report_unused(unused, colour=True, show_all=False, context=None): "is what this Firefox provides", width=name_width) print() - print(style.heading_line("Unused and unreachable", - "housekeeping, not breakage: nothing here stops the theme working", - on=on)) notes = [] if context is None else context - analysis = unused.get("analysis") or {} + # A heading only over something: with undefined properties and nothing + # else, it used to stand alone above the closing lines. + if (total == 0 or len(unused["missing_properties"]) < total + or not analysis.get("complete", True)): + print(style.heading_line("Unused and unreachable", + "housekeeping, not breakage: nothing here stops the theme working", + on=on)) + print() + if analysis and not analysis.get("complete", True): print(_status("INCOMPLETE", "warn", on) + "the import graph could not be read in full, so the findings") @@ -1150,7 +1154,6 @@ def report_unused(unused, colour=True, show_all=False, context=None): "short": "content-only stylesheet" if n == 1 else "content-only stylesheets", "text": ("stylesheet that loads" if n == 1 else "stylesheets that load") + " only through userContent.css, for web and extension pages"}) - print() if unused["orphans"]: print(_status("NOT IMPORTED", "warn", on) diff --git a/fxcss/cli.py b/fxcss/cli.py index 6bcc03a..d74e7d7 100644 --- a/fxcss/cli.py +++ b/fxcss/cli.py @@ -562,7 +562,8 @@ def _inventory_report(theme_root, facts, strict, force, quiet=False): print(f" {line}") if found["entry_unresolved"]: names = ", ".join(f"{e['source']} → {e['target']}" for e in found["entry_unresolved"][:4]) - print("\n The entry stylesheet imports file(s) this source does not contain:" + print(f"\n The entry stylesheet imports " + f"{_agree(len(found['entry_unresolved']), 'files', 'a file')} this source does not contain:" f"\n {names}\n That usually means the theme needs building — a release " "package, or its\n own installer's output — rather than a copy of its sources.", file=sys.stderr) @@ -639,7 +640,7 @@ def _source_rows(plan, facts, found, remote): where = (("the repository root" if remote else "the top of the folder") if key in (".", "") else key) size = style.muted(f"{style.plural(facts['stylesheets'], 'stylesheet')}, " - f"{facts['bytes'] // 1024:,} KB") + f"{_size(facts['bytes'])}") named = (f" {selected['named']['name']!r}" if selected.get("kind") == layout.NAMED else "") flags = [] @@ -685,7 +686,10 @@ def _report_checklist(repo_root, theme_root, plan, pref_files): from . import checklist items = checklist.build(repo_root, theme_root, plan, applied_pref_files=pref_files) - for line in checklist.render(items): + lines = checklist.render(items) + if lines: + print() + for line in lines: print(line) return items @@ -1541,14 +1545,61 @@ def row(i, current, pointer): return picked["ref"], picked["why"] +def _rows(pairs): + """Label and value rows, in the one column `install` set for them.""" + from . import style + for line in style.rows(pairs, indent=2, label_width=10): + print(line) + + +def _profile_header(command, picked, manifest=None): + """Open a command that works on one profile: its title, then what is there.""" + from . import style + print(style.title(command, picked["name"])) + print() + pairs = [("profile", [style.strong(picked["name"]), + style.muted(_short_path(picked["path"]))])] + if manifest and (manifest.get("source") or manifest.get("theme")): + label = _theme_label(manifest) + if (manifest.get("source") or {}).get("kind") == "local": + pairs.append(("installed", [style.strong(Path(label).name), + style.muted(style.short_path(label))])) + else: + pairs.append(("installed", style.strong(label))) + _rows(pairs) + + +def _running_note(picked, effect="the change shows after a restart"): + from . import install, style + if install.firefox_running(picked["path"]): + _rows([("note", style.warn(f"Firefox is running; {effect}"))]) + + +def _done(verb, rest="", note=None): + """The closing line of a change: a tick, what happened in bold, then to what.""" + from . import style + print(f"\n {style.good(style.TICK)} {style.strong(verb)}{' ' + rest if rest else ''}" + + (f" {style.muted(note)}" if note else "")) + + +def _then(*parts): + """What to do next, dim, with any `fxcss command` in it bold.""" + from . import style + print(" " + " ".join(style.cmd(part[1:-1]) if part.startswith("`") else style.muted(part) + for part in parts)) + + def _confirm(question, interactive, assume_yes): """Enter means yes; only an explicit n declines. Never asks in CI.""" if assume_yes or not interactive: return True from . import style + # A question may open with a blank line; the indent is what follows it. + above = len(question) - len(question.lstrip("\n")) + question = question[above:] lead = len(question) - len(question.lstrip()) try: - raw = input(style.ask(question.strip(), default="Y/n", indent=lead or 2)) + raw = input("\n" * above + style.ask(question.strip(), default="Y/n", indent=lead or 2)) except EOFError: raw = "" return not raw.strip().lower().startswith("n") @@ -1706,15 +1757,12 @@ def cmd_uninstall(args): and not os.environ.get("CI")) picked = _choose_profile(args.profile, interactive, prefer="managed") manifest = install.read_manifest(picked["path"]) - print(f"\n profile: {picked['name']} ({picked['path']})") - if manifest and manifest.get("theme"): - print(f" installed theme: {manifest['theme']}") - if install.firefox_running(picked["path"]): - print(" note: Firefox appears to be running — the change will only " - "show after a restart.") - if not _confirm(" Remove the installed theme from this profile?", + from . import style + _profile_header("uninstall", picked, manifest) + _running_note(picked) + if not _confirm("\n Remove the installed theme from this profile?", interactive, args.yes): - print(" nothing removed.") + print(style.muted(" Nothing removed.")) return 1 try: result = install.uninstall_theme(picked["path"]) @@ -1722,25 +1770,33 @@ def cmd_uninstall(args): print(f"error: {exc}", file=sys.stderr) return 2 if result.get("noop"): - print(" no fxcss-installed theme is active here, so nothing was " + print("\n No fxcss-installed theme is active here, so nothing was " "removed or restored.") + pairs = [] if result.get("user_js_cleaned"): - print(" user.js: removed a leftover fxcss block") + pairs.append(("user.js", "removed a leftover fxcss block")) if result.get("backups"): - print(f" backups kept: {', '.join(result['backups'])} " - "(`fxcss rollback --to ` restores one)") + pairs.append(("backups", [", ".join(result["backups"]), + style.cmd("fxcss rollback --to ") + + style.muted(" restores one")])) + _rows(pairs) return 0 - if result["removed"]: - print(f" removed {_pl(result['removed'], 'file')}") + pairs = [] if result["restored"]: - print(f" restored your previous chrome/ from {result['restored']}") + pairs.append(("restored", f"your previous chrome/, from {result['restored']}")) if result["moved_aside"]: - print(f" moved the current chrome/ to {result['moved_aside']} " - "(fxcss could not prove it wrote it, so nothing is deleted)") + pairs.append(("moved", [f"the current chrome/, to {result['moved_aside']}", + style.muted("fxcss could not prove it wrote it, so " + "nothing is deleted")])) if result["kept"]: - print(f" left {len(result['kept'])} added, modified or unverifiable " - "file(s) in chrome/; any backup stays put alongside them") - print("\n Restart Firefox to see the change.") + pairs.append(("kept", [f"{_pl(len(result['kept']), 'file')} you added or edited, " + "or that could not be checked, still in chrome/", + style.muted("any backup stays put alongside them")])) + if pairs: + print() + _rows(pairs) + _done("Uninstalled", note=f"{_pl(result['removed'], 'file')} removed") + _then("Restart Firefox to see the change.") return 0 @@ -1800,6 +1856,19 @@ def _report_drift(moved, indent=" "): def cmd_upgrade(args): + """`upgrade`, with --no-colour holding for all of it and for nothing after.""" + from . import style + if not args.no_colour: + return _upgrade(args) + previous = style._override + style.set_colour(False) + try: + return _upgrade(args) + finally: + style.set_colour(previous) + + +def _upgrade(args): import shutil import tempfile from . import fetch, install @@ -1808,7 +1877,8 @@ def cmd_upgrade(args): and not os.environ.get("CI")) picked = _choose_profile(args.profile, interactive, prefer="managed") manifest = install.read_manifest(picked["path"]) - print(f"\n profile: {picked['name']} ({picked['path']})") + from . import style + _profile_header("upgrade", picked, manifest) if not manifest: print("\n Nothing fxcss installed in this profile, so there is " "nothing to\n upgrade. `fxcss install ` puts one here; " @@ -1816,7 +1886,6 @@ def cmd_upgrade(args): return 2 source = manifest.get("source") or {} - print(f" installed: {_theme_label(manifest)}") recorded_layout = manifest.get("layout") if isinstance(manifest.get("layout"), dict) else {} if args.subpath is None and recorded_layout.get("subpath"): args.subpath = recorded_layout["subpath"] @@ -1856,10 +1925,9 @@ def cmd_upgrade(args): else: target_ref, why = state.get("ref") or source.get("ref"), \ state.get("label") or "what is installed" - print(f" upstream: {state['label']}" - + (f" — {state['detail']}" if state.get("detail") else "")) - if state.get("also"): - print(f" also: {state['also']}") + _rows([("upstream", state["label"] + (f" {style.muted(state['detail'])}" + if state.get("detail") else "")), + ("", style.muted(state["also"]) if state.get("also") else None)]) else: print("\n error: this install has no record of where it came from, " "so fxcss\n cannot fetch a newer copy. Reinstall it with " @@ -1919,15 +1987,21 @@ def cmd_upgrade(args): repo_root = fetch.download(info["owner"], info["name"], revision, workdir / "src", host=info["host"]) - planned = _plan_source(repo_root, args, interactive, workdir) + planned = _plan_source(repo_root, args, interactive, workdir, + remote=local_root is None, quiet=True) if planned is None: print(" (the recorded layout no longer matches this version; choose " "with --subpath)", file=sys.stderr) return 2 plan, theme_root = planned facts = fetch.describe(plan["repo_root"], theme_root, plan) - if _inventory_report(theme_root, facts, strict=True, force=args.force) is None: + found = _inventory_report(theme_root, facts, strict=True, force=args.force, + quiet=True) + if found is None: return 2 + # The new version, in the rows `install` describes a theme with. + for line in _source_rows(plan, facts, found, local_root is None): + print(line) if args.with_sheets is not None: selected = _match_sheets(args.with_sheets, facts) @@ -1950,8 +2024,7 @@ def cmd_upgrade(args): "for none.", file=sys.stderr) return 2 if continuity["kept"]: - print(f" keeping optional sheets: " - f"{', '.join(s.stem for s in continuity['kept'])}") + _rows([("sheets", f"keeping {', '.join(s.stem for s in continuity['kept'])}")]) # Checked against the *new* version's sheets, not the old ones: a # release that splits one option into two, or merges two into one, # can turn a combination that used to work into a pair that @@ -1981,7 +2054,7 @@ def cmd_upgrade(args): file=sys.stderr) return 2 if pref_files: - print(f" keeping preference file(s): {', '.join(pref_files)}") + _rows([("prefs", f"keeping {', '.join(pref_files)}")]) if local_root is not None or setup_requested: # A local source has no upstream to ask; the files themselves are @@ -2063,14 +2136,11 @@ def cmd_upgrade(args): return status print(f" before/after images: {outdir / 'diff'}") - print() _report_checklist(plan["repo_root"], theme_root, plan, pref_files) - if install.firefox_running(picked["path"]): - print("\n note: Firefox appears to be running — the change will " - "only show after a restart.") + _running_note(picked) _report_additions(install.user_additions(picked["path"], manifest)) if not _confirm(f"\n Upgrade to {why}?", interactive, args.yes): - print(" nothing changed.") + print(style.muted(" Nothing changed.")) return 1 if local_root is not None: @@ -2099,8 +2169,8 @@ def cmd_upgrade(args): except install.CollisionError as exc: _report_collision(exc) return 2 - print(f"\n upgraded to {why}") - print(f" the previous version is kept as {result['backup']}") + print() + _rows([("backup", f"the previous version, kept as {result['backup']}")]) _report_preserved(result) keep = args.keep if keep is not None and keep < 1: @@ -2113,10 +2183,11 @@ def cmd_upgrade(args): removed = install.prune_backups( picked["path"], keep, protect=[manifest.get("origin_backup")]) if removed: - print(f" pruned {_pl(len(removed), 'older backup')}, keeping the " - f"newest {keep}") - print("\n Restart Firefox to see it. `fxcss rollback` puts the " - "previous version back.") + _rows([("pruned", f"{_pl(len(removed), 'older backup')}, keeping the " + f"newest {keep}")]) + _done("Upgraded", f"to {why}") + _then("Restart Firefox to see it;", "`fxcss rollback`", + "puts the previous version back.") return 0 except RuntimeError as exc: print(f"\n error: {exc}", file=sys.stderr) @@ -2133,7 +2204,8 @@ def cmd_adopt(args): and not os.environ.get("CI")) picked = _choose_profile(args.profile, interactive, prefer="unmanaged") chrome = Path(picked["path"]) / "chrome" - print(f"\n profile: {picked['name']} ({picked['path']})") + from . import style + _profile_header("adopt", picked) if not (chrome / "userChrome.css").is_file(): print("\n No chrome/userChrome.css here, so there is no theme to " @@ -2164,11 +2236,11 @@ def cmd_adopt(args): " fxcss adopt owner/theme", file=sys.stderr) return 2 owner, name = fetch.parse_repo(found[0]["repo"]) - print(f" looks like {found[0]['repo']} — {found[0]['why']}") + _rows([("looks like", [style.strong(found[0]["repo"]), style.muted(found[0]["why"])])]) if not found[0]["certain"] and not _confirm( - " Check the files against it?", interactive, args.yes): - print(" nothing changed. Pass the repository instead: " - "fxcss adopt owner/theme") + "\n Check the files against it?", interactive, args.yes): + print(style.muted(" Nothing changed. Pass the repository instead: ") + + style.cmd("fxcss adopt owner/theme")) return 1 # Which version? @@ -2237,12 +2309,10 @@ def cmd_adopt(args): if not adopt.exact(best): print(" Recorded as that version plus local differences, so an " "upgrade knows\n not to overwrite them without being told.") - if install.firefox_running(picked["path"]): - print(" note: Firefox appears to be running — nothing here needs a " - "restart.") + _running_note(picked, "nothing here needs a restart") if not _confirm(f"\n Record this profile as {owner}/{name}@{best['ref']}?", interactive, args.yes): - print(" nothing changed.") + print(style.muted(" Nothing changed.")) return 1 kind = {"release": "release", "tag": "release", @@ -2264,11 +2334,15 @@ def cmd_adopt(args): except RuntimeError as exc: print(f" error: {exc}", file=sys.stderr) return 2 - print(f"\n recorded {_pl(len(manifest['files']), 'file')} as " - f"{manifest['theme']}") - print(f" the theme as it is now is kept as {manifest['backup']}") - print("\n `fxcss upgrade` can now update it, and `fxcss uninstall` puts " - "this back.") + print() + pairs = [("backup", f"the theme as it is now, kept as {manifest['backup']}")] + if manifest.get("user_files"): + # Files the matched version does not have: the person's, not the theme's. + pairs.append(("yours", f"{_pl(len(manifest['user_files']), 'file')} that version does " + "not ship, kept as your own across upgrades")) + _rows(pairs) + _done("Recorded", f"{_pl(len(manifest['files']), 'file')} as {manifest['theme']}") + _then("`fxcss upgrade`", "can now update it, and", "`fxcss uninstall`", "puts this back.") return 0 @@ -2280,9 +2354,8 @@ def cmd_rollback(args): picked = _choose_profile(args.profile, interactive, prefer="managed") backups = install.list_backups(picked["path"]) manifest = install.read_manifest(picked["path"]) - print(f"\n profile: {picked['name']} ({picked['path']})") - if manifest: - print(f" installed: {_theme_label(manifest)}") + from . import style + _profile_header("rollback", picked, manifest) if not backups: print("\n No backups here to roll back to. `fxcss install` and " @@ -2292,13 +2365,15 @@ def cmd_rollback(args): origin = (manifest or {}).get("origin_backup") if args.list: - print("\n Backups, newest first:\n") + print() + print(style.heading_line("Backups", "newest first")) for backup in backups: what = backup["theme"] or "your own chrome/, from before fxcss" - tag = " (the original)" if backup["name"] == origin else "" - print(f" {backup['name']}{tag}") - print(f" {what}") - print("\n `fxcss rollback --to ` restores one of these.") + tag = f" {style.brand('the original')}" if backup["name"] == origin else "" + print(f" {style.strong(backup['name'])}{tag}") + print(f" {style.muted(what)}") + print() + _then("`fxcss rollback --to `", "restores one of these.") return 0 target = args.to or backups[0]["name"] @@ -2309,15 +2384,12 @@ def cmd_rollback(args): return 2 what = chosen["theme"] or "your own chrome/, from before fxcss ran here" - print(f"\n rolling back to {chosen['name']}\n {what}") - if chosen["manifest"] is None: - print(" that has no fxcss theme in it, so the user.js block goes " - "too") - if install.firefox_running(picked["path"]): - print(" note: Firefox appears to be running — the change will only " - "show after a restart.") - if not _confirm(" Roll back to this?", interactive, args.yes): - print(" nothing changed.") + _rows([("back to", [style.strong(chosen["name"]), style.muted(what)]), + ("user.js", "that has no fxcss theme in it, so the fxcss block goes too" + if chosen["manifest"] is None else None)]) + _running_note(picked) + if not _confirm("\n Roll back to this?", interactive, args.yes): + print(style.muted(" Nothing changed.")) return 1 try: @@ -2325,18 +2397,15 @@ def cmd_rollback(args): except RuntimeError as exc: print(f" error: {exc}", file=sys.stderr) return 2 - print(f"\n restored {summary['restored']}") - if summary["moved_aside"]: - print(f" what was installed is kept as {summary['moved_aside']}, so " - "this is undoable") - if summary["user_js"] == "restored": - print(" user.js: put that version's prefs back") - elif summary["user_js"] == "removed": - print(" user.js: removed the fxcss block") - elif summary["user_js"] == "unknown": - print(" user.js: left as it is — that version did not record its " - "prefs") - print("\n Restart Firefox to see the change.") + print() + _rows([("backup", f"what was installed, kept as {summary['moved_aside']}, so this " + "can be undone" if summary["moved_aside"] else None), + ("user.js", {"restored": "put that version's prefs back", + "removed": "removed the fxcss block", + "unknown": "left as it is; that version did not record its prefs", + }.get(summary["user_js"]))]) + _done("Rolled back", f"to {summary['restored']}") + _then("Restart Firefox to see the change.") return 0 @@ -2411,6 +2480,19 @@ def cmd_tweaks(args): +def _from_package_index(): + """Whether this fxcss was installed from a package index, by version. + + pip records where anything else came from (a checkout, a URL, a commit) + in direct_url.json; a release installed by name has no such file. + """ + try: + from importlib import metadata + return metadata.distribution("fxcss").read_text("direct_url.json") is None + except Exception: + return False + + def cmd_init(args): from . import layout, scaffold theme = args.theme.resolve() @@ -2446,20 +2528,33 @@ def cmd_init(args): except ValueError as exc: print(f"error: {exc}", file=sys.stderr) return 2 + from . import style + print(style.title("init", style.short_path(theme))) + print() + pairs = [] for line in layout.describe_plan(plan): - print(f" {line}") + label, _, text = line.partition(": ") + pairs.append((label, text) if text else ("note", line)) if repo_root.resolve() != theme_dir.resolve(): try: rel = theme_dir.resolve().relative_to(repo_root.resolve()).as_posix() except ValueError: rel = str(theme_dir) - print(f" workflows go to {repo_root / '.github' / 'workflows'} and point at {rel}/") + pairs.append(("workflows", f"go to {style.short_path(repo_root / '.github' / 'workflows')} " + f"and point at {rel}/")) toolkit_ref = getattr(args, "toolkit_ref", None) if toolkit_ref: - print(f" workflows install fxcss from commit {toolkit_ref}") + pairs.append(("fxcss", f"workflows install fxcss from commit {toolkit_ref}")) + elif _from_package_index(): + pairs.append(("fxcss", f"workflows pin fxcss {__version__}")) else: - print(f" workflows pin fxcss {__version__}; that version must be published on PyPI " - "before they run. Use --toolkit-ref to test an unreleased commit.") + # Only a copy that did not come from PyPI can be ahead of it. + pairs.append(("fxcss", f"workflows pin fxcss {__version__}, and this copy was not " + "installed from PyPI: that version must be published on PyPI " + "before they run. Use --toolkit-ref to test an " + "unreleased commit.")) + for line in style.rows(pairs, indent=2): + print(line) try: written, skipped = scaffold.write_workflows( theme_dir, slugs, watch=args.watch, showcase=args.showcase, @@ -2468,8 +2563,19 @@ def cmd_init(args): except ValueError as exc: print(f"error: {exc}", file=sys.stderr) return 2 - print(scaffold.next_steps(written, skipped, slugs, args.watch, args.showcase, - args.previews)) + # next_steps is written flush left, as a block of its own; here it sits + # under the title like every other command's output, headings in bold. + print() + for line in scaffold.next_steps(written, skipped, slugs, args.watch, args.showcase, + args.previews).splitlines(): + if line.endswith(":") and not line.startswith(" "): + head, _, note = line[:-1].partition(" (") + print(style.heading_line(head, note.rstrip(")") or None)) + elif line.startswith(" "): + print(f" {line}") + else: + for part in style.wrap(line, indent=2) if line else [""]: + print(part) return 0 def _fit_names(names, width): @@ -2907,12 +3013,26 @@ def cmd_catalogue(args): def cmd_doctor(args): - from . import style + import tempfile + from . import inventory, style theme = args.theme.resolve() firefox = choose_firefox(args.firefox) print(style.title("doctor", style.short_path(theme))) - with core.Session(theme, firefox, devtools=True) as session: - info = session.info() + # No theme here is not a reason to stop: the installer and the docs send + # people to `doctor` first, before they have one, and what it says about + # Firefox holds either way. A blank stylesheet stands in for the session. + no_theme = getattr(args, "theme_problem", None) + if not no_theme and not any((theme / "chrome" / name).is_file() + for name in inventory.ENTRY_SHEETS): + no_theme = "no chrome/userChrome.css in this folder" + with tempfile.TemporaryDirectory(prefix="fxcss-doctor-") as blank: + root = theme + if no_theme: + root = Path(blank) + (root / "chrome").mkdir() + (root / "chrome" / "userChrome.css").write_text("", encoding="utf-8") + with core.Session(root, firefox, devtools=True) as session: + info = session.info() sheets = sorted((theme / "chrome").rglob("*.css")) if (theme / "chrome").exists() else [] total = sum(p.stat().st_size for p in sheets) @@ -2929,7 +3049,8 @@ def cmd_doctor(args): # The builds table below names the binary in use; say it here # only when that table will not. ("binary", None if listed else style.short_path(firefox)), - ("theme", f"{style.plural(len(sheets), 'stylesheet')}, {total / 1024:,.0f} KB"), + ("theme", style.muted("none in this folder") if no_theme else + f"{style.plural(len(sheets), 'stylesheet')}, {_size(total)}"), ("window", f"{width} × {height}{scale}" if height else str(info["outer"])), ]): print(line) @@ -2952,7 +3073,11 @@ def report(state, text, detail=None, short=None): report("bad", "userChrome.css loading is off", "set toolkit.legacyUserProfileCustomizations.stylesheets to true") missing = [p for p in ("chrome/userChrome.css",) if not (theme / p).exists()] - if missing: + if no_theme: + report("info", "No theme in this folder, so this is about Firefox alone", + f"{no_theme}; run this from a theme's root folder, the one holding " + "chrome/, or pass --theme, to check a theme as well") + elif missing: report("bad", f"{', '.join(missing)} is missing", "run this from a theme's root folder, the one holding chrome/, or pass --theme") else: @@ -2996,7 +3121,7 @@ def report(state, text, detail=None, short=None): f"{style.muted(style.plural(findings['warn'], 'thing') + ' to know: ' + ', '.join(named))}") else: print(f" {style.good(style.TICK)} {style.strong('Ready to theme')}") - if missing: + if no_theme or missing: print(f" {style.muted('New here?')} {style.cmd('fxcss try owner/repo')} " f"{style.muted('test-drives a theme;')} {style.cmd('fxcss new')} " f"{style.muted('starts one.')}") @@ -3004,6 +3129,11 @@ def report(state, text, detail=None, short=None): return 0 +def _size(count): + """A size in KB, without calling a small theme `0 KB`.""" + return "under 1 KB" if 0 < count < 1024 else f"{count // 1024:,} KB" + + def _bool(v): return v.lower() not in ("false", "0", "no") @@ -3443,7 +3573,14 @@ def build_parser(): def _resolve_layouts(args): from . import layout if getattr(args, "cmd", None) in LAYOUT_AWARE and getattr(args, "theme", None): - if args.cmd == "audit" and args.patch: + if args.cmd == "doctor": + # doctor reports a folder it cannot read as a theme; it does not + # stop at it. See cmd_doctor. + try: + args.theme = layout.standard_root(args.theme) + except layout.LayoutError as exc: + args.theme_problem = str(exc) + elif args.cmd == "audit" and args.patch: args.theme, args._layout_plan = layout.standard_root(args.theme, with_plan=True) layout.patch_source_paths(args._layout_plan, args.theme, []) else: @@ -3456,6 +3593,8 @@ def _resolve_layouts(args): def main(argv=None): + from . import style + style.tolerant_output() raw = list(sys.argv[1:] if argv is None else argv) if raw and raw[0] == "__complete": return _complete_entry(raw[1:]) diff --git a/fxcss/probe.py b/fxcss/probe.py index 28bbe79..aabff8b 100644 --- a/fxcss/probe.py +++ b/fxcss/probe.py @@ -188,7 +188,7 @@ def inspect_selector(session, selector, repo, references): if not count: print(f"no elements match {selector!r} in this Firefox") return 1 - print(f"{count} element{'s' if count != 1 else ''} match {selector!r}" + print(f"{count} element{'s match' if count != 1 else ' matches'} {selector!r}" + (" (showing first 8)" if count > 8 else "")) for info in result["matches"]: _print_element(info, repo, references) diff --git a/fxcss/prompt.py b/fxcss/prompt.py index c410e98..ab8a4e6 100644 --- a/fxcss/prompt.py +++ b/fxcss/prompt.py @@ -159,36 +159,56 @@ def keys(): def _windows_vt(): # pragma: no cover - needs a Windows console """Let a Windows console act on the cursor codes the redraw uses.""" - try: - import ctypes - kernel32 = ctypes.windll.kernel32 - handle = kernel32.GetStdHandle(-11) - mode = ctypes.c_uint32() - if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)): - return False - return bool(kernel32.SetConsoleMode(handle, mode.value | 0x0004)) - except (AttributeError, OSError): - return False + return style.windows_vt() def keypresses(): return _windows_keys() if os.name == "nt" else _posix_keys() +def _cells(text): + """How many terminal columns `text` takes, colour codes aside.""" + import unicodedata + return sum(0 if unicodedata.combining(ch) else + 2 if unicodedata.east_asian_width(ch) in "WF" else 1 + for ch in style._visible(text)) + + class Frame: """The menu's own lines at the foot of the terminal, redrawn in place.""" - def __init__(self, out=None): + def __init__(self, out=None, columns=None): self.out = out or sys.stdout + self.columns = columns self.height = 0 + self.wrapped = False + + def _columns(self): + if self.columns: + return self.columns + try: + return os.get_terminal_size(self.out.fileno()).columns + except (AttributeError, ValueError, OSError): + return 0 def draw(self, lines, final=False): rows = "\n".join(lines).split("\n") + # A row wider than the terminal takes two of its lines or more, and + # the way back to the top is counted in the terminal's lines. The + # prompt gets there as soon as enough is typed after it. + columns = self._columns() + taken = [max(1, -(-_cells(r) // columns)) if columns else 1 for r in rows] + wrapped = max(taken) > 1 up = f"\033[{self.height - 1}A" if self.height > 1 else "" - text = ("\r" + up if self.height else "") + "\n".join(f"\033[2K{r}" for r in rows) + home = "\r" + up if self.height else "" + if wrapped or self.wrapped: + # Erasing line by line misses what a wrapped row left behind. + home += "\033[J" + text = home + "\n".join(f"\033[2K{r}" for r in rows) self.out.write(text + "\033[J" + ("\n" if final else "")) self.out.flush() - self.height = len(rows) + self.height = sum(taken) + self.wrapped = wrapped def _cancel(frame): diff --git a/fxcss/style.py b/fxcss/style.py index 74f5cad..f5b56cc 100644 --- a/fxcss/style.py +++ b/fxcss/style.py @@ -78,9 +78,70 @@ def colour_on(stream=None): return True stream = stream or sys.stdout try: - return bool(stream.isatty()) + if not stream.isatty(): + return False except (AttributeError, ValueError): return False + # An older Windows console prints the codes as text until it is told to + # act on them, and one that cannot be told gets none. + return windows_vt(stream) if os.name == "nt" else True + + +_vt = {} + + +def windows_vt(stream=None): # pragma: no cover - needs a Windows console + """Let a Windows console act on colour and cursor codes; False if it will not.""" + handle_id = -12 if stream is sys.stderr else -11 + if handle_id not in _vt: + try: + import ctypes + kernel32 = ctypes.windll.kernel32 + handle = kernel32.GetStdHandle(handle_id) + mode = ctypes.c_uint32() + _vt[handle_id] = bool( + kernel32.GetConsoleMode(handle, ctypes.byref(mode)) + and kernel32.SetConsoleMode(handle, mode.value | 0x0004)) + except (AttributeError, OSError): + _vt[handle_id] = False + return _vt[handle_id] + + +# What a console that cannot show a character gets in its place. Report text +# is written once, for every terminal; only the last step knows the encoding. +_STAND_INS = {"→": "->", "←": "<-", "↑": "^", "↓": "v", "…": "...", "—": "-", "–": "-", + "·": "-", "●": "*", "✓": "ok", "✗": "x", "›": ">", "█": "#", + "‘": "'", "’": "'", "“": '"', "”": '"', "\u00a0": " "} + + +def _stand_in(error): + if not isinstance(error, UnicodeEncodeError): + raise error + text = error.object[error.start:error.end] + return "".join(_STAND_INS.get(ch, "?") for ch in text), error.end + + +def tolerant_output(streams=None): + """Never let a character the console cannot encode stop a command. + + Piped output on Windows is written in the system code page, which has no + arrow, tick or bullet. Printing one raised UnicodeEncodeError halfway + through a report. Give those streams the nearest ASCII instead; a stream + someone has already set an error mode for is left as they set it. + """ + import codecs + codecs.register_error("fxcss-stand-in", _stand_in) + for stream in streams or (sys.stdout, sys.stderr): + encoding = (getattr(stream, "encoding", None) or "").lower() + # stderr starts out on backslashreplace, which never raises but + # prints `\u2192` in the middle of a sentence. + default = "backslashreplace" if stream is sys.stderr else "strict" + if "utf" in encoding or getattr(stream, "errors", None) != default: + continue + try: + stream.reconfigure(errors="fxcss-stand-in") + except (AttributeError, ValueError, OSError): + pass def colour_depth(): diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index 7ebbbb7..86cee9b 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -50,7 +50,7 @@ def _stamps(): def run_cli(*argv): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \ - mock.patch.dict(os.environ, {"CI": "1"}): + mock.patch.dict(os.environ, {"CI": "1", "NO_COLOR": "1"}): code = cli.main(list(argv)) return code, out.getvalue(), err.getvalue() @@ -115,7 +115,7 @@ def test_install_twice_then_three_upgrades_from_the_command_line(self): _write(self.theme, {"chrome/userChrome.css": f"#nav-bar {{ order: {number} }}\n"}) code, out, err = run_cli("upgrade", "--profile", str(self.profile), "--yes") self.assertEqual(code, 0, err) - self.assertIn("pruned 1 older backup", out) + self.assertIn("pruned 1 older backup", " ".join(out.split())) self.assertEqual(len(self.original_copies()), 1) code, out, err = run_cli("uninstall", "--profile", str(self.profile), "--yes") self.assertEqual(code, 0, err) @@ -381,7 +381,7 @@ def test_a_bare_upgrade_of_a_pinned_install_changes_nothing(self): code, out, err = run_cli("upgrade", "--profile", str(self.profile), "--yes") self.assertEqual(code, 0, err) self.assertIn(f"Pinned to {ref} with --ref", out) - self.assertNotIn("upgraded to", out) + self.assertNotIn("Upgraded", out) self.assertEqual(self.downloaded, [ref]) self.assertEqual(_tree(self.profile), before) code, _, _ = run_cli("uninstall", "--profile", str(self.profile), "--yes") diff --git a/tests/test_maintenance_cli.py b/tests/test_maintenance_cli.py index 3c2cf6d..bbcbc1f 100644 --- a/tests/test_maintenance_cli.py +++ b/tests/test_maintenance_cli.py @@ -34,7 +34,9 @@ def _write(root, files): def run_cli(*argv): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \ - mock.patch.dict(os.environ, {"CI": "1"}): + mock.patch.dict(os.environ, {"CI": "1", "NO_COLOR": "1"}): + # NO_COLOR: these tests read the words, and FORCE_COLOR in the + # environment would otherwise put codes between them. code = cli.main(list(argv)) return code, out.getvalue(), err.getvalue() @@ -91,8 +93,8 @@ def test_install_upgrade_and_uninstall_a_flat_repository(self): code, out, err = run_cli("upgrade", "--profile", str(self.profile), "--yes") self.assertEqual(code, 0, err) self.assertTrue((chrome / "tweaks" / "mine.css").is_file()) - self.assertIn("keeping optional sheets: hide-tabs", out) - self.assertIn("keeping preference file(s): user.js", out) + self.assertIn("sheets keeping hide-tabs", out) + self.assertIn("prefs keeping user.js", out) manifest = install.read_manifest(self.profile) self.assertEqual(manifest["user_files"], ["chrome/tweaks/mine.css"]) self.assertEqual((chrome / "theme" / "base.css").read_text(), ":root { --v: 2 }\n") @@ -459,12 +461,26 @@ def test_nested_theme_gets_workflows_at_the_repository_root(self): def test_flat_theme_previews_cover_all_repository_dependencies(self): with tempfile.TemporaryDirectory() as td: repo = _write(Path(td) / "repo", {"userChrome.css": "#a { }\n"}) - code, out, err = run_cli("init", "--theme", str(repo), "--previews") + with mock.patch.object(cli, "_from_package_index", return_value=False): + code, out, err = run_cli("init", "--theme", str(repo), "--previews") self.assertEqual(code, 0, err) text = (repo / ".github" / "workflows" / "pr-preview.yml").read_text() self.assert_preview_triggers_cover_all_dependencies(repo / ".github" / "workflows") self.assertIn("--theme head ", text) - self.assertIn("must be published on PyPI", out) + # The sentence wraps to the terminal; read it as one line. + self.assertIn("must be published on PyPI", " ".join(out.split())) + + def test_a_released_fxcss_does_not_warn_that_it_is_unpublished(self): + # The warning is for a checkout ahead of PyPI. Printed after every + # `init`, it told people on a release that their pin might not install. + with tempfile.TemporaryDirectory() as td: + repo = _write(Path(td) / "repo", {"userChrome.css": "#a { }\n"}) + with mock.patch.object(cli, "_from_package_index", return_value=True): + code, out, err = run_cli("init", "--theme", str(repo), "--previews") + self.assertEqual(code, 0, err) + self.assertIn(f"workflows pin fxcss {cli.__version__}\n", out) + self.assertNotIn("published on PyPI", out) + self.assertNotIn("--toolkit-ref", out) def test_several_editions_need_a_subpath(self): with tempfile.TemporaryDirectory() as td: diff --git a/tests/test_prompt.py b/tests/test_prompt.py index d7250c5..09ca86a 100644 --- a/tests/test_prompt.py +++ b/tests/test_prompt.py @@ -319,5 +319,95 @@ def interrupted(args): self.assertIn("Stopped.", err.getvalue()) +class Terminal: + """Just enough of a terminal to see what a redraw leaves on screen.""" + + def __init__(self, columns): + self.columns = columns + self.lines, self.row, self.col = [[]], 0, 0 + + def write(self, text): + for code, char in re.findall(r"\033\[([0-9;]*[A-Za-z])|([\s\S])", text): + if code: + self.control(code) + elif char == "\r": + self.col = 0 + elif char == "\n": # the terminal driver adds the return + self.row, self.col = self.row + 1, 0 + while len(self.lines) <= self.row: + self.lines.append([]) + else: + if self.col == self.columns: # the wrap waits for the next character + self.write("\n") + line = self.lines[self.row] + line.extend(" " * (self.col + 1 - len(line))) + line[self.col] = char + self.col += 1 + + def control(self, code): + if code.endswith("A"): + self.row = max(0, self.row - int(code[:-1] or 1)) + self.col = min(self.col, self.columns - 1) + elif code == "2K": + self.lines[self.row] = [] + elif code == "J": + del self.lines[self.row][self.col:] + del self.lines[self.row + 1:] + + def flush(self): + pass + + def shown(self): + return ["".join(line).rstrip() for line in self.lines] + + +class WrappedFrameTests(unittest.TestCase): + """A row wider than the terminal takes two of its lines. + + The stylesheet prompt is 67 columns before anything is typed after it, + so it wraps in a narrow terminal straight away and in an 80-column one + a dozen characters in. Going back up by the count of rows, not of + terminal lines, left the top of every earlier frame on screen. + """ + + def redraw(self, columns, *frames): + terminal = Terminal(columns) + frame = prompt.Frame(terminal, columns=columns) + for lines in frames: + frame.draw(lines) + return terminal.shown() + + def test_a_wrapped_prompt_is_redrawn_where_it_was(self): + long = "Which? " + "x" * 30 + self.assertEqual(self.redraw(20, ["one", "two", long], ["ONE", "TWO", long + "y"]), + ["ONE", "TWO", (long + "y")[:20], (long + "y")[20:]]) + + def test_a_prompt_that_stops_wrapping_leaves_nothing_behind(self): + long = "Which? " + "x" * 30 + self.assertEqual(self.redraw(20, ["one", long], ["one", "Which? "], ["one", "Which? 2"]), + ["one", "Which? 2"]) + + def test_a_row_exactly_as_wide_as_the_terminal_is_one_line(self): + full = "x" * 20 + self.assertEqual(self.redraw(20, [full, "ask"], [full, "ask 1"]), [full, "ask 1"]) + + def test_colour_codes_and_wide_characters_are_measured_as_shown(self): + coloured = style.sgr("x" * 18, "bold", on=True) + self.assertEqual(self.redraw(20, [coloured, "ask"], ["plain", "ask"]), ["plain", "ask"]) + wide = "\u4e3b\u9898" * 6 # twelve characters, 24 columns + self.assertEqual(prompt._cells(wide), 24) + frame = prompt.Frame(io.StringIO(), columns=20) + frame.draw([wide, "ask"]) + self.assertEqual(frame.height, 3) + + def test_a_stand_in_for_the_terminal_is_never_measured(self): + out = io.StringIO() + frame = prompt.Frame(out) + frame.draw(["x" * 500, "ask"]) + frame.draw(["x" * 500, "ask"]) + self.assertEqual(frame.height, 2) + self.assertIn("\033[1A", out.getvalue()) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_terminal_style.py b/tests/test_terminal_style.py index 3c8b6da..2ec84c6 100644 --- a/tests/test_terminal_style.py +++ b/tests/test_terminal_style.py @@ -101,6 +101,43 @@ def test_no_colour_does_not_outlive_the_audit(self): unittest.main() +class LegacyConsoleTests(unittest.TestCase): + """Output piped on Windows is written in a code page with no arrow in it. + + `fxcss try --info` on a theme with an unresolved @import printed + `a.css → b.css` and stopped there with a UnicodeEncodeError. + """ + + def piped(self, encoding, errors="strict"): + import io + raw = io.BytesIO() + return raw, io.TextIOWrapper(raw, encoding=encoding, errors=errors) + + def test_what_the_code_page_lacks_gets_an_ascii_stand_in(self): + raw, out = self.piped("cp1252") + style.tolerant_output([out]) + out.write("a.css → b.css ✓ ● … \u4e3b") + out.flush() + self.assertEqual(raw.getvalue().decode("cp1252"), "a.css -> b.css ok * … ?") + + def test_utf8_is_left_alone(self): + raw, out = self.piped("utf-8") + style.tolerant_output([out]) + self.assertEqual(out.errors, "strict") + out.write("a → b") + out.flush() + self.assertEqual(raw.getvalue().decode("utf-8"), "a → b") + + def test_an_error_mode_someone_chose_is_kept(self): + _, out = self.piped("cp1252", errors="backslashreplace") + style.tolerant_output([out]) + self.assertEqual(out.errors, "backslashreplace") + + def test_a_stand_in_for_the_stream_is_ignored(self): + import io + style.tolerant_output([io.StringIO(), object()]) + + class ClipTests(unittest.TestCase): def test_prose_keeps_its_start_and_breaks_between_words(self): self.assertEqual(style.clip("newer than the release — fix tabs", 24), "newer than the release…") diff --git a/tests/test_units.py b/tests/test_units.py index 456e91a..cf8a8ea 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -473,6 +473,8 @@ def test_backticked_flag_keeps_its_argument(self): def test_try_info_aligns_flags_with_arguments(self): import contextlib import io + import os + from unittest import mock from fxcss import cli with tempfile.TemporaryDirectory() as td: (Path(td) / "chrome").mkdir() @@ -481,7 +483,8 @@ def test_try_info_aligns_flags_with_arguments(self): "- `-c` Left hand side tab close button\n" "- `-t ` Colour theme (see Colour themes below)\n") buffer = io.StringIO() - with contextlib.redirect_stdout(buffer): + with contextlib.redirect_stdout(buffer), \ + mock.patch.dict(os.environ, {"NO_COLOR": "1"}): code = cli.main(["try", td, "--info"]) out = buffer.getvalue() self.assertEqual(code, 0) @@ -4219,6 +4222,52 @@ def test_report_names_the_section_and_the_rename(self): self.assertIn("only DevTools declares it", text) +class UnusedReportWordingTests(unittest.TestCase): + """The closing section of the audit, when there is little to put in it.""" + + EMPTY = {"orphans": [], "unused_properties": [], "stale_overrides": [], + "devtools_only": [], "missing_properties": []} + + def report(self, **found): + import contextlib + import io + from fxcss import audit + out = io.StringIO() + with contextlib.redirect_stdout(out): + audit.report_unused(dict(self.EMPTY, **found), colour=False, context=[]) + return out.getvalue() + + MISSING = [{"name": "--gone", "file": "chrome/userChrome.css", "line": 4}] + + def test_no_heading_over_nothing(self): + text = self.report(missing_properties=self.MISSING) + self.assertIn("UNDEFINED", text) + self.assertNotIn("Unused and unreachable", text) + + def test_the_heading_stays_over_a_finding(self): + text = self.report(missing_properties=self.MISSING, orphans=["chrome/old.css"]) + self.assertLess(text.index("Unused and unreachable"), text.index("NOT IMPORTED")) + + def test_the_heading_stays_over_the_all_clear(self): + text = self.report() + self.assertLess(text.index("Unused and unreachable"), text.index("Nothing unused found.")) + + def test_one_of_a_thing_is_singular(self): + import contextlib + import io + from fxcss import audit + rows = [{"count": 1, "kind": "token", "text": "x"}, + {"count": 1, "kind": "property", "text": "y"}, + {"count": 2, "kind": "file", "text": "z"}] + out = io.StringIO() + with contextlib.redirect_stdout(out): + audit.print_context(rows, False, False) + text = " ".join(out.getvalue().split()) # it wraps in a narrow terminal + self.assertIn("1 token out of reach", text) + self.assertIn("1 property skipped", text) + self.assertIn("2 files left out", text) + + class KeepPragmaTests(unittest.TestCase): """`/* fxcss-keep */` on a declaration line exempts that property. @@ -4454,6 +4503,30 @@ def test_a_local_theme_has_nothing_to_check(self): self.assertNotIn("Pass --check", text) +class ConfirmPromptTests(unittest.TestCase): + """A yes/no question sits at the indent of the lines above it. + + The upgrade and adopt questions open with a blank line, and the newline + was counted as indent: they sat one column to the right of everything. + """ + + def asked(self, question): + from unittest import mock + from fxcss import cli, style + style.set_colour(False) + self.addCleanup(style.set_colour, None) + with mock.patch("builtins.input", return_value="") as prompt: + self.assertTrue(cli._confirm(question, True, False)) + return prompt.call_args[0][0] + + def test_a_leading_blank_line_is_not_indent(self): + self.assertEqual(self.asked("\n Upgrade to v2?"), "\n Upgrade to v2? [Y/n] ") + + def test_the_indent_given_is_the_indent_used(self): + self.assertEqual(self.asked(" Roll back to this?"), " Roll back to this? [Y/n] ") + self.assertEqual(self.asked(" Deeper?"), " Deeper? [Y/n] ") + + class SubcommandUsageTests(unittest.TestCase): """Every subcommand introduces itself as `fxcss `. @@ -4477,9 +4550,13 @@ def test_each_one_is_named_after_the_program_and_itself(self): def test_an_error_says_which_command_it_came_from(self): import contextlib import io + import os + from unittest import mock from fxcss import cli err = io.StringIO() - with self.assertRaises(SystemExit), contextlib.redirect_stderr(err): + # NO_COLOR: from Python 3.14 argparse colours its own usage line. + with self.assertRaises(SystemExit), contextlib.redirect_stderr(err), \ + mock.patch.dict(os.environ, {"NO_COLOR": "1"}): cli.build_parser().parse_args(["new"]) self.assertIn("usage: fxcss new ", err.getvalue()) self.assertIn("fxcss new: error:", err.getvalue()) diff --git a/tests/test_welcome_context.py b/tests/test_welcome_context.py index ad7cd0a..22da7b2 100644 --- a/tests/test_welcome_context.py +++ b/tests/test_welcome_context.py @@ -192,6 +192,69 @@ def test_the_firefox_row_carries_the_symbol(self): self.assertIn("155.0.1 on ⌘ macOS", style._visible(out.getvalue())) +class DoctorWithoutAThemeTests(unittest.TestCase): + """`fxcss doctor` is the first thing the installer says to run. + + Run before there is a theme, it stopped with "no userChrome.css or + userContent.css anywhere" and said nothing about Firefox at all. + """ + + INFO = {"version": "158.0", "os": "Darwin", "buildID": "20261007", + "outer": [1280, 480], "dpr": 1, "legacyStylesheets": True, + "nativeContextMenus": {}} + + def doctor(self, files=()): + session = mock.MagicMock() + session.__enter__.return_value.info.return_value = self.INFO + seen = {} + + def opened(root, firefox, **kwargs): + seen["root"] = Path(root) + seen["sheet"] = (Path(root) / "chrome" / "userChrome.css").is_file() + return session + + out = io.StringIO() + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch("fxcss.cli.choose_firefox", return_value="/x/firefox"), \ + mock.patch("fxcss.cli.core.Session", side_effect=opened), \ + mock.patch("fxcss.cli.core.discover_firefoxes", return_value=[]), \ + mock.patch.dict("os.environ", {"NO_COLOR": "1"}), \ + contextlib.redirect_stdout(out): + for name in files: + target = Path(tmp) / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("#nav-bar { }\n") + code = cli.main(["doctor", "--theme", tmp]) + seen["own"] = seen["root"].resolve() == Path(tmp).resolve() + return code, out.getvalue(), seen + + def test_an_empty_folder_still_gets_the_firefox_checks(self): + code, text, seen = self.doctor() + self.assertEqual(code, 0) + self.assertIn("theme none in this folder", text) + self.assertIn("userChrome.css loading is enabled", text) + self.assertIn("No theme in this folder", text) + self.assertIn("Ready to theme", text) + self.assertIn("New here?", text) + self.assertNotIn("to fix", text) + # The session ran on a blank stand-in, not on the folder. + self.assertTrue(seen["sheet"]) + self.assertFalse(seen["own"]) + + def test_loose_stylesheets_that_are_not_a_theme_are_reported_not_fatal(self): + code, text, _ = self.doctor(["notes/tabs.css"]) + self.assertEqual(code, 0) + self.assertIn("No theme in this folder", text) + + def test_a_theme_is_checked_as_before(self): + code, text, seen = self.doctor(["chrome/userChrome.css"]) + self.assertEqual(code, 0) + self.assertIn("theme 1 stylesheet, under 1 KB", text) + self.assertIn("chrome/userChrome.css is in place", text) + self.assertNotIn("New here?", text) + self.assertTrue(seen["own"]) + + class BuildIdentityTests(unittest.TestCase): def build(self, *folders, body="[App]\nName=Firefox\nVersion=155.0.1\n"): tmp = tempfile.TemporaryDirectory()