Skip to content

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

tools: run manager theme operations natively on Windows

Jernej Pangersic68cf00355052
diff --git a/tests/test_manage_set.py b/tests/test_manage_set.py
index db31043e3..82f18003c 100644
--- a/tests/test_manage_set.py
+++ b/tests/test_manage_set.py
@@ -40,6 +40,7 @@ class SetValueTest(unittest.TestCase):
# 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.push.return_value = 0
self.addCleanup(patcher.stop)
def set_key(self, key, value):
@@ -225,6 +226,7 @@ class SetThemeFolderTest(unittest.TestCase):
self.config = self.theme / "config.json"
patcher = mock.patch.object(manage, "run")
self.push = patcher.start()
+ self.push.return_value = 0
self.addCleanup(patcher.stop)
def set_key(self, key="dock_band", value="true", folder=None):
@@ -249,7 +251,8 @@ class SetThemeFolderTest(unittest.TestCase):
with self.subTest(encoding=encoding, newline=newline):
self.config.write_bytes(text.replace("\n", newline).encode(encoding))
self.push.reset_mock()
- self.assertIsNone(self.set_key("dock_band", "true"))
+ with mock.patch.object(sys, "platform", "linux"):
+ self.assertIsNone(self.set_key("dock_band", "true"))
written = self.config.read_bytes()
self.assertFalse(written.startswith(b"\xef\xbb\xbf"))
updated = json.loads(written.decode("utf-8"))
diff --git a/tests/test_manage_set_arguments.py b/tests/test_manage_set_arguments.py
index 9a5bc8f67..5c15aeb62 100644
--- a/tests/test_manage_set_arguments.py
+++ b/tests/test_manage_set_arguments.py
@@ -92,7 +92,8 @@ class SetArgumentsTest(unittest.TestCase):
self.push.assert_not_called()
def test_the_shape_the_pages_print_still_writes_and_pushes(self):
- status, err = self.run_set("hidden_apps", '["a", "b"]', "--theme", str(self.theme))
+ with mock.patch.object(sys, "platform", "linux"):
+ status, err = self.run_set("hidden_apps", '["a", "b"]', "--theme", str(self.theme))
self.assertEqual(status, 0, err)
self.assertEqual(self.written(), {"hidden_apps": ["a", "b"]})
self.push.assert_called_once_with(
@@ -105,15 +106,12 @@ class SetArgumentsTest(unittest.TestCase):
self.assertEqual(self.written(), {"dock_band": True})
self.push.assert_called_once()
- def test_the_judgement_is_above_the_folder_and_the_push_in_the_source(self):
- source = (ROOT / "tools" / "manage.py").read_text(encoding="utf-8")
- branch = source[source.index('if c == "set":'):source.index("print(__doc__)", source.index('if c == "set":'))]
- self.assertIn("set_args(args)", branch)
- self.assertIn("except Usage", branch)
- self.assertIn("return 2", branch)
- self.assertNotIn("args[1]", branch, "set indexes its arguments without judging the count again")
- self.assertLess(branch.index("except Usage"), branch.index("cmd_set("),
- "the refusal must come before cmd_set reads the folder")
+ def test_invalid_arguments_are_refused_before_the_theme_is_read(self):
+ with mock.patch.object(manage, "theme_config", side_effect=AssertionError("the theme was read")):
+ status, err = self.run_set("hidden_apps", "--theme", str(self.theme))
+ self.assertEqual(status, 2, err)
+ self.assertIsNone(self.written())
+ self.push.assert_not_called()
if __name__ == "__main__":
diff --git a/tests/test_manage_windows.py b/tests/test_manage_windows.py
new file mode 100644
index 000000000..dd0b6d029
--- /dev/null
+++ b/tests/test_manage_windows.py
@@ -0,0 +1,164 @@
+"""Theme operations use the existing PowerShell script on Windows, without needing Bash."""
+import contextlib
+import io
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "tools"))
+import manage # noqa: E402
+
+
+class ThemeDispatchTest(unittest.TestCase):
+ def install(self, platform, executables, extra=(), result=0):
+ out, err = io.StringIO(), io.StringIO()
+ with mock.patch.object(sys, "platform", platform), \
+ mock.patch("shutil.which", side_effect=executables.get), \
+ mock.patch.object(manage.subprocess, "run",
+ return_value=subprocess.CompletedProcess([], result)) as runner, \
+ contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = manage.main(["install", "aurora", *extra])
+ return code, runner, out.getvalue(), err.getvalue()
+
+ def test_windows_installs_with_powershell_without_a_profile_or_policy_bypass(self):
+ code, runner, _, _ = self.install("win32", {"pwsh": r"C:\PowerShell\pwsh.exe"})
+ self.assertEqual(code, 0)
+ runner.assert_called_once_with(
+ [r"C:\PowerShell\pwsh.exe", "-NoProfile", "-NonInteractive", "-File",
+ str(manage.TOOLS / "theme.ps1"), "-Theme", str(ROOT / "themes" / "aurora")],
+ cwd=ROOT)
+
+ def test_windows_can_use_the_bundled_windows_powershell(self):
+ code, runner, _, _ = self.install("win32", {"powershell": r"C:\Windows\powershell.exe"})
+ self.assertEqual(code, 0)
+ self.assertEqual(runner.call_args.args[0][0], r"C:\Windows\powershell.exe")
+
+ def test_unix_keeps_the_existing_bash_command(self):
+ code, runner, _, _ = self.install("linux", {})
+ self.assertEqual(code, 0)
+ runner.assert_called_once_with(
+ ["bash", str(manage.TOOLS / "theme.sh"), str(ROOT / "themes" / "aurora")], cwd=ROOT)
+
+ def test_a_failed_installer_keeps_its_exit_status(self):
+ code, _, _, _ = self.install("win32", {"pwsh": "pwsh"}, result=17)
+ self.assertEqual(code, 17)
+
+ def test_extra_theme_arguments_are_refused_before_any_script_runs(self):
+ for platform in ("win32", "linux"):
+ with self.subTest(platform=platform):
+ code, runner, _, err = self.install(platform, {}, extra=["--reset"])
+ self.assertEqual(code, 2)
+ self.assertIn("--reset", err)
+ runner.assert_not_called()
+
+ def test_an_executable_that_cannot_start_is_reported_without_a_traceback(self):
+ err = io.StringIO()
+ with mock.patch.object(sys, "platform", "win32"), \
+ mock.patch("shutil.which", return_value="pwsh"), \
+ mock.patch.object(manage.subprocess, "run", side_effect=FileNotFoundError("gone")), \
+ contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err):
+ self.assertEqual(manage.main(["install", "aurora"]), 1)
+ self.assertIn("cannot start", err.getvalue())
+ self.assertIn("gone", err.getvalue())
+
+ def test_missing_powershell_does_not_rewrite_a_personal_theme(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ config = Path(tmp) / "config.json"
+ original = '{"columns": 4}\n'
+ config.write_text(original, encoding="utf-8")
+ with mock.patch.object(sys, "platform", "win32"), \
+ mock.patch("shutil.which", return_value=None), \
+ mock.patch.object(manage.subprocess, "run") as runner, \
+ self.assertRaisesRegex(SystemExit, "PowerShell"):
+ manage.main(["set", "columns", "6", "--theme", tmp])
+ self.assertEqual(config.read_text(encoding="utf-8"), original)
+ runner.assert_not_called()
+
+ def test_failed_set_keeps_the_local_edit_and_explains_the_failed_push(self):
+ with tempfile.TemporaryDirectory(prefix="theme with spaces ") as tmp:
+ folder = Path(tmp).resolve()
+ config = folder / "config.json"
+ config.write_text('{"dock_band": true}\n', encoding="utf-8")
+ out, err = io.StringIO(), io.StringIO()
+ with mock.patch.object(sys, "platform", "win32"), \
+ mock.patch("shutil.which", return_value="pwsh"), \
+ mock.patch.object(manage.subprocess, "run",
+ return_value=subprocess.CompletedProcess([], 17)) as runner, \
+ contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = manage.main(["set", "columns", "6", "--theme", str(folder)])
+ self.assertEqual(code, 17)
+ self.assertEqual(json.loads(config.read_text(encoding="utf-8")),
+ {"dock_band": True, "columns": 6})
+ runner.assert_called_once_with(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-File",
+ str(manage.TOOLS / "theme.ps1"), "-Theme", str(folder)], cwd=ROOT)
+ self.assertIn(str(config), err.getvalue())
+ self.assertIn("locally", err.getvalue())
+ self.assertIn("failed", err.getvalue())
+ self.assertIn("17", err.getvalue())
+
+
+class WindowsGuidanceTest(unittest.TestCase):
+ def test_help_and_show_print_windows_commands(self):
+ for args in (["--help"], ["show", "aurora"], ["show", "columns"], ["show", "weather"]):
+ with self.subTest(args=args):
+ out = io.StringIO()
+ with mock.patch.object(sys, "platform", "win32"), contextlib.redirect_stdout(out):
+ self.assertEqual(manage.main(args), 0)
+ text = out.getvalue()
+ self.assertIn(r".\tools\venv\Scripts\python.exe", text)
+ self.assertIn("$env:TV_HOST", text)
+ self.assertNotIn("TV_HOST=<tv ip>", text)
+ self.assertNotIn("tools/venv/bin/python", text)
+
+ def test_a_missing_venv_names_the_windows_setup_commands(self):
+ with tempfile.TemporaryDirectory() as tmp, \
+ mock.patch.object(manage, "TOOLS", Path(tmp)), \
+ mock.patch.object(sys, "platform", "win32"), \
+ self.assertRaises(SystemExit) as stop:
+ manage.tv_python()
+ self.assertIn(r"tools\venv\Scripts\python.exe", str(stop.exception.code))
+ self.assertNotIn("bin/pip", str(stop.exception.code))
+
+
[email protected](os.name == "nt", "real Windows PowerShell subprocesses")
+class WindowsSubprocessTest(unittest.TestCase):
+ def test_each_available_powershell_receives_the_folder_and_returns_failures(self):
+ shells = [path for name in ("pwsh", "powershell") if (path := shutil.which(name))]
+ self.assertTrue(shells, "Windows theme operations need PowerShell on PATH")
+ with tempfile.TemporaryDirectory(prefix="manage scripts ") as tmp:
+ tools = Path(tmp).resolve()
+ theme = tools / "personal theme ' & $name"
+ theme.mkdir()
+ receipt = tools / "received.json"
+ (tools / "theme.ps1").write_text(
+ "param([string]$Theme)\n"
+ "$data = @{ theme = $Theme; extra = @($args) } | ConvertTo-Json -Compress\n"
+ "[System.IO.File]::WriteAllText($env:MANAGE_TEST_RECEIPT, $data)\n"
+ "exit ([int]$env:MANAGE_TEST_EXIT)\n", encoding="utf-8")
+ for shell in shells:
+ for status in (0, 17):
+ with self.subTest(shell=shell, status=status), \
+ mock.patch.object(manage, "TOOLS", tools), \
+ mock.patch("shutil.which", return_value=shell), \
+ mock.patch.dict(os.environ, {"MANAGE_TEST_RECEIPT": str(receipt),
+ "MANAGE_TEST_EXIT": str(status)}), \
+ contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
+ receipt.unlink(missing_ok=True)
+ self.assertEqual(manage.main(
+ ["set", "columns", "6", "--theme", str(theme)]), status)
+ self.assertEqual(json.loads(receipt.read_text(encoding="utf-8")),
+ {"theme": str(theme), "extra": []})
+ self.assertEqual(json.loads((theme / "config.json").read_text(encoding="utf-8")),
+ {"columns": 6})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/themes/README.md b/themes/README.md
index 8bed449ed..55955e67d 100644
--- a/themes/README.md
+++ b/themes/README.md
@@ -14,9 +14,25 @@ powershell -ExecutionPolicy Bypass -File tools\theme.ps1 -TvHost 192.168.1.50 th
`tools/venv/bin/python -I 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 folder of your own
-and pushes it with `theme.sh`. The folder has to be outside this checkout: one under `themes/` or `examples/` is
+and pushes it with `theme.sh` (`theme.ps1` on Windows). 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.
+On Windows, the manager's theme operations need no Bash: they use `pwsh`, or `powershell` if `pwsh` is not on
+PATH, without loading profiles or changing execution policy. If the computer's policy blocks scripts, the
+PowerShell error is reported rather than bypassed. From the repository root in PowerShell:
+
+```powershell
+$env:TV_HOST = '192.168.1.50'
+.\tools\venv\Scripts\python.exe -I .\tools\manage.py list themes
+.\tools\venv\Scripts\python.exe -I .\tools\manage.py install aurora
+Copy-Item .\themes\aurora "$HOME\my-theme" -Recurse
+.\tools\venv\Scripts\python.exe -I .\tools\manage.py set columns 6 --theme "$HOME\my-theme"
+```
+
+`install <theme>` takes only the theme's name, not script arguments. `set` saves the local `config.json`
+before pushing it; if the push fails, the edit stays on disk and the error says the TV may be only partly
+updated. Add-ons with custom shell installers still need Bash; this native Windows support covers themes.
+
| Theme | What it does | Screenshot |
|---|---|---|
| `default/` | The built-in look written out as JSON, as a starting point for your own | <img src="default/screenshot.jpg" width="320" alt="default theme"> |
diff --git a/tools/manage.py b/tools/manage.py
index 354a6c9bc..1eba3fa0c 100644
--- a/tools/manage.py
+++ b/tools/manage.py
@@ -2,7 +2,7 @@
"""One place for the project's add-ons, themes and switches: what each is, its screenshot, what is on the TV,
and installing, updating or removing it the way its creator wrote it down. Nothing is downloaded: everything comes
from this checkout of the repo, and every install runs the creator's own script (an add-on's install.sh or
-build-and-install.sh, or the steps in addons/README.md; tools/theme.sh for themes).
+build-and-install.sh, or the steps in addons/README.md; tools/theme.sh or theme.ps1 for themes).
tools/venv/bin/python -I tools/manage.py list [addons|themes|switches]
tools/venv/bin/python -I tools/manage.py show <add-on, theme or switch>
@@ -12,7 +12,7 @@ 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 a folder in this checkout, so pointing
+pushes it with the platform's theme script, 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
@@ -23,6 +23,11 @@ left over are answered with the usage line and exit 2 before a theme folder is r
show, install and remove read their own words the same way, before anything is read from this checkout or asked
of the TV.
+On Windows, theme install and set use PowerShell (pwsh, or powershell when pwsh is not on PATH), without loading
+profiles or changing execution policy. Add-ons with their own shell installer still need Bash. A theme install
+takes only its name; script arguments belong to add-ons. If set saves the local file but the push fails, it
+reports that separately: the TV may have received only part of the theme.
+
Exit status: 0 the command ran, 1 a command on the TV or a script this checkout runs failed, 2 the command line
asked for something this script does not do - a command it does not have, or a word the command would drop - which
is answered before the READMEs are read or the TV is asked anything.
@@ -31,6 +36,7 @@ import json
import math
import os
import re
+import shutil
import subprocess
import sys
from pathlib import Path
@@ -293,15 +299,28 @@ def theme_config(folder):
# ---------------------------------------------------------------- the TV
+def platform_usage(text):
+ if sys.platform == "win32":
+ return text.replace("TV_HOST=<tv ip> ", "$env:TV_HOST = '<tv ip>'; ").replace(
+ "tools/venv/bin/python -I tools/manage.py",
+ r".\tools\venv\Scripts\python.exe -I .\tools\manage.py")
+ return text
+
+
def tv_python():
for p in (TOOLS / "venv" / "bin" / "python", TOOLS / "venv" / "Scripts" / "python.exe"):
if p.is_file():
return str(p)
+ if sys.platform == "win32":
+ sys.exit(r"run: python -m venv tools\venv; "
+ r".\tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt")
sys.exit("run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt")
def tv(command):
if not os.environ.get("TV_HOST"):
+ if sys.platform == "win32":
+ sys.exit("set $env:TV_HOST to the TV IP address")
sys.exit("set TV_HOST to the TV IP address")
r = subprocess.run([tv_python(), "-I", str(TOOLS / "tv.py"), command], capture_output=True, text=True)
# A failed read is unknown, not empty: never report "not installed" for a TV that didn't answer.
@@ -319,6 +338,23 @@ def run(cmd, cwd):
return subprocess.run(cmd, cwd=cwd).returncode
+def theme_command(folder):
+ if sys.platform == "win32":
+ shell = shutil.which("pwsh") or shutil.which("powershell")
+ if not shell:
+ sys.exit("PowerShell was not found: put pwsh or powershell on PATH. Nothing was written or pushed.")
+ return [shell, "-NoProfile", "-NonInteractive", "-File", str(TOOLS / "theme.ps1"), "-Theme", str(folder)]
+ return ["bash", str(TOOLS / "theme.sh"), str(folder)]
+
+
+def push_theme(command):
+ try:
+ return run(command, ROOT)
+ except OSError as e:
+ sys.stderr.write(f"cannot start {command[0]}: {reason(e)}. Nothing was pushed.\n")
+ return 1
+
+
def install_addon(item, extra):
folder = ROOT / "addons" / item["id"]
if item["script"]:
@@ -371,11 +407,20 @@ def cmd_show(name):
print(f"{k:>12}: {item[k]}")
if item["kind"] == "add-on":
how = item["script"] or "the steps in addons/README.md"
- print(f"{'install':>12}: TV_HOST=<tv ip> tools/venv/bin/python -I tools/manage.py install {item['id']} (runs {how})")
+ if sys.platform == "win32" and item["script"]:
+ how += "; requires Bash"
+ label = "install"
+ instruction = f"TV_HOST=<tv ip> tools/venv/bin/python -I tools/manage.py install {item['id']} (runs {how})"
elif item["kind"] == "theme":
- print(f"{'install':>12}: TV_HOST=<tv ip> tools/theme.sh themes/{item['id']}")
+ label = "install"
+ if sys.platform == "win32":
+ instruction = f"TV_HOST=<tv ip> tools/venv/bin/python -I tools/manage.py install {item['id']}"
+ else:
+ instruction = f"TV_HOST=<tv ip> tools/theme.sh themes/{item['id']}"
else:
- print(f"{'set':>12}: TV_HOST=<tv ip> tools/venv/bin/python -I tools/manage.py set {item['id']} <value> --theme <your theme folder>")
+ label = "set"
+ instruction = f"TV_HOST=<tv ip> tools/venv/bin/python -I tools/manage.py set {item['id']} <value> --theme <your theme folder>"
+ print(f"{label:>12}: {platform_usage(instruction)}")
return 0
@@ -406,7 +451,11 @@ def cmd_install(name, extra):
if not item or item["kind"] == "switch":
sys.exit(f"no add-on or theme called {name}")
if item["kind"] == "theme":
- return run(["bash", str(TOOLS / "theme.sh"), str(ROOT / "themes" / item["id"])] + extra, ROOT)
+ if extra:
+ sys.stderr.write(f"install of a theme takes only its name, not {' '.join(extra)!r}. "
+ "Nothing was pushed.\n")
+ return 2
+ return push_theme(theme_command(ROOT / "themes" / item["id"]))
return install_addon(item, extra)
@@ -431,6 +480,7 @@ def cmd_set(key, value, theme_folder):
if problem:
sys.exit(problem)
parsed = value_as(key, item, value) # before the file is written or anything is pushed
+ command = theme_command(folder)
data[key] = parsed
f = folder / "config.json"
try:
@@ -441,11 +491,15 @@ def cmd_set(key, value, theme_folder):
# 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)
+ code = push_theme(command)
+ if code:
+ sys.stderr.write(f"Saved {f} locally, but the theme push failed (exit {code}). "
+ "The TV may be only partly updated; the local edit was kept.\n")
+ return code
SET_USAGE = ("set takes a switch, its value and --theme <your theme folder>, e.g. "
- "set hidden_apps '[\"a\", \"b\"]' --theme ~/my-theme")
+ "set hidden_apps '[\"a\", \"b\"]' --theme my-theme")
class Usage(Exception):
@@ -535,7 +589,7 @@ def set_args(args):
def main(argv):
if not argv or argv[0] in ("-h", "--help", "help"):
- print(__doc__)
+ print(platform_usage(__doc__))
return 0
c, args = argv[0], argv[1:]
if c == "set":
@@ -546,7 +600,7 @@ def main(argv):
return 2
return cmd_set(key, value, theme)
if c not in WORDS:
- print(__doc__)
+ print(platform_usage(__doc__))
return 2
try:
args = own_words(c, args)