Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

Merge PR #248: tools record the state a debloat list changes, so restore replays it

Gathin2366284088afdc
diff --cc README.md
index f3701deb0,63ebb25c1..9631b8a37
--- a/README.md
+++ b/README.md
@@@ -257,14 -258,24 +258,27 @@@ the install script finds `~/Android/Sdk
## Restoring your TV
- Keep the list you applied. The restore script re-enables exactly those packages, puts the stock
- launcher back as Home and resets the animation scales:
+ Before `tools/disable.sh` changes anything it writes down what the TV looked like: for every package
+ in the list whether it was enabled, already disabled or not installed, which component owned Home,
+ and the three animation scales. That record lives in `~/.cleanyourtv/`, one file per TV and list, and
+ a second run of the same list keeps the first record instead of saving the cleaned-up state over it.
++If you added packages to the list since, that run adds them to the record before disabling them.
+
+ Keep the list you applied. The restore script replays the record, so a package you had disabled
+ yourself stays disabled and Home goes back to the component that owned it:
```bash
TV_HOST=192.168.1.50 tools/restore.sh examples/<your tv>/debloat.txt # Android TV
TV_HOST=192.168.1.50 tools/restore.sh examples/<your tv>/debloat.txt com.google.android.apps.tv.launcherx # Google TV
```
+ The `stock launcher` argument is only a fallback: with a record, the launcher that actually owned Home
-is the one that gets it back, and the argument is used only when nothing answered HOME at the time.
++is the one that gets it back, and the argument is used only when nothing answered HOME at the time
++or this project's launcher owned it. The stock launcher is enabled again either way, unless it was
++already disabled when the record was taken.
+ Without a record (an older run, or a record you deleted) the script says so and falls back to
+ enabling the whole list and resetting the scales to `1.0`, which is what it used to do.
+
It leaves the new launcher installed (remove it from the TV's Settings → Apps if you want it gone)
and does not know about packages you disabled outside the list. To switch back later, run the
install script again; it works out which launcher to disable even when Home has fallen back to
diff --cc tests/test_recovery_record.py
index 000000000,fa268ae7e..882d58bde
mode 000000,100644..100644
--- a/tests/test_recovery_record.py
+++ b/tests/test_recovery_record.py
@@@ -1,0 -1,274 +1,353 @@@
+ """Run tools/recovery.py and the shell that calls it against a simulated TV (#239).
+
+ The property worth testing is the one no TV reproduces on demand: what undo does to a package the
+ owner had already disabled before cleanup, and whether the record survives a retry. tools/tv.py is
+ replaced by a fake that answers the queries from a JSON file, so the real recovery.py logic runs and
+ only the ADB transport is simulated.
+
+ Run from the repository root: python3 -m unittest discover -s tests -v
+ """
+ import json
+ import os
+ from pathlib import Path
+ import shutil
+ import subprocess
+ import sys
+ import tempfile
+ import unittest
+
+
+ ROOT = Path(__file__).resolve().parents[1]
+ STOCK_HOME = "com.google.android.tvlauncher/.MainActivity"
+
+ # Stands in for tools/tv.py: answers the queries recovery.py makes, and records what a batch sends.
+ FAKE_TV = r'''
+ import json
+ import os
+ import sys
+
+ STATE_PATH = os.environ["FAKE_TV_STATE"]
+
+
+ def load():
+ with open(STATE_PATH) as f:
+ return json.load(f)
+
+
+ state = load()
+
+
+ def save():
+ with open(STATE_PATH, "w") as f:
+ json.dump(state, f)
+
+
+ def answer(command):
+ if command == "pm list packages":
+ return "".join(f"package:{name}\n" for name in state["installed"])
+ if command == "pm list packages -d":
+ return "".join(f"package:{name}\n" for name in state["disabled"])
+ if "resolve-activity" in command:
+ return (state["home"] or "") + "\n"
+ if command.startswith("settings get global "):
+ key = command.split()[-1]
+ return str(state["settings"].get(key, "null")) + "\n"
+ return ""
+
+
+ class Device:
+ def shell(self, command, read_timeout_s=None):
+ return answer(command)
+
+ def close(self):
+ pass
+
+
+ def connect():
+ if state.get("unreachable"):
+ raise ConnectionError("could not connect to 192.168.1.50:5555")
+ return Device()
+
+
+ def main():
+ args = sys.argv[1:]
+ if "--batch" in args:
+ for line in sys.stdin:
+ line = line.strip()
+ if line and not line.startswith("#"):
+ state["commands"].append(line)
+ save()
+ return 0
+
+
+ if __name__ == "__main__":
+ sys.exit(main())
+ '''
+
+
+ class RecoveryRecordTest(unittest.TestCase):
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.base = Path(tmp.name)
+ self.repo = self.base / "repo"
+ tools = self.repo / "tools"
+ tools.mkdir(parents=True)
+ for name in ("disable.sh", "restore.sh", "recovery.py"):
+ shutil.copy2(ROOT / "tools" / name, tools / name)
+ (tools / "tv.py").write_text(FAKE_TV)
+ # The scripts call tools/venv/bin/python; run the real interpreter, which imports the fake
+ # tv.py for the transport and the real recovery.py for the logic.
+ client = tools / "venv" / "bin" / "python"
+ client.parent.mkdir(parents=True)
+ client.write_text(f'#!/bin/sh\nexec "{sys.executable}" "$@"\n')
+ client.chmod(0o755)
+
+ self.home = self.base / "home"
+ self.home.mkdir()
+ self.state_path = self.base / "tv-state.json"
+ self.list_path = self.base / "debloat.txt"
+ self.write_list(["com.example.enabled", "com.example.already_off", "com.example.absent"])
+
+ def write_list(self, names):
+ self.list_path.write_text("# My TV\n" + "".join(f"{name}\n" for name in names))
+
+ def tv(self, **overrides):
+ state = {
+ "installed": ["com.example.enabled", "com.example.already_off",
+ "com.google.android.tvlauncher"],
+ "disabled": ["com.example.already_off"],
+ "home": STOCK_HOME,
+ "settings": {"window_animation_scale": "0.5",
+ "transition_animation_scale": "null",
+ "animator_duration_scale": "1.0"},
+ "commands": [],
+ "unreachable": False,
+ }
+ state.update(overrides)
+ self.state_path.write_text(json.dumps(state))
+
+ def run_script(self, script, *args):
+ env = dict(os.environ, TV_HOST="192.168.1.50", HOME=str(self.home),
+ FAKE_TV_STATE=str(self.state_path))
+ return subprocess.run(
+ ["bash", str(self.repo / "tools" / script), *args],
+ cwd=self.repo, env=env, capture_output=True, text=True, timeout=120,
+ )
+
+ def record(self):
+ files = list((self.home / ".cleanyourtv").glob("recovery-*.json"))
+ self.assertLessEqual(len(files), 1, "one record per TV and list")
+ return json.loads(files[0].read_text()) if files else None
+
+ def sent(self):
+ with open(self.state_path) as f:
+ return json.load(f)["commands"]
+
+ def test_save_records_the_state_undo_needs(self):
+ self.tv()
+ result = self.run_script("disable.sh", str(self.list_path))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ record = self.record()
+ self.assertIsNotNone(record)
+ self.assertEqual(record["packages"], {
+ "com.example.enabled": "enabled",
+ "com.example.already_off": "disabled",
+ "com.example.absent": "absent",
+ # Home's package is recorded even though the list does not mention it: undo has to put it
+ # back if the list disabled it.
+ "com.google.android.tvlauncher": "enabled",
+ })
+ self.assertEqual(record["home"], STOCK_HOME)
+ self.assertEqual(record["settings"]["window_animation_scale"], "0.5")
+ # The list itself still reaches the TV, after the record is on disk.
+ self.assertEqual(self.sent()[:3], [
+ "pm disable-user --user 0 com.example.enabled",
+ "pm disable-user --user 0 com.example.already_off",
+ "pm disable-user --user 0 com.example.absent",
+ ])
+
+ def test_retry_keeps_the_original_record(self):
+ self.tv()
+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)
+ first = self.record()
+ # A second run happens on a TV where the list has already been applied: enabled is now off.
+ self.tv(installed=["com.example.already_off", "com.google.android.tvlauncher"],
+ disabled=["com.example.enabled", "com.example.already_off"])
+ result = self.run_script("disable.sh", str(self.list_path))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("keeping the recovery record", result.stdout)
+ self.assertEqual(self.record()["packages"], first["packages"])
+
+ def test_failed_save_disables_nothing(self):
+ self.tv(unreachable=True)
+ result = self.run_script("disable.sh", str(self.list_path))
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(self.sent(), [], "a failed record must not be followed by a mutation")
+ self.assertIsNone(self.record())
+
+ def test_corrupt_record_is_not_overwritten(self):
+ self.tv()
+ folder = self.home / ".cleanyourtv"
+ # Take a record, then damage it the way an interrupted copy would.
+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)
+ path = next(folder.glob("recovery-*.json"))
+ path.write_text("{not json")
+ with open(self.state_path) as f:
+ state = json.load(f)
+ state["commands"] = []
+ self.state_path.write_text(json.dumps(state))
+
+ result = self.run_script("disable.sh", str(self.list_path))
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("not a usable recovery record", result.stderr)
+ self.assertEqual(path.read_text(), "{not json", "the original file is left for inspection")
+ self.assertEqual(self.sent(), [], "nothing was disabled")
+
+ def test_restore_replays_recorded_states(self):
+ self.tv(settings={"window_animation_scale": "0.5",
+ "transition_animation_scale": "null",
+ "animator_duration_scale": "3.0"})
+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)
+ with open(self.state_path) as f:
+ state = json.load(f)
+ state["commands"] = []
+ self.state_path.write_text(json.dumps(state))
+
+ result = self.run_script("restore.sh", str(self.list_path))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ sent = self.sent()
+ self.assertIn("pm enable com.example.enabled", sent)
+ self.assertNotIn("pm enable com.example.already_off",
+ sent, "a package that was already disabled stays disabled")
+ self.assertNotIn("pm enable com.example.absent", sent)
+ # Home is the component that owned it, not a package name resolved on the fly.
+ self.assertIn(f"cmd package set-home-activity --user 0 {STOCK_HOME}", sent)
+ # Settings go back to the recorded values, including the one that was unset before.
+ self.assertIn("settings put global window_animation_scale 0.5", sent)
+ self.assertIn("settings delete global transition_animation_scale", sent)
+ self.assertIn("settings put global animator_duration_scale 3.0", sent)
+ self.assertEqual(sent[-1], "pm list packages -d")
+ self.assertIn("leaving com.example.already_off alone", result.stderr)
+
+ def test_restore_without_a_record_says_so_and_falls_back(self):
+ self.tv()
+ result = self.run_script("restore.sh", str(self.list_path))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ sent = self.sent()
+ self.assertIn("no recovery record", result.stderr)
+ self.assertEqual(sent[:3], [
+ "pm enable com.example.enabled",
+ "pm enable com.example.already_off",
+ "pm enable com.example.absent",
+ ])
+ self.assertIn("pm enable com.google.android.tvlauncher", sent)
+ self.assertIn("settings put global window_animation_scale 1.0", sent)
+
+ def test_edited_list_leaves_new_names_alone(self):
+ self.tv()
+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)
+ self.write_list(["com.example.enabled", "com.example.added_later"])
+ with open(self.state_path) as f:
+ state = json.load(f)
+ state["commands"] = []
+ self.state_path.write_text(json.dumps(state))
+
+ result = self.run_script("restore.sh", str(self.list_path))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertNotIn("pm enable com.example.added_later", self.sent())
+ self.assertIn("not in the record, leaving alone: com.example.added_later", result.stderr)
+
++ def clear_sent(self):
++ with open(self.state_path) as f:
++ state = json.load(f)
++ state["commands"] = []
++ self.state_path.write_text(json.dumps(state))
++
++ def test_rerun_with_edited_list_records_the_new_names(self):
++ self.tv()
++ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)
++ first = self.record()
++ # The list gains a name; the second run happens on a TV where the first list is applied.
++ self.write_list(["com.example.enabled", "com.example.already_off", "com.example.absent",
++ "com.example.added_later"])
++ self.tv(installed=["com.example.enabled", "com.example.already_off",
++ "com.example.added_later", "com.google.android.tvlauncher"],
++ disabled=["com.example.enabled", "com.example.already_off"])
++ result = self.run_script("disable.sh", str(self.list_path))
++ self.assertEqual(result.returncode, 0, result.stderr)
++ packages = self.record()["packages"]
++ self.assertEqual(packages["com.example.added_later"], "enabled")
++ # Entries from the first run keep the state from before it, not the half-applied one.
++ for name, state in first["packages"].items():
++ self.assertEqual(packages[name], state, name)
++ self.assertEqual(self.record()["created"], first["created"])
++
++ self.clear_sent()
++ result = self.run_script("restore.sh", str(self.list_path))
++ self.assertEqual(result.returncode, 0, result.stderr)
++ sent = self.sent()
++ self.assertIn("pm enable com.example.added_later", sent,
++ "a name added to the list later is not left disabled forever")
++ self.assertIn("pm enable com.example.enabled", sent)
++ self.assertNotIn("pm enable com.example.already_off", sent)
++
++ def test_custom_launcher_home_restores_the_stock_launcher(self):
++ custom = "com.gathin.tvhome/.MainActivity"
++ self.tv(installed=["com.example.enabled", "com.example.already_off",
++ "com.google.android.tvlauncher", "com.gathin.tvhome"],
++ home=custom)
++ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)
++ self.assertEqual(self.record()["home"], custom)
++ self.clear_sent()
++
++ result = self.run_script("restore.sh", str(self.list_path))
++ self.assertEqual(result.returncode, 0, result.stderr)
++ sent = self.sent()
++ self.assertIn("pm enable com.google.android.tvlauncher", sent)
++ self.assertNotIn(f"cmd package set-home-activity --user 0 {custom}", sent)
++ home = [c for c in sent if c.startswith("cmd package set-home-activity")]
++ self.assertEqual(len(home), 1, sent)
++ self.assertIn("resolve-activity", home[0])
++ self.assertIn("com.google.android.tvlauncher", home[0])
++ self.assertLess(sent.index("pm enable com.google.android.tvlauncher"), sent.index(home[0]))
++
++ def test_stock_launcher_disabled_before_cleanup_stays_disabled(self):
++ custom = "com.gathin.tvhome/.MainActivity"
++ self.write_list(["com.example.enabled", "com.google.android.tvlauncher"])
++ self.tv(installed=["com.example.enabled", "com.google.android.tvlauncher",
++ "com.gathin.tvhome"],
++ disabled=["com.google.android.tvlauncher"], home=custom)
++ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)
++ self.assertEqual(self.record()["packages"]["com.google.android.tvlauncher"], "disabled")
++ self.clear_sent()
++
++ result = self.run_script("restore.sh", str(self.list_path))
++ self.assertEqual(result.returncode, 0, result.stderr)
++ self.assertNotIn("pm enable com.google.android.tvlauncher", self.sent())
++
++ def test_stock_launcher_enabled_once_when_it_owned_home(self):
++ # The usual case: Home's package is recorded as enabled, so it is enabled exactly once.
++ self.tv()
++ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)
++ self.clear_sent()
++ result = self.run_script("restore.sh", str(self.list_path))
++ self.assertEqual(result.returncode, 0, result.stderr)
++ sent = self.sent()
++ self.assertEqual(sent.count("pm enable com.google.android.tvlauncher"), 1)
++ self.assertIn(f"cmd package set-home-activity --user 0 {STOCK_HOME}", sent)
++
+ def test_list_that_is_not_package_names_is_refused(self):
+ self.tv()
+ self.list_path.write_text("com.example.good\ncom.example.evil;settings put global adb_enabled 0\n")
+ for script in ("disable.sh", "restore.sh"):
+ with self.subTest(script=script):
+ result = self.run_script(script, str(self.list_path))
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("not a package name", result.stderr)
+ self.assertIn("com.example.evil;settings", result.stderr)
+ self.assertEqual(self.sent(), [])
+
+
+ if __name__ == "__main__":
+ unittest.main()
diff --cc tools/disable.sh
index 673156d7c,d4c7ebcfc..af48b5a9e
--- a/tools/disable.sh
+++ b/tools/disable.sh
@@@ -5,8 -5,8 +5,10 @@@
# Usage: TV_HOST=192.168.1.50 tools/disable.sh examples/xiaomi-mi-tv-4a/debloat.txt
set -euo pipefail
LIST="${1:?usage: disable.sh <debloat list>}"
--# Resolve the list against the caller's directory before moving into the repo.
--LIST_DIR="$(cd "$(dirname "$LIST")" && pwd)"
++# Resolve the list against the caller's directory before moving into the repo. Git Bash's pwd says
++# /c/Users/..., which the Windows Python cannot open with MSYS_NO_PATHCONV=1 set; pwd -W gives
++# C:/Users/..., the same path (and so the same record) as the PowerShell scripts.
++LIST_DIR="$(cd "$(dirname "$LIST")" && { pwd -W 2>/dev/null || pwd; })"
LIST="$LIST_DIR/$(basename "$LIST")"
cd "$(dirname "$0")/.."
PY=tools/venv/bin/python
diff --cc tools/recovery.py
index 000000000,422c9ac61..40d17baaf
mode 000000,100644..100644
--- a/tools/recovery.py
+++ b/tools/recovery.py
@@@ -1,0 -1,252 +1,281 @@@
+ #!/usr/bin/env python3
+ """The state a debloat list is about to change, so that undo means undo (#239).
+
+ recovery.py --save <debloat list> read the TV and write the record
+ recovery.py --commands <list> [stock launcher] print a batch for tools/tv.py --batch that puts
+ the recorded states back
+
+ `tools/restore.sh` used to enable every package in the list, including ones the owner had already
+ disabled, and reset Home and the animation scales to fixed values instead of to what was there
+ before. Both scripts now go through this record: `disable.sh` writes it before the first command
+ reaches the TV, and `restore.sh` replays it.
+
+ Records live in ~/.cleanyourtv/, one per TV and list. The first one wins: a retry after a
-half-applied list must not record the broken state as the original.
++half-applied list must not record the broken state as the original. A later run only adds the names
++the list gained since then, with their state before this list disabled them.
+ """
+ import hashlib
+ import json
+ import os
+ from pathlib import Path
+ import re
+ import sys
+ import time
+
+ # Every name from the TV or from the list ends up inside a command run by the TV's shell, so nothing
+ # that could carry shell syntax is allowed through.
+ PACKAGE_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+")
+ HOME_RE = re.compile(r"[A-Za-z_][\w.]*/[\w.$]+")
+ SCALE_RE = re.compile(r"-?\d+(\.\d+)?")
+ SETTINGS = ("window_animation_scale", "transition_animation_scale", "animator_duration_scale")
++# This project's own launcher. When it already owned Home before debloating, restoring Home to it
++# would leave the stock launcher off, so restore goes back to the stock one instead.
++CUSTOM_LAUNCHER = "com.gathin.tvhome"
+ VERSION = 1
+
+
+ def read_list(path):
+ """Package names from a debloat list, in file order.
+
+ A BOM and CRLF from a Windows editor are dropped, as is a trailing `# note`; anything that is not
+ a bare package name stops the run before the TV is touched.
+ """
+ text = Path(path).read_text(encoding="utf-8-sig", errors="replace")
+ names = []
+ for number, line in enumerate(text.splitlines(), 1):
+ line = line.split("#", 1)[0].strip()
+ if not line:
+ continue
+ name = line.split()[0]
+ if not PACKAGE_RE.fullmatch(name):
+ raise SystemExit(f"{path}:{number}: not a package name: {name!r}")
+ names.append(name)
+ if not names:
+ raise SystemExit(f"{path}: no package names in this list")
+ return names
+
+
+ def record_path(list_path, host):
+ """One record per TV and list. The list is identified by its absolute path, so a copy of the
+ same file somewhere else gets its own record."""
+ tag = re.sub(r"[^A-Za-z0-9.-]", "_", host or "no-host")
+ digest = hashlib.sha1(str(Path(list_path).resolve()).encode()).hexdigest()[:8]
+ return Path.home() / ".cleanyourtv" / f"recovery-{tag}-{digest}.json"
+
+
+ def load_record(path):
+ try:
+ with open(path) as f:
+ record = json.load(f)
+ except (OSError, ValueError) as e:
+ raise SystemExit(f"{path}: not a usable recovery record ({e}).\n"
+ "It is left where it is: move it aside deliberately, a retry must not "
+ "replace the state recorded before the first change.")
+ if record.get("version") != VERSION or not isinstance(record.get("packages"), dict):
+ raise SystemExit(f"{path}: unknown recovery record format; move it aside deliberately.")
+ return record
+
+
+ def write_record(path, record):
+ # Written next to its final name first: a crash halfway through must not leave a truncated record
+ # that then blocks every retry as "already recorded".
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(path.name + ".tmp")
+ with open(tmp, "w") as f:
+ json.dump(record, f, indent=2, sort_keys=True)
+ f.write("\n")
+ f.flush()
+ os.fsync(f.fileno())
+ os.replace(tmp, path)
+
+
+ def shell(dev, command):
+ return (dev.shell(command, read_timeout_s=120.0) or "").strip()
+
+
+ def query_packages(dev):
+ installed = {line.split(":", 1)[1].strip()
+ for line in shell(dev, "pm list packages").splitlines()
+ if line.startswith("package:")}
+ if not installed:
+ raise SystemExit("the TV returned no packages, so nothing was recorded and nothing will be "
+ "disabled. Check the connection (tools/tv.py --probe) and try again.")
+ disabled = {line.split(":", 1)[1].strip()
+ for line in shell(dev, "pm list packages -d").splitlines()
+ if line.startswith("package:")}
+ return installed, disabled
+
+
+ def query_home(dev):
+ answer = shell(dev, "cmd package resolve-activity --brief -a android.intent.action.MAIN -c "
+ "android.intent.category.HOME")
+ candidate = answer.splitlines()[-1].strip() if answer else ""
+ # Android answers "android" (the chooser) when nothing handles HOME; that is not a component and
+ # must never be written into a set-home-activity command.
+ return candidate if HOME_RE.fullmatch(candidate) else None
+
+
+ def connect():
+ # Imported here so --commands works on a machine where adb_shell is not installed: printing the
+ # restore batch needs no TV. tv.py itself exits with a readable message when TV_HOST is unset.
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ try:
+ import tv
+ except ImportError as e:
+ raise SystemExit(f"cannot load tools/tv.py ({e}).\nrun: python3 -m venv tools/venv && "
+ "tools/venv/bin/pip install -r tools/requirements.txt")
+ return tv.connect()
+
+
++def package_state(name, installed, disabled):
++ return ("absent" if name not in installed
++ else "disabled" if name in disabled
++ else "enabled")
++
++
+ def save(list_path, host):
+ path = record_path(list_path, host)
+ if path.exists():
+ record = load_record(path)
++ packages = read_list(list_path)
++ # The list may have been edited since the record was taken. Entries already in the record are
++ # never overwritten (a retry must not record the broken state as the original), but names it
++ # does not hold yet have not been touched by this list, so their state now is their state
++ # before cleanup. Without them, restore would leave those packages disabled for good.
++ added = [name for name in packages if name not in record["packages"]]
+ print(f"keeping the recovery record from {record.get('created')}: {path}")
- print("nothing was recorded again: it holds the state from before the first run.")
++ if not added:
++ print("nothing was recorded again: it holds the state from before the first run.")
++ return 0
++ dev = connect()
++ try:
++ installed, disabled = query_packages(dev)
++ finally:
++ dev.close()
++ for name in added:
++ record["packages"][name] = package_state(name, installed, disabled)
++ write_record(path, record)
++ print(f"added {len(added)} names the list gained since then, entries already recorded "
++ f"are unchanged: {', '.join(added)}")
+ return 0
+
+ packages = read_list(list_path)
+ dev = connect()
+ try:
+ installed, disabled = query_packages(dev)
+ home = query_home(dev)
+ scales = {key: shell(dev, f"settings get global {key}") for key in SETTINGS}
+ finally:
+ dev.close()
+
+ # The launcher that owns Home may not be in the list, but it is what undo has to put back.
+ home_package = home.split("/", 1)[0] if home else None
+ targets = packages + ([home_package] if home_package and home_package not in packages else [])
+ record = {
+ "version": VERSION,
+ "created": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
+ "host": host,
+ "list": str(Path(list_path).resolve()),
+ "home": home,
+ "settings": scales,
- "packages": {
- name: ("absent" if name not in installed
- else "disabled" if name in disabled
- else "enabled")
- for name in targets
- },
++ "packages": {name: package_state(name, installed, disabled) for name in targets},
+ }
+ write_record(path, record)
+
+ already = sum(1 for state in record["packages"].values() if state == "disabled")
+ print(f"recorded {len(record['packages'])} packages on {host} "
+ f"({already} already disabled, left alone by undo) -> {path}")
+ print(f"HOME before: {home or 'no component answered'}")
+ print("undo with tools/restore.sh <same list>; keep this file, it is the only copy.")
+ return 0
+
+
+ def restore_commands(list_path, stock, host):
+ """The batch that puts the recorded states back, one command per line."""
+ packages = read_list(list_path)
+ if stock and not PACKAGE_RE.fullmatch(stock):
+ raise SystemExit(f"not a package name: {stock!r}")
+ path = record_path(list_path, host)
+ commands = []
+
+ if not path.exists():
+ sys.stderr.write(
+ f"no recovery record for this TV and list ({path}).\n"
+ "Enabling every listed package and resetting Home and the animation scales to their\n"
+ "defaults. Packages that were already disabled before cleanup will be enabled too:\n"
+ "check the list before running this.\n")
+ for name in packages:
+ commands.append(f"pm enable {name}")
+ if stock:
+ commands.append(f"pm enable {stock}")
+ commands.append(f"cmd package set-home-activity --user 0 $(cmd package resolve-activity "
+ f"--brief -a android.intent.action.MAIN -c android.intent.category.HOME "
+ f"{stock or 'com.google.android.tvlauncher'} | tail -n 1)")
+ commands.extend(f"settings put global {key} 1.0" for key in SETTINGS)
+ commands.append("pm list packages -d")
+ return commands
+
+ record = load_record(path)
+ states = record["packages"]
+ re_enable = [name for name, state in states.items() if state == "enabled"]
+ for name in re_enable:
+ commands.append(f"pm enable {name}")
+ untouched = [(name, state) for name, state in states.items() if state != "enabled"]
+ for name, state in untouched:
+ sys.stderr.write(f" leaving {name} alone ({state} when the record was taken)\n")
+
++ # The stock launcher comes back unless the owner had disabled it before cleanup: the list may
++ # have disabled it even when it was not the recorded Home (e.g. the custom launcher owned Home).
++ fallback = stock or "com.google.android.tvlauncher"
++ if states.get(fallback) != "disabled" and fallback not in re_enable:
++ commands.append(f"pm enable {fallback}")
++
+ home = record.get("home")
- if home:
++ if home and home.split("/", 1)[0] != CUSTOM_LAUNCHER:
+ commands.append(f"cmd package set-home-activity --user 0 {home}")
+ else:
- # Nothing handled HOME before cleanup (fresh TV, chooser only), so there is no component to
- # replay; ask the TV to resolve the stock launcher the way restore.sh always did.
- fallback = stock or "com.google.android.tvlauncher"
++ # Nothing handled HOME before cleanup (fresh TV, chooser only), or this project's launcher
++ # did, so there is no stock component to replay; ask the TV to resolve the stock launcher the
++ # way restore.sh always did.
+ commands.append(f"cmd package set-home-activity --user 0 $(cmd package resolve-activity "
+ f"--brief -a android.intent.action.MAIN -c android.intent.category.HOME "
+ f"{fallback} | tail -n 1)")
+ for key in SETTINGS:
+ value = str(record.get("settings", {}).get(key, "")).strip()
+ if value == "null":
+ commands.append(f"settings delete global {key}")
+ elif SCALE_RE.fullmatch(value):
+ commands.append(f"settings put global {key} {value}")
+ else:
+ sys.stderr.write(f" skipping {key}: the record holds {value!r}, not a number\n")
- # The list is not in the record (it may have been edited since); packages added afterwards are
- # left as they are, which is what "leave the TV alone" means for them.
++ # disable.sh adds names the list gained to the record before disabling them, so a name still
++ # missing here was added after the last disable run and never disabled by it: leave it alone.
+ edited = [name for name in packages if name not in states]
+ if edited:
+ sys.stderr.write(f"not in the record, leaving alone: {', '.join(edited)}\n")
+ commands.append("pm list packages -d")
+
+ sys.stderr.write(f"restoring the state recorded on {record.get('created')}: "
+ f"re-enabling {len(re_enable)}, leaving {len(untouched)} as they were.\n")
+ return commands
+
+
+ def main():
+ args = sys.argv[1:]
+ host = os.environ.get("TV_HOST", "")
+ if len(args) == 2 and args[0] == "--save":
+ return save(args[1], host)
+ if len(args) in (2, 3) and args[0] == "--commands":
+ if not host:
+ sys.stderr.write("Set TV_HOST to your TV's IP address, e.g. TV_HOST=192.168.1.50\n")
+ stock = args[2] if len(args) == 3 else "com.google.android.tvlauncher"
+ for command in restore_commands(args[1], stock, host):
+ print(command)
+ return 0
+ sys.stderr.write("usage: recovery.py --save <debloat list>\n"
+ " recovery.py --commands <debloat list> [stock launcher package]\n")
+ return 2
+
+
+ if __name__ == "__main__":
+ sys.exit(main())
diff --cc tools/restore.sh
index b073d80d6,2c74d96d7..84537fae4
--- a/tools/restore.sh
+++ b/tools/restore.sh
@@@ -5,30 -6,15 +6,18 @@@
# Usage: TV_HOST=192.168.1.50 tools/restore.sh examples/xiaomi-mi-tv-4a/debloat.txt [stock.launcher.package]
set -euo pipefail
LIST="${1:?usage: restore.sh <debloat list> [stock launcher package]}"
--# Resolve the list against the caller's directory before moving into the repo.
--LIST_DIR="$(cd "$(dirname "$LIST")" && pwd)"
++# Resolve the list against the caller's directory before moving into the repo. Git Bash's pwd says
++# /c/Users/..., which the Windows Python cannot open with MSYS_NO_PATHCONV=1 set; pwd -W gives
++# C:/Users/..., the same path (and so the same record) as the PowerShell scripts.
++LIST_DIR="$(cd "$(dirname "$LIST")" && { pwd -W 2>/dev/null || pwd; })"
LIST="$LIST_DIR/$(basename "$LIST")"
cd "$(dirname "$0")/.."
STOCK="${2:-com.google.android.tvlauncher}"
PY=tools/venv/bin/python
[ -x "$PY" ] || PY=tools/venv/Scripts/python.exe
export MSYS_NO_PATHCONV=1
- # Same check as disable.sh: the list is contributor-supplied and each entry becomes a shell
- # command on the TV. A BOM and CRLF from a Windows editor are dropped first (#165, #208).
- PKGS=$(LC_ALL=C awk 'NR==1{sub(/^\357\273\277/,"")} {sub(/\r$/,""); print}' "$LIST" \
- | grep -vE '^\s*(#|$)' | sed -E 's/\s+#.*$//' | awk '{print $1}')
- BAD=$(printf '%s\n' "$PKGS" | grep -vE '^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$' || true)
- if [ -n "$BAD" ]; then
- { echo "refusing $LIST: not a package name:"; printf '%s\n' "$BAD" | sed 's/^/ /'; } >&2
- exit 1
- fi
- {
- [ -n "$PKGS" ] && printf '%s\n' "$PKGS" | sed 's/^/pm enable /'
- echo "pm enable $STOCK"
- # resolve the stock HOME component on the TV (Android 9 needs pkg/activity, not just pkg)
- echo "cmd package set-home-activity --user 0 \$(cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME $STOCK | tail -n 1)"
- echo "settings put global window_animation_scale 1.0"
- echo "settings put global transition_animation_scale 1.0"
- echo "settings put global animator_duration_scale 1.0"
- echo "pm list packages -d"
- } | "$PY" -I tools/tv.py --batch
+ # recovery.py reads and validates the list itself, prints the batch for tv.py and says on stderr what
-# it will leave alone. Without a record it warns and falls back to enabling the whole list. pipefail
-# keeps a refused plan from reaching the TV.
++# it will leave alone. Without a record it warns and falls back to enabling the whole list. A refused
++# plan never reaches the TV because recovery.py prints nothing until the whole plan is built, so
++# tv.py reads an empty batch; pipefail only makes this script exit non-zero afterwards.
+ "$PY" -I tools/recovery.py --commands "$LIST" "$STOCK" | "$PY" -I tools/tv.py --batch