Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
tools: manage.py set refuses a theme folder inside the checkout, and a config.json it cannot read
xbshengab4d2ea0e280
diff --git a/tests/test_manage_set.py b/tests/test_manage_set.pyindex 965f5bd47..d3950df7e 100644--- a/tests/test_manage_set.py+++ b/tests/test_manage_set.py@@ -207,5 +207,127 @@ class SetValueTest(unittest.TestCase):self.assertIn("return i < min || i > max ? fallback : i;", config)+class SetThemeFolderTest(unittest.TestCase):+ """set writes into the owner's theme folder: one it cannot read, or one this checkout ships, is refused.++ themes/README.md sends a theme author to write config.json by hand, so the file set reads is a hand-edited+ one: a comma left after the last key, a list where the launcher reads an object, a file saved by an editor+ in another encoding. Each of those was a traceback from halfway through set, and `--theme examples/<model>`+ rewrote a tracked config.json and pushed it (tests/test_shipped_config_values.py holds those files to the+ launcher's readers, so the edit could also fail CI in an unrelated pull request).+ """++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.theme = Path(self.tmp.name) / "my-theme"+ self.theme.mkdir()+ self.config = self.theme / "config.json"+ patcher = mock.patch.object(manage, "run")+ self.push = patcher.start()+ self.addCleanup(patcher.stop)++ def set_key(self, key="dock_band", value="true", folder=None):+ """Runs set the way main() does; returns the refusal text, or None when the value was written."""+ try:+ with mock.patch("sys.stdout"):+ manage.cmd_set(key, value, str(folder or self.theme))+ except SystemExit as stop:+ return str(stop.code)+ return None++ def test_a_config_json_that_is_not_json_is_named_and_left_alone(self):+ self.config.write_text('{"greeting_name": "Old",}\n', encoding="utf-8")+ before = self.config.read_bytes()+ refusal = self.set_key()+ self.assertIn(str(self.config), refusal)+ self.assertIn("is not valid JSON", refusal)+ self.assertIn("Nothing was written or pushed", refusal)+ self.assertEqual(before, self.config.read_bytes(), "a refused theme must not be rewritten")+ self.push.assert_not_called()++ def test_a_config_json_that_is_not_an_object_is_named(self):+ for text, kind in (("[1, 2]", "an array"), ('"a theme"', "a string"), ("12", "a number"),+ ("null", "null"), ("true", "a boolean")):+ with self.subTest(config=text):+ self.config.write_text(text, encoding="utf-8")+ refusal = self.set_key()+ self.assertIn(f"holds {kind}", refusal)+ self.assertIn("not a JSON object", refusal)+ self.assertEqual(text, self.config.read_text(encoding="utf-8"), "a refused theme must not be rewritten")+ self.push.assert_not_called()++ def test_a_config_json_in_another_encoding_is_named(self):+ # A file an editor saved as UTF-16, the way a Windows editor does by default for "Unicode".+ self.config.write_bytes('{"greeting_name": "Old"}'.encode("utf-16"))+ before = self.config.read_bytes()+ refusal = self.set_key()+ self.assertIn(f"cannot read {self.config}", refusal)+ self.assertIn("Nothing was written or pushed", refusal)+ self.assertEqual(before, self.config.read_bytes())+ self.push.assert_not_called()++ def test_a_theme_that_is_a_file_is_named(self):+ afile = Path(self.tmp.name) / "not-a-theme"+ afile.write_text("", encoding="utf-8")+ refusal = self.set_key(folder=afile)+ self.assertIn(f"{afile} is a file, not a folder", refusal)+ self.push.assert_not_called()++ def test_a_write_it_cannot_make_is_named(self):+ # A file in the middle of the path: mkdir cannot create a folder under one.+ afile = Path(self.tmp.name) / "not-a-folder"+ afile.write_text("", encoding="utf-8")+ refusal = self.set_key(folder=afile / "theme")+ self.assertIn("cannot write", refusal)+ self.assertIn("config.json", refusal)+ self.assertIn("Nothing was pushed", refusal)+ self.push.assert_not_called()++ def test_a_folder_this_checkout_ships_is_refused(self):+ # A checkout of its own, so the project's real files are never touched by this test.+ root = Path(self.tmp.name) / "checkout"+ for name in manage.PROJECT_FOLDERS:+ (root / name / "shipped").mkdir(parents=True)+ (root / name / "shipped" / "config.json").write_text('{"greeting_name": "Shipped"}\n', encoding="utf-8")+ patcher = mock.patch.object(manage, "ROOT", root)+ patcher.start()+ self.addCleanup(patcher.stop)+ for name in manage.PROJECT_FOLDERS:+ folder = root / name / "shipped"+ before = (folder / "config.json").read_bytes()+ with self.subTest(project=name):+ refusal = self.set_key(folder=folder)+ self.assertIn(f"inside this checkout's {name}/", refusal)+ self.assertIn("Nothing was written or pushed", refusal)+ self.assertEqual(before, (folder / "config.json").read_bytes(),+ "set must not rewrite a config.json the checkout ships")+ self.push.assert_not_called()+ # The guard is about where the file is, not about being careful: a folder of the owner's own is written.+ mine = root / "my-theme"+ mine.mkdir()+ self.assertIsNone(self.set_key(folder=mine))+ self.assertIs(json.loads((mine / "config.json").read_text(encoding="utf-8"))["dock_band"], True)++ def test_every_folder_that_ships_a_config_json_is_one_set_refuses(self):+ # A third kind of folder with a config.json in it (a new add-on contract, say) has to be added to+ # PROJECT_FOLDERS, or set would rewrite it the way examples/ used to be rewritable.+ shipped = {}+ for path in sorted(ROOT.glob("*/*/config.json")):+ shipped.setdefault(path.relative_to(ROOT).parts[0], set()).add(path)+ self.assertGreaterEqual(sum(len(v) for v in shipped.values()), 60, "no config.json files were found")+ self.assertEqual({"examples", "themes"}, set(shipped), "a folder with a config.json that set does not guard")+ self.assertEqual(set(shipped), set(manage.PROJECT_FOLDERS))+++ def test_the_page_that_hands_out_set_names_the_refusal(self):+ # themes/README.md is where a theme author meets `set`: a refusal they were not told about costs them+ # a run against a TV.+ page = (ROOT / "themes" / "README.md").read_text(encoding="utf-8")+ self.assertIn("outside this checkout", page)+ for name in manage.PROJECT_FOLDERS:+ self.assertIn(f"`{name}/`", page)++if __name__ == "__main__":unittest.main()diff --git a/themes/README.md b/themes/README.mdindex 174166236..b91bdf998 100644--- a/themes/README.md+++ b/themes/README.md@@ -13,8 +13,9 @@ powershell -ExecutionPolicy Bypass -File tools\theme.ps1 -TvHost 192.168.1.50 th````tools/manage.py list themes` and `list switches` list them from this file, `show <name>` gives one with its-screenshot, and `manage.py set <switch> <value> --theme <your folder>` writes a key into a theme of your own and-pushes it with `theme.sh`.+screenshot, and `manage.py set <switch> <value> --theme <your folder>` writes a key into a theme folder of your own+and pushes it with `theme.sh`. The folder has to be outside this checkout: one under `themes/` or `examples/` is+refused (copy a theme first), and a `config.json` it cannot read is named before anything is written or pushed.| Theme | What it does | Screenshot ||---|---|---|diff --git a/tools/manage.py b/tools/manage.pyindex 84b0d4071..b7be1d627 100644--- a/tools/manage.py+++ b/tools/manage.py@@ -12,10 +12,12 @@ build-and-install.sh, or the steps in addons/README.md; tools/theme.sh for themeTV_HOST=<tv ip> tools/venv/bin/python -I tools/manage.py set <switch> <json value> --theme <your theme folder>install on an installed add-on updates it (pm install -r). set writes the key into a theme folder of your own and-pushes it with tools/theme.sh, as themes/README.md describes; it never edits the project's themes. set reads the-value the way the key's own type in the Keys table needs - true or false for a bool, a JSON list, object or number-where the table says so, the text itself for a string - and refuses one the launcher would ignore or a number-outside the range the table states.+pushes it with tools/theme.sh, as themes/README.md describes; it never edits a folder in this checkout, so pointing+--theme at the project's themes/ or examples/ is refused before anything is written. set reads the value the way+the key's own type in the Keys table needs - true or false for a bool, a JSON list, object or number where the+table says so, the text itself for a string - and refuses one the launcher would ignore or a number outside the+range the table states. A theme's config.json is hand-edited, so one that cannot be read, is not JSON, or is not a+JSON object is named before the key is written, and a write it cannot make says so instead of ending in a traceback."""import jsonimport math@@ -221,6 +223,66 @@ def value_as(key, item, text):return parsed+# ---------------------------------------------------------------- the theme folder set writes into++# Both folders hold config.json files this checkout ships and its tests hold to the launcher's readers+# (tests/test_shipped_config_values.py): a theme author who pointed --theme at one would rewrite a tracked+# file, and the edit would ride along in their next pull request.+PROJECT_FOLDERS = ("themes", "examples")+++def reason(error):+ """The short reason from an OSError or a decoding error, without the errno prefix Python repeats."""+ return getattr(error, "strerror", None) or str(error)+++def json_kind(value):+ """What a parsed JSON value is, in the words a reader would use."""+ for kind, name in ((bool, "a boolean"), (list, "an array"), (str, "a string"), (int, "a number"),+ (float, "a number"), (type(None), "null")):+ if isinstance(value, kind):+ return name+ return type(value).__name__+++def own_folder_problem(folder):+ """Why set may not write into `folder`, or None: it is one of the folders this checkout ships, or a file."""+ for name in PROJECT_FOLDERS:+ project = ROOT / name+ if folder == project or project in folder.parents:+ return (f"{folder} is inside this checkout's {name}/: set writes into a theme folder of your own, "+ f"so copy one somewhere else first. Nothing was written or pushed.")+ if folder.exists() and not folder.is_dir():+ return f"{folder} is a file, not a folder: --theme takes a theme folder of your own."+ return None+++def theme_config(folder):+ """(data, problem): the theme folder's config.json as an object, or why set cannot use it.++ The file is the owner's own, hand-edited and pushed by tools/theme.sh, so the ways it can be unreadable are+ the owner's next problem to fix: a comma left after the last key, a list where the launcher reads an object,+ a file saved in another encoding. Each is named with its path before the key is written, and nothing is+ pushed, rather than a JSONDecodeError traceback from halfway through the command.+ """+ path = folder / "config.json"+ if not path.is_file():+ return {}, None # a folder of their own with no config.json yet: set starts the file+ try:+ text = path.read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError) as e:+ return {}, f"cannot read {path}: {reason(e)}. Nothing was written or pushed."+ try:+ data = json.loads(text)+ except ValueError as e:+ return {}, (f"{path} is not valid JSON ({e}); fix it, then run set again. "+ f"Nothing was written or pushed.")+ if not isinstance(data, dict):+ return {}, (f"{path} holds {json_kind(data)}, not a JSON object, and a theme's config.json is an object "+ f"of keys. Nothing was written or pushed.")+ return data, None++# ---------------------------------------------------------------- the TVdef tv_python():@@ -353,14 +415,22 @@ def cmd_set(key, value, theme_folder):if not item or item["kind"] != "switch":sys.exit(f"no switch called {key}")folder = Path(theme_folder).resolve()- if ROOT / "themes" in folder.parents or folder == ROOT / "themes":- sys.exit("use a theme folder of your own, not one of the project's (copy one first)")+ problem = own_folder_problem(folder)+ if problem:+ sys.exit(problem)+ data, problem = theme_config(folder)+ if problem:+ sys.exit(problem)parsed = value_as(key, item, value) # before the file is written or anything is pushed- f = folder / "config.json"- data = json.loads(f.read_text(encoding="utf-8")) if f.is_file() else {}data[key] = parsed- folder.mkdir(parents=True, exist_ok=True)- f.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ f = folder / "config.json"+ try:+ folder.mkdir(parents=True, exist_ok=True)+ f.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ except OSError as e:+ # A folder that is read-only, a path with a file in the middle of it, a full disk: the key is not+ # written and the theme on the TV is untouched, so say which file and why rather than a traceback.+ sys.exit(f"cannot write {f}: {reason(e)}. Nothing was pushed.")print(f"{key} = {json.dumps(parsed)} in {f}")return run(["bash", str(TOOLS / "theme.sh"), str(folder)], ROOT)