Skip to content

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

tools: manage.py set refuses a switch value the launcher would drop

xbshengcc24309dd179
diff --git a/tests/test_manage_set.py b/tests/test_manage_set.py
new file mode 100644
index 000000000..c7714d7c8
--- /dev/null
+++ b/tests/test_manage_set.py
@@ -0,0 +1,157 @@
+"""tools/manage.py set writes a value the launcher will read, or refuses one it would drop.
+
+Every reader in Config.java is strict about the JSON type: bool() takes a Boolean and nothing else, string() a
+String, integer() a Number in its range, the list readers an array. A value of another type is not an error
+there - the built-in default comes back - so `set dock_band 3` used to write 3, print "dock_band = 3", push the
+theme and leave the switch at its default on the TV. The type of every key is in the Keys table of
+themes/README.md, so set reads the argument the way that table says and refuses the rest before it writes.
+"""
+import json
+import re
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "tools"))
+import manage # noqa: E402
+
+
+def keys_table_types():
+ """The type cell of every key in themes/README.md's Keys table, read the way manage.switches() reads it."""
+ text = (ROOT / "themes" / "README.md").read_text(encoding="utf-8")
+ part = text[text.index("## Keys"):]
+ out = {}
+ for row in manage.table_rows(part, "| Key |"):
+ for key in re.findall(r"`([a-z_]+)`", row[0]):
+ out[key] = manage.plain(row[1]) if len(row) > 1 else ""
+ return out
+
+
+class SetValueTest(unittest.TestCase):
+ 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"
+ # cmd_set ends by pushing the theme with tools/theme.sh; the tests stop before the TV.
+ patcher = mock.patch.object(manage, "run")
+ self.push = patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def set_key(self, key, value):
+ """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(self.theme))
+ except SystemExit as stop:
+ return str(stop.code)
+ return None
+
+ def written(self):
+ return json.loads(self.config.read_text(encoding="utf-8")) if self.config.is_file() else None
+
+ def test_a_bool_key_refuses_a_number_before_anything_is_written(self):
+ self.config.write_text('{"greeting_name": "Old"}\n', encoding="utf-8")
+ before = self.config.read_bytes()
+ refusal = self.set_key("dock_band", "3")
+ self.assertIn("dock_band", refusal)
+ self.assertIn("true or false", refusal)
+ self.assertIn("3", refusal)
+ self.assertEqual(before, self.config.read_bytes(), "a refused value must not touch the theme")
+ self.push.assert_not_called()
+
+ def test_a_bool_key_takes_true_and_false(self):
+ for text, expected in (("true", True), ("false", False), ("True", True)):
+ with self.subTest(value=text):
+ self.assertIsNone(self.set_key("dock_band", text))
+ self.assertIs(self.written()["dock_band"], expected)
+ self.assertIsInstance(self.written()["dock_band"], bool)
+
+ def test_a_list_key_refuses_a_bare_package_name(self):
+ # The shape a reader types by hand: one package where the launcher wants an array.
+ refusal = self.set_key("dock_apps", "com.example.player")
+ self.assertIn("dock_apps", refusal)
+ self.assertIn("list of package names", refusal)
+ self.assertIn('["a", "b"]', refusal)
+ self.assertIsNone(self.written())
+ self.push.assert_not_called()
+
+ def test_a_list_key_takes_a_json_list(self):
+ self.assertIsNone(self.set_key("dock_apps", '["com.example.player", "com.example.tv"]'))
+ self.assertEqual(["com.example.player", "com.example.tv"], self.written()["dock_apps"])
+
+ def test_a_number_key_refuses_text_and_takes_a_number(self):
+ refusal = self.set_key("columns", "six")
+ self.assertIn("columns", refusal)
+ self.assertIn("1 to 8", refusal)
+ self.assertIsNone(self.written())
+ self.assertIsNone(self.set_key("columns", "6"))
+ self.assertEqual(6, self.written()["columns"])
+
+ def test_a_number_key_refuses_true(self):
+ # Python reads True as an int; the launcher's integer() does not, so the value would be dropped.
+ refusal = self.set_key("columns", "true")
+ self.assertIn("columns", refusal)
+ self.assertIsNone(self.written())
+
+ def test_an_object_key_refuses_a_word_and_takes_a_json_object(self):
+ refusal = self.set_key("wallpaper_moods", "nope")
+ self.assertIn("wallpaper_moods", refusal)
+ self.assertIn("object", refusal)
+ self.assertIsNone(self.written())
+ self.assertIsNone(self.set_key("wallpaper_moods", '{"morning": "a.jpg"}'))
+ self.assertEqual({"morning": "a.jpg"}, self.written()["wallpaper_moods"])
+
+ def test_a_string_key_takes_a_number_as_its_text(self):
+ # string() takes a String only, so a number here would leave the key at its default.
+ self.assertIsNone(self.set_key("greeting_name", "42"))
+ self.assertEqual("42", self.written()["greeting_name"])
+
+ def test_a_string_key_keeps_a_quoted_value_working(self):
+ self.assertIsNone(self.set_key("greeting_name", '"Good evening"'))
+ self.assertEqual("Good evening", self.written()["greeting_name"])
+
+ def test_a_key_the_launcher_never_reads_from_a_theme_is_refused(self):
+ # The table's own words for these two: "list, config.xml only" ... "Not read from a theme".
+ for key in ("input_sources", "settings_fallback_components"):
+ with self.subTest(key=key):
+ refusal = self.set_key(key, '["a/b"]')
+ self.assertIn(key, refusal)
+ self.assertIn("config.xml", refusal)
+ self.assertIsNone(self.written())
+ self.push.assert_not_called()
+
+ def test_an_unknown_key_is_still_refused_by_name(self):
+ self.assertIn("no switch called", self.set_key("no_such_key", "1"))
+
+ def test_the_kind_of_every_key_comes_from_the_keys_table(self):
+ types = keys_table_types()
+ self.assertGreater(len(types), 90, "the Keys table was read")
+ self.assertEqual("bool", manage.declared_kind(manage.find("dock_band")))
+ self.assertEqual("list", manage.declared_kind(manage.find("dock_apps")))
+ self.assertEqual("number", manage.declared_kind(manage.find("columns")))
+ self.assertEqual("object", manage.declared_kind(manage.find("wallpaper_moods")))
+ self.assertEqual("string", manage.declared_kind(manage.find("greeting_name")))
+ self.assertEqual("config-only", manage.declared_kind(manage.find("input_sources")))
+ # A type cell this file does not recognise would fall through to "string" and let a wrong value
+ # through, so every cell the table carries today has to land on a kind.
+ known = {"bool", "list", "number", "object", "string", "config-only"}
+ for cell in sorted(set(types.values())):
+ with self.subTest(cell=cell):
+ self.assertIn(manage.declared_kind({"type": cell}), known)
+
+ def test_the_readers_it_copies_are_still_strict(self):
+ """A launcher that started coercing types would make set's refusals wrong, so pin the readers."""
+ config = (ROOT / "launcher/app/src/main/java/com/gathin/tvhome/Config.java").read_text(encoding="utf-8")
+ self.assertIn("Object v = o.opt(key);", config)
+ self.assertIn("return v instanceof Boolean ? (Boolean) v : fallback;", config)
+ self.assertIn('return v instanceof String ? ((String) v).trim() : fallback;', config)
+ self.assertIn("if (!(v instanceof Number)) return fallback;", config)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/manage.py b/tools/manage.py
index fe8e372ac..aa6d605e0 100644
--- a/tools/manage.py
+++ b/tools/manage.py
@@ -12,7 +12,9 @@ build-and-install.sh, or the steps in addons/README.md; tools/theme.sh for theme
TV_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.
+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.
"""
import json
import os
@@ -134,6 +136,59 @@ def find(name, root=ROOT):
return None
+# ---------------------------------------------------------------- a switch's value
+
+def declared_kind(item):
+ """How the launcher reads a switch, from the type column of the Keys table in themes/README.md.
+
+ Every reader in Config.java is strict about the JSON type - bool() takes a Boolean and nothing else,
+ string() a String, integer() a Number in its range, the list readers an array - and a value of another type
+ is not an error there: the built-in default comes back, so the key silently does nothing on the TV while set
+ reports it as written. The table states the type of every key, so set reads the value the way that type needs
+ and refuses one the launcher would drop.
+ """
+ cell = (item.get("type") or "").strip()
+ if "config.xml only" in cell:
+ return "config-only"
+ if cell == "bool":
+ return "bool"
+ if cell.startswith("list"):
+ return "list"
+ if cell == "object":
+ return "object"
+ if re.fullmatch(r"\d+(?:\.\d+)? to \d+(?:\.\d+)?", cell):
+ return "number"
+ return "string" if cell else None
+
+
+def value_as(key, item, text):
+ """The argument read the way the key's type needs, or a refusal naming what the key takes."""
+ kind = declared_kind(item)
+ if kind == "config-only":
+ sys.exit(f"{key} is only read from config.xml, not from a theme, so a theme push cannot set it")
+ if kind == "bool":
+ if text.strip().lower() not in ("true", "false"):
+ sys.exit(f"{key} is a bool, so pass true or false, not {text}")
+ return text.strip().lower() == "true"
+ if kind in (None, "string"):
+ try:
+ parsed = json.loads(text)
+ except ValueError:
+ return text
+ # A string key is read as a String only, so `set greeting_name 42` means the text 42, not a number.
+ return parsed if isinstance(parsed, str) else text
+ try:
+ parsed = json.loads(text)
+ except ValueError:
+ parsed = None
+ wanted = {"list": list, "object": dict, "number": (int, float)}[kind]
+ # A Python bool is an int, so it would pass the number test while the launcher's integer() drops it.
+ if not isinstance(parsed, wanted) or isinstance(parsed, bool):
+ example = {"list": '["a", "b"]', "object": '{"key": "value"}', "number": "6"}[kind]
+ sys.exit(f"{key} takes {item.get('type')}, so pass {example}, not {text}")
+ return parsed
+
+
# ---------------------------------------------------------------- the TV
def tv_python():
@@ -262,15 +317,13 @@ def cmd_remove(name):
def cmd_set(key, value, theme_folder):
- if not find(key) or find(key)["kind"] != "switch":
+ item = find(key)
+ 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)")
- try:
- parsed = json.loads(value)
- except ValueError:
- parsed = value
+ 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