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: tv.py answers a mistyped flag before asking for TV_HOST
xbsheng8efef65fbf1b
diff --git a/tests/test_tv_help.py b/tests/test_tv_help.pyindex 6ced33853..c84272b6a 100644--- a/tests/test_tv_help.py+++ b/tests/test_tv_help.py@@ -11,6 +11,12 @@ So -h/--help prints this script's own note, before the adb_shell imports and befand a leading dash that is not a flag of tv.py is refused with the usage (exit 2), before connecting.A shell command's first word is never a dash, so the shell branch is unchanged.+That refusal sat below the TV_HOST check, so without TV_HOST it was never reached: `tv.py --proob` and+`tv.py --push only-two.apk` printed "Set TV_HOST to your TV's IP address" and exited 1 - the status+this client keeps for a command the TV ran and failed - and the reader who set the address they were+told to set then got the usage. The flag, and how many words it takes, is now judged where --help is,+before the client is imported and before TV_HOST, and a checkout with no tools/venv answers it too.+The runs use a stub adb_shell (as tests/test_tv_target.py does) that records whether a device wasopened and every command sent, so "refused before connecting" and "the command still reaches the TV"are both observed rather than assumed. HOME points at a temporary folder so the run does not write an@@ -212,6 +218,78 @@ class TvHelpTest(unittest.TestCase):self.assertIsNone(opened)self.assertEqual([], sent)+ def test_a_flag_it_does_not_have_is_refused_before_the_tv_is_asked_for(self):+ # The reader who has not set TV_HOST yet: this used to be the TV_HOST error and exit 1, so the+ # typo read as a command the TV ran and failed.+ status, out, err, opened, sent = self.run_tv(["--proob"], tv_host=None)+ self.assertEqual(2, status, out)+ self.assertIn("not a flag of tv.py: '--proob'", err)+ self.assertIn("tv.py --probe", err, "the refusal carries the usage")+ self.assertNotIn("Set TV_HOST", err, "a typo is answered from the usage, not with the TV's address")+ self.assertEqual("", out)+ self.assertIsNone(opened)+ self.assertEqual([], sent)++ def test_a_flag_with_the_wrong_number_of_words_is_refused_before_the_tv_is_asked_for(self):+ for args in (["--probe", "extra"], ["--push", "only-two.apk"], ["--pull", "only-two.png"],+ ["--batch", "a", "b"], ["--reboot", "now"]):+ with self.subTest(args=args):+ status, out, err, opened, sent = self.run_tv(args, tv_host=None)+ self.assertEqual(2, status, out)+ self.assertIn("usage:", err)+ self.assertNotIn("Set TV_HOST", err)+ self.assertIsNone(opened)+ self.assertEqual([], sent)++ def test_a_screenshot_with_no_file_is_refused_before_the_tv_is_asked_for(self):+ status, out, err, opened, sent = self.run_tv(["--screenshot"], tv_host=None)+ self.assertEqual(2, status, out)+ self.assertIn("--screenshot needs the file to save to", err)+ self.assertNotIn("Set TV_HOST", err)+ self.assertIsNone(opened)+ self.assertEqual([], sent)++ def test_a_well_formed_command_still_says_which_address_is_missing(self):+ # The other half: a command that is right about itself is still the TV_HOST message, and 1.+ for args in (["--probe"], ["--push", "a.apk", "/data/local/tmp/a.apk"],+ ["pm", "list", "packages"]):+ with self.subTest(args=args):+ status, out, err, opened, sent = self.run_tv(args, tv_host=None)+ self.assertEqual(1, status, out)+ self.assertIn("Set TV_HOST to your TV's IP address", err)+ self.assertEqual("", out)+ self.assertIsNone(opened)+ self.assertEqual([], sent)++ def test_another_script_that_imports_the_client_keeps_its_own_arguments(self):+ # recovery.py, privacy.py and bench.py import this file: their command line is not tv.py's, so+ # the flag check above is tv.py's own run only.+ work = Path(tempfile.mkdtemp(dir=Path(self._tmp.name)))+ importer = work / "importer.py"+ importer.write_text("import tv\nprint('imported', tv.USAGE.splitlines()[0])\n", encoding="utf-8")+ env = {k: v for k, v in os.environ.items() if k not in ("TV_HOST", "TV_PORT", "PYTHONPATH")}+ env["HOME"] = str(self.home)+ if os.name == "nt":+ env["USERPROFILE"] = str(self.home)+ env["PYTHONPATH"] = os.pathsep.join([str(ROOT / "tools"), str(self.base)])+ env["TV_HOST"] = "192.0.2.1"+ r = subprocess.run([sys.executable, str(importer), "--proob", "only-one"], cwd=str(ROOT), env=env,+ capture_output=True, text=True)+ self.assertEqual(0, r.returncode, r.stderr)+ self.assertIn("imported usage:", r.stdout)+ self.assertNotIn("not a flag of tv.py", r.stderr)++ def test_the_flag_check_is_read_before_the_client_and_before_tv_host(self):+ lines = SCRIPT.read_text(encoding="utf-8").splitlines()+ call = next(n for n, l in enumerate(lines) if l.startswith(" check_flags(sys.argv"))+ client = next(n for n, l in enumerate(lines) if l.lstrip().startswith("from adb_shell"))+ host = next(n for n, l in enumerate(lines) if 'os.environ.get("TV_HOST")' in l)+ self.assertLess(call, client, "the flag check must run before adb_shell is imported")+ self.assertLess(call, host, "the flag check must run before TV_HOST is required")+ source = "\n".join(lines)+ self.assertEqual(1, source.count("def check_flags"), "one flag check, called from both places")+ self.assertIn("\n check_flags(args)\n", source, "check_arity() runs it too, for an importer")+def test_the_help_branch_is_read_before_the_client_is_imported(self):# The claim in the docstring is that no venv is needed, which only holds while the branch sits# above the adb_shell imports (and above the TV_HOST check, which exits at import time).diff --git a/tools/tv.py b/tools/tv.pyindex e40e58e78..6a59f0500 100755--- a/tools/tv.py+++ b/tools/tv.py@@ -13,8 +13,9 @@ Set TV_HOST to the TV's IP (or IP:port). Usage:tv.py --help this text; needs neither the venv nor a TVExit status: 0 the command ran (the TV's own answer is in its output), 1 the screenshot came back-empty or failed, 2 it was refused before anything ran on the TV - a flag it does not have, a local-path that cannot be used, a port it could not open.+empty or failed, 2 it was refused before anything ran on the TV - a flag it does not have, one of its+own with the wrong number of words, a local path that cannot be used, a port it could not open. A flag+and its count are judged before TV_HOST is read, so a typo names the usage instead of the TV's address.Set TV_ADB_BINARY to the Google adb executable to use an already connected, paired transport(including encrypted Wireless debugging). See tools/native-adb.md.@@ -33,6 +34,55 @@ if sys.argv[1:2] and sys.argv[1] in ("-h", "--help"):print((__doc__ or "").strip())sys.exit(0)+USAGE = """usage:+ tv.py --probe+ tv.py --screenshot <local.png> [KEY ...] [--wait SECONDS]+ tv.py --push <local> <remote>+ tv.py --pull <remote> <local>+ tv.py --batch < commands.txt+ tv.py --reboot+ tv.py --help+ tv.py <shell command...>+"""+# Arguments each known flag takes, the flag included. The shell branch takes anything, so a flag+# with the wrong count listed here is a typo, not a command for the TV.+# --screenshot takes its file and then any number of keys, so it is checked by screenshot_args instead.+ARITY = {"--probe": 1, "--push": 3, "--pull": 3, "--batch": 1, "--reboot": 1}+++def usage_error(message):+ sys.stderr.write(f"{message}\n{USAGE}")+ sys.exit(2)+++def check_flags(args):+ """A flag tv.py does not have, or one of its own with the wrong number of words, before TV_HOST.++ The TV_HOST check below exits at import time, so a command line that is wrong could only ever be+ answered with the TV's address: `--proob` and `--push only-two.apk` both printed "Set TV_HOST to+ your TV's IP address" and exited 1 - the status this client keeps for a command the TV ran and+ failed, while the docstring's 2 is "refused before anything ran on the TV" - and the reader who+ set the address they were told to set then got the usage. A typo in a flag is answered from the+ usage, which needs neither the venv nor a TV, so it is judged here beside -h/--help.+ """+ if args and args[0] in ARITY and len(args) != ARITY[args[0]]:+ sys.stderr.write(USAGE)+ sys.exit(2)+ if not args or not args[0].startswith("-"):+ return # a shell command, or the bare run that is a probe+ if args[0] == "--screenshot":+ if len(args) == 1:+ usage_error("--screenshot needs the file to save to")+ return+ if args[0] not in ARITY:+ usage_error(f"not a flag of tv.py: {args[0]!r}")+++if __name__ == "__main__":+ # Only tv.py's own command line: recovery.py, privacy.py, bench.py and the tests import this file,+ # and the words their commands take are not this script's flags.+ check_flags(sys.argv[1:])+# The docs type `tools/tv.py ...`, which starts the first python3 on PATH, and that one seldom has# adb_shell: the README installs it into tools/venv only. Run that way, tv.py starts again under the# venv's Python, or says how to make the venv, instead of ending in a ModuleNotFoundError traceback.@@ -294,21 +344,6 @@ def connect_error(e):return None-USAGE = """usage:- tv.py --probe- tv.py --screenshot <local.png> [KEY ...] [--wait SECONDS]- tv.py --push <local> <remote>- tv.py --pull <remote> <local>- tv.py --batch < commands.txt- tv.py --reboot- tv.py --help- tv.py <shell command...>-"""-# Arguments each known flag takes, the flag included. The shell branch takes anything, so a flag-# with the wrong count listed here is a typo, not a command for the TV.-# --screenshot takes its file and then any number of keys, so it is checked by screenshot_args instead.-ARITY = {"--probe": 1, "--push": 3, "--pull": 3, "--batch": 1, "--reboot": 1}-# screencap writes the PNG on the TV and we pull the file afterwards: adb_shell's shell() decodes# what comes back as text, which corrupts an image, and `exec-out screencap -p` returns a broken# PNG on some MediaTek sets (docs/TROUBLESHOOTING.md). /data/local/tmp is writable from shell.@@ -329,21 +364,17 @@ WAIT_MAX_S = 300.0def check_arity(args):- """Reject a known flag with the wrong argument count before connecting.+ """Judge --screenshot's arguments and the two paths of --push/--pull before the TV is opened.- Without this, `--screenshot` with a destination missing falls through to the shell branch and- the TV tries to run `--screenshot` as a command. The same goes for a flag this script does not- have at all: `--proob` used to be sent to the TV, whose shell answered "inaccessible or not- found" while tv.py exited 0, so a mistyped flag looked like a command that ran."""- if args and args[0] in ARITY and len(args) != ARITY[args[0]]:- sys.stderr.write(USAGE)- sys.exit(2)+ The flag itself, and how many words it takes, is check_flags() above, which runs before TV_HOST is+ read. What is left here is the file a flag takes: `--screenshot` with its destination missing would+ otherwise fall through to the shell branch and the TV would try to run `--screenshot` as a command.+ """+ check_flags(args)if args and args[0] == "--screenshot":screenshot_args(args[1:])elif args and args[0] in ("--push", "--pull"):transfer_args(args)- elif args and args[0].startswith("-") and args[0] not in ARITY:- usage_error(f"not a flag of tv.py: {args[0]!r}")def transfer_args(args):@@ -477,11 +508,6 @@ def screenshot_args(rest):return local, keys, wait-def usage_error(message):- sys.stderr.write(f"{message}\n{USAGE}")- sys.exit(2)--def path_error(message):"""Refuse a path that cannot be used, before anything is sent. Exit 2, no usage block.