diff --git a/host-setup/linux/README.md b/host-setup/linux/README.md index c7ebfb235..aa4fd1f15 100644 --- a/host-setup/linux/README.md +++ b/host-setup/linux/README.md @@ -57,6 +57,8 @@ A report changes nothing and reads the apt cache as it stands. An available vers `unmanaged` means the tool is installed from the distro while its upstream repository is unconfigured. The one thing the report must not say is that such a tool is current against the distro's own version. The Windows report uses the same word for a different mechanism, a tool on `PATH` that `winget` knows no package for. +`--json` writes the same report as one JSON object, for a program to read instead of the table. It carries a `schema` number, the `platform`, a `tools` list, and a top-level `notes` list for what belongs to no tool. Each entry in `tools` carries `tool`, `installed`, `available`, `source`, `mechanism`, `status`, and that tool's own `notes`, and a version that was not read is `null`. Like `source`, `mechanism` names how this script manages the tool rather than where the installed copy came from. It is `apt` for a tool any apt upgrade moves, and `binary` for a released binary in `/usr/local/bin` that only this script moves. Inside a WSL distribution, `docker` reads `docker-desktop`, since this script leaves it to Docker Desktop. A change to what a field means raises `schema`. + An install or upgrade collects a tool whose install fails and carries on, so one failure does not strand the rest of the run. A refusal is different and ends the run. An unverifiable keyring, a checksum mismatch, or a declined prompt stops everything, because continuing past one would install something nobody vouched for. ## Docker, node, dotnet, and powershell diff --git a/host-setup/linux/install-tools.sh b/host-setup/linux/install-tools.sh index 7edd98b51..ddd0770fe 100755 --- a/host-setup/linux/install-tools.sh +++ b/host-setup/linux/install-tools.sh @@ -32,6 +32,7 @@ readonly PYTHON_OPTIONAL=(python-is-python3 python-dev-is-python3 pipx python3-s MODE="report" DRY_RUN=false +JSON_OUTPUT=false ASSUME_YES=false WITH_OPTIONAL=false APT_REFRESHED=false @@ -48,6 +49,7 @@ REPO="" declare -A REPO_PACKAGES=() declare -A REPO_KEYS=() NOTES=() +NOTE_TEXTS=() FAILED=() CHANGED=() @@ -65,7 +67,82 @@ die() { exit 1 } -note() { NOTES+=("$1: $2"); } +note() { + NOTES+=("$1: $2") + NOTE_TEXTS+=("$2") +} + +json_string() ( + export LC_ALL=C + local s="$1" out="" i n b c cp need min j hi lo + if [[ $s != *[!\ -~]* && $s != *[\"\\]* ]]; then + printf '"%s"' "$s" + return 0 + fi + n=${#s} + for ((i = 0; i < n; i++)); do + printf -v b '%d' "'${s:i:1}" + b=$((b & 0xff)) + if ((b == 34 || b == 92)); then + out+="\\${s:i:1}" + elif ((b < 32)); then + printf -v c '\\u%04x' "$b" + out+=$c + elif ((b < 128)); then + out+=${s:i:1} + else + if ((b >= 0xc2 && b <= 0xdf)); then + need=1 cp=$((b & 0x1f)) min=0x80 + elif ((b >= 0xe0 && b <= 0xef)); then + need=2 cp=$((b & 0x0f)) min=0x800 + elif ((b >= 0xf0 && b <= 0xf4)); then + need=3 cp=$((b & 0x07)) min=0x10000 + else + continue + fi + for ((j = 1; j <= need; j++)); do + ((i + j < n)) || break + printf -v c '%d' "'${s:i+j:1}" + c=$((c & 0xff)) + ((c >= 0x80 && c <= 0xbf)) || break + cp=$(((cp << 6) | (c & 0x3f))) + done + if ((j <= need || cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff))); then + continue + fi + i=$((i + need)) + if ((cp < 0x10000)); then + printf -v c '\\u%04x' "$cp" + else + cp=$((cp - 0x10000)) + hi=$((0xd800 + (cp >> 10))) + lo=$((0xdc00 + (cp & 0x3ff))) + printf -v c '\\u%04x\\u%04x' "$hi" "$lo" + fi + out+=$c + fi + done + printf '"%s"' "$out" +) + +json_value() { + if [[ -n $1 ]]; then + json_string "$1" + else + printf 'null' + fi +} + +json_notes() { + local i sep="" + printf '[' + for ((i = $1; i < $2; i++)); do + printf '%s' "$sep" + json_string "${NOTE_TEXTS[i]}" + sep=", " + done + printf ']' +} usage() { cat <<'EOF' @@ -85,6 +162,7 @@ Actions, name one, default --report: -h, --help Show this help Options: + -j, --json Write the report as JSON rather than a table, for a program to read -n, --dry-run Print the commands instead of running them -y, --yes Do not prompt before changing the host -o, --optional Include the optional tool and the optional package sets, where a tool has one @@ -94,6 +172,13 @@ Versions read as apt versions for an apt-managed tool and as upstream versions f binary, so a column compares like with like. A report reads the apt cache as it stands and does not refresh it, so an available version is as current as the last apt update. +--json writes one object carrying the same rows: "schema" (1), "platform" ("linux"), "tools", one +entry per tool with "tool", "installed", "available", "source", "mechanism", "status" and that +tool's own "notes", and a top-level "notes" for what belongs to no tool. A version that was not +read is null. Like "source", "mechanism" names how this script manages the tool rather than where +the installed copy came from: "apt", which any apt upgrade moves, "binary", which only this script +moves, or "docker-desktop" for docker inside a WSL distribution, which it leaves to Docker Desktop. + --sudo-timestamp writes a sudoers drop-in for the invoking user alone, so one "sudo -v" covers every terminal that user has open rather than only the one it ran in. It touches no tool. Removing the file it names undoes it, and "update-alternatives --auto sudo" undoes the @@ -101,6 +186,7 @@ implementation switch it asks for on a host whose sudo parses no timestamp_type. Examples: install-tools.sh Report on every tool + install-tools.sh --json Report on every tool, as JSON install-tools.sh --install Install what is missing install-tools.sh --upgrade --yes Bring every tool current, no prompt install-tools.sh --upgrade node jq Bring two tools current @@ -1006,33 +1092,74 @@ tool_note() { return 0 } +tool_mechanism() { + case "$1" in + jq | uv | git-restore-mtime) printf 'binary' ;; + docker) + if [[ $IS_WSL == true ]]; then + printf 'docker-desktop' + else + printf 'apt' + fi + ;; + *) printf 'apt' ;; + esac +} + report() { # Wide enough for an Ubuntu backport version, which is the longest of these in practice. local format="%-18s %-26s %-26s %-22s %s\n" - # shellcheck disable=SC2059 # Format string is a constant defined above. - printf "$format" "TOOL" "INSTALLED" "AVAILABLE" "SOURCE" "STATUS" + local -a rows=() + if [[ $JSON_OUTPUT == false ]]; then + # shellcheck disable=SC2059 # Format string is a constant defined above. + printf "$format" "TOOL" "INSTALLED" "AVAILABLE" "SOURCE" "STATUS" + fi if ! command -v curl >/dev/null; then note "report" "curl is not installed, so an upstream that is not an apt repository cannot be read yet" fi + local report_notes=${#NOTES[@]} - local tool installed target + local tool installed target source mechanism status first for tool in "${SELECTED[@]}"; do + first=${#NOTES[@]} if [[ -n ${REPO_PACKAGES[$tool]:-} ]]; then installed=$(apt_installed_version "${REPO_PACKAGES[$tool]}") target=$(apt_candidate_version "${REPO_PACKAGES[$tool]}") + source="apt:${REPO_PACKAGES[$tool]}" + mechanism="apt" + status=$(tool_status "$installed" "$target") + else + installed=$("$(tool_function "$tool" version)" 2>/dev/null || true) + target=$("$(tool_function "$tool" target)" 2>/dev/null || true) + source=$("$(tool_function "$tool" source)") + mechanism=$(tool_mechanism "$tool") + status=$(tool_effective_status "$tool" "$installed" "$target") + fi + if [[ $JSON_OUTPUT == false ]]; then # shellcheck disable=SC2059 # Format string is a constant defined above. - printf "$format" "$tool" "${installed:--}" "${target:--}" "apt:${REPO_PACKAGES[$tool]}" "$(tool_status "$installed" "$target")" - continue + printf "$format" "$tool" "${installed:--}" "${target:--}" "$source" "$status" + fi + [[ -n ${REPO_PACKAGES[$tool]:-} ]] || tool_note "$tool" + if [[ $JSON_OUTPUT == true ]]; then + rows+=("$(printf '{"tool": %s, "installed": %s, "available": %s, "source": %s, "mechanism": %s, "status": %s, "notes": %s}' \ + "$(json_string "$tool")" "$(json_value "$installed")" "$(json_value "$target")" "$(json_string "$source")" \ + "$(json_string "$mechanism")" "$(json_string "$status")" "$(json_notes "$first" "${#NOTES[@]}")")") fi - installed=$("$(tool_function "$tool" version)" 2>/dev/null || true) - target=$("$(tool_function "$tool" target)" 2>/dev/null || true) - # shellcheck disable=SC2059 # Format string is a constant defined above. - printf "$format" "$tool" "${installed:--}" "${target:--}" \ - "$("$(tool_function "$tool" source)")" "$(tool_effective_status "$tool" "$installed" "$target")" - tool_note "$tool" done + if [[ $JSON_OUTPUT == true ]]; then + local i sep="" + printf '{\n "schema": 1,\n "platform": "linux",\n "tools": [' + for ((i = 0; i < ${#rows[@]}; i++)); do + printf '%s\n %s' "$sep" "${rows[i]}" + sep="," + done + [[ ${#rows[@]} -eq 0 ]] || printf '\n ' + printf '],\n "notes": %s\n}\n' "$(json_notes 0 "$report_notes")" + return 0 + fi + [[ ${#NOTES[@]} -eq 0 ]] && return 0 log "" log "Notes:" @@ -1562,6 +1689,7 @@ parse_args() { -u | --upgrade) actions+=(upgrade) ;; -l | --list) actions+=(list) ;; --sudo-timestamp) actions+=(sudo-timestamp) ;; + -j | --json) JSON_OUTPUT=true ;; -n | --dry-run) DRY_RUN=true ;; -y | --yes) ASSUME_YES=true ;; -o | --optional) WITH_OPTIONAL=true ;; @@ -1588,6 +1716,10 @@ parse_args() { fi [[ ${#actions[@]} -eq 1 ]] && MODE="${actions[0]}" + if [[ $JSON_OUTPUT == true && $MODE != "report" ]]; then + die "--json changes how a report is written, so it applies only to --report, and the $MODE action was given" + fi + # The sudo-timestamp refusal needs the whole set of tool names a run asked for, so it is checked after the loop rather than inside it. if [[ $MODE == "sudo-timestamp" && ${#REQUESTED[@]} -gt 0 ]]; then die "--sudo-timestamp changes the host rather than a tool, so it takes no tool, and \"${REQUESTED[*]}\" names one" diff --git a/host-setup/windows/README.md b/host-setup/windows/README.md index df1f48c62..9cd0deb3e 100644 --- a/host-setup/windows/README.md +++ b/host-setup/windows/README.md @@ -110,6 +110,7 @@ This moved a boundary the tool used to hold: WSL used to be read-only here, and | `sudo` re-runs a command as root | nothing elevates | `winget` raises UAC per installer, which is the path with the fewest failures | | `install-tools.sh --sudo-timestamp` shares one sudo credential cache across a user's terminals | no peer | Nothing here elevates on Windows, so there is no cached credential to share | | `unmanaged` means the upstream repository is unconfigured | `unmanaged` means the tool is on `PATH` and winget knows no package for it | The same question, by a different mechanism | +| `--json` reports `mechanism` as `apt`, `binary`, or `docker-desktop` | `-Json` reports `mechanism` as `winget`, `source` as the winget package id, and adds each tool's `scope` list | `winget` is the one package manager here, and scope is the one column Linux has no peer for. The report's shape is otherwise the one the [Linux README][linux-readme] describes, and a `multiple` row's `installed` is `null`, its note naming the versions | | `python-is-python3` supplies the `python` name, under `--optional` | `install-tools.ps1` supplies the `python3` name itself, always | Debian packages the alias and Windows does not, so the one platform installs a package and the other writes the file. This is the only action here that deletes something winget did not install, so it is narrow by construction: it removes an app execution alias only where the reparse tag and the target package both say it is the Microsoft Store placeholder, and reports rather than removes anything else | | `credential.helper cache --timeout=3600` | `credential.helper manager`, and only where unset | Git Credential Manager ships with Git for Windows | | `ssh-agent` is a socket, started per shell | `ssh-agent` is a Windows service, reported and not started | Starting it needs administrator, and nothing here elevates | @@ -157,6 +158,7 @@ The scripts are checked by `PSScriptAnalyzer`, which runs in CI as the peer of t [host-setup]: ../../docs/host-setup.md [host-setup-readme]: ../README.md [install-tools]: ./install-tools.ps1 +[linux-readme]: ../linux/README.md [menu]: ../menu.sh [menu-ps1]: ../menu.ps1 [setup-github]: ./setup-github.ps1 diff --git a/host-setup/windows/install-tools.ps1 b/host-setup/windows/install-tools.ps1 index 8cda91986..a8d34cf09 100644 --- a/host-setup/windows/install-tools.ps1 +++ b/host-setup/windows/install-tools.ps1 @@ -18,6 +18,7 @@ param( [Alias('u')][switch]$Upgrade, [switch]$Reinstall, [Alias('l')][switch]$List, + [Alias('j')][switch]$Json, [Alias('n')][switch]$DryRun, [Alias('y')][switch]$Yes, [Alias('o')][switch]$Optional, @@ -51,6 +52,7 @@ $WANT_TOOLS = @($Name | Where-Object { $_ }) $MODE = 'report' $DRY_RUN = [bool]$DryRun +$JSON_OUTPUT = [bool]$Json $ASSUME_YES = [bool]$Yes $WITH_OPTIONAL = [bool]$Optional $WANT_SCOPE = $Scope @@ -58,6 +60,7 @@ $REPO = $Repo $ELEVATED = $false $SELECTED = @() $NOTES = @() +$NOTE_TEXTS = @() $FAILED = @() $CHANGED = @() $EXPLICIT = $null @@ -70,7 +73,17 @@ function step { param([string]$Message) Write-Host "`n==> $Message" } function warn { param([string]$Message) [Console]::Error.WriteLine("WARNING: $Message") } function die { param([string]$Message) [Console]::Error.WriteLine("ERROR: $Message"); exit 1 } -function note { param([string]$Tool, [string]$Message) $script:NOTES += "${Tool}: $Message" } +function note { + param([string]$Tool, [string]$Message) + $script:NOTES += "${Tool}: $Message" + $script:NOTE_TEXTS += $Message +} + +function Get-NoteText { + param([int]$First, [int]$Last) + if ($Last -le $First) { return , @() } + return , @($script:NOTE_TEXTS[$First..($Last - 1)]) +} # A path with the home directory replaced by the variable that names it. # A report is written to be pasted into an issue or a pull request, so a path it prints carries the account name into wherever it is pasted, and the comments here already avoid writing one for the same reason. @@ -101,12 +114,19 @@ Actions, name one, default -Report: -h, -Help Show this help Options: + -j, -Json Write the report as JSON rather than a table, for a program to read -n, -DryRun Print the commands instead of running them -y, -Yes Do not prompt before changing the host -o, -Optional Include the optional package set, where a tool has one -Scope Name a scope, either user or machine, for the copy to act on -Repo PATH Include winget packages declared by PATH\host-tools.json +-Json writes one object carrying the same rows: "schema" (1), "platform" ("windows"), "tools", +one entry per tool with "tool", "installed", "available", "source" (the winget package id), +"mechanism" ("winget", how this script manages every tool), "status", "scope" and that tool's +own "notes", and a top-level "notes" for what belongs to no tool. A version that was not read, or +that did not resolve to one, is null. + Run this without elevation. No scope is passed unless -Scope names one, so winget acts on the copy it finds and an installer that needs administrator asks for it itself. Naming a scope that disagrees with the installed copy would add a second copy beside the first rather than replacing @@ -120,6 +140,7 @@ prompt, which this refuses to start unattended where nothing could answer it, ra Examples: install-tools.ps1 Report on every tool + install-tools.ps1 -Json Report on every tool, as JSON install-tools.ps1 -Install Install what is missing install-tools.ps1 -Upgrade -Yes Bring every tool current, no prompt install-tools.ps1 -Upgrade uv jq Bring two tools current @@ -1006,23 +1027,48 @@ function Show-List { function Show-Report { $format = '{0,-10} {1,-16} {2,-16} {3,-24} {4,-13} {5}' - log ($format -f 'TOOL', 'INSTALLED', 'AVAILABLE', 'SOURCE', 'SCOPE', 'STATUS') + if (-not $script:JSON_OUTPUT) { log ($format -f 'TOOL', 'INSTALLED', 'AVAILABLE', 'SOURCE', 'SCOPE', 'STATUS') } + $rows = @() foreach ($tool in $script:SELECTED) { + $first = $script:NOTE_TEXTS.Count $record = Get-Tool $tool $state = Get-ToolState -Tool $record # Every row is printed only where they did not resolve to one version, since a dotnet line carrying three side by side builds resolves cleanly and listing all three would overflow the column for nothing. - $installed = if ($state.Status -eq 'multiple') { $state.Rows -join ',' } elseif ($state.Installed) { $state.Installed } else { '-' } - $available = if ($state.Available) { $state.Available } else { '-' } - $scope = if ($state.Scope.Count -gt 0) { $state.Scope -join '+' } else { '-' } - log ($format -f $record.Name, $installed, $available, $state.Package, $scope, $state.Status) + if (-not $script:JSON_OUTPUT) { + $installed = if ($state.Status -eq 'multiple') { $state.Rows -join ',' } elseif ($state.Installed) { $state.Installed } else { '-' } + $available = if ($state.Available) { $state.Available } else { '-' } + $scope = if ($state.Scope.Count -gt 0) { $state.Scope -join '+' } else { '-' } + log ($format -f $record.Name, $installed, $available, $state.Package, $scope, $state.Status) + } Add-ToolNote -Tool $record -State $state + $rows += [ordered]@{ + tool = $record.Name + installed = $(if ($state.Installed) { $state.Installed } else { $null }) + available = $(if ($state.Available) { $state.Available } else { $null }) + source = $state.Package + mechanism = 'winget' + status = $state.Status + scope = @($state.Scope) + notes = (Get-NoteText -First $first -Last $script:NOTE_TEXTS.Count) + } } + $last = $script:NOTE_TEXTS.Count if ($script:ELEVATED) { note 'report' 'this pwsh is elevated, and some installers fail when launched from an elevated process, so an unelevated run is the one to prefer' } + if ($script:JSON_OUTPUT) { + [ordered]@{ + schema = 1 + platform = 'windows' + tools = $rows + notes = (Get-NoteText -First $last -Last $script:NOTE_TEXTS.Count) + } | ConvertTo-Json -Depth 4 -EscapeHandling EscapeNonAscii + return + } + if ($script:NOTES.Count -eq 0) { return } log '' log 'Notes:' @@ -1203,8 +1249,11 @@ function Invoke-Apply { function Resolve-Mode { $given = @($script:ACTIONS.Keys | Where-Object { $script:ACTIONS[$_] }) if ($given.Count -gt 1) { die "More than one action given ($($given -join ', ')), name one" } - if ($given.Count -eq 0) { return 'report' } - return $given[0] + $mode = if ($given.Count -eq 0) { 'report' } else { $given[0] } + if ($script:JSON_OUTPUT -and $mode -ne 'report') { + die "-Json changes how a report is written, so it applies only to -Report, and the $mode action was given" + } + return $mode } function Resolve-Selection { diff --git a/tests/test_install_tools.py b/tests/test_install_tools.py new file mode 100755 index 000000000..5356acec6 --- /dev/null +++ b/tests/test_install_tools.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Tests for the host tool installers' JSON report, on both platforms. + +The JSON report exists so a program can read what the table tells a person, so its contract is the +shape a program parses: every field present on every row, a version that was not read written as +null, and each note filed under the tool that raised it. Each installer's report is driven through +its own functions with the host reads stubbed, since a real report reads the host it runs on. + +Run as `python3 tests/test_install_tools.py`, or under `python3 -m unittest discover -s tests`. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +LINUX_INSTALLER = ROOT / "host-setup" / "linux" / "install-tools.sh" +WINDOWS_INSTALLER = ROOT / "host-setup" / "windows" / "install-tools.ps1" + +AWKWARD = 'a "quoted" back\\slash\ttab\nnewline\rreturn \x01\x1f \u00e9 end' + + +def linux_functions() -> str: + """`install-tools.sh` without its closing `main "$@"`, so a test can source its functions alone.""" + lines = LINUX_INSTALLER.read_text(encoding="utf-8").rstrip("\n").split("\n") + if lines[-1] != 'main "$@"': + raise AssertionError(f"install-tools.sh no longer ends with its main call: {lines[-1]!r}") + return "\n".join(lines[:-1]) + "\n" + + +@unittest.skipUnless(sys.platform == "linux", "drives the Linux installer's own functions") +class TestLinuxJsonReport(unittest.TestCase): + """`install-tools.sh --json`, driven through the script's own functions.""" + + def setUp(self) -> None: + self.dir = Path(self.enterContext(tempfile.TemporaryDirectory())) + self.functions = self.dir / "functions.sh" + self.functions.write_text(linux_functions(), encoding="utf-8") + + def run_bash(self, body: str, argument: str = "") -> subprocess.CompletedProcess[str]: + script = f'source "{self.functions}"\n{body}\n' + return subprocess.run( + ["bash", "-c", script, "bash", argument], + capture_output=True, + text=True, + encoding="utf-8", + check=False, + timeout=30, + ) + + def test_json_string_round_trips_every_escaped_character(self) -> None: + result = self.run_bash('json_string "$1"', AWKWARD) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout), AWKWARD) + + def test_report_writes_each_row_and_files_each_note(self) -> None: + body = f""" +host_path=$PATH +PATH="{self.dir}/empty" +JSON_OUTPUT=true +SELECTED=(jq extra) +REPO_PACKAGES[extra]=extra-package +jq_version() {{ :; }} +jq_target() {{ printf '1.8.2'; }} +apt_installed_version() {{ printf '2.0'; }} +apt_candidate_version() {{ printf '2.0'; }} +tool_note() {{ note "$1" "$AWKWARD"; }} +AWKWARD=$1 +report +PATH=$host_path +""" + result = self.run_bash(body, AWKWARD) + self.assertEqual(result.returncode, 0, result.stderr) + report = json.loads(result.stdout) + self.assertEqual(report["schema"], 1) + self.assertEqual(report["platform"], "linux") + self.assertEqual( + report["tools"], + [ + { + "tool": "jq", + "installed": None, + "available": "1.8.2", + "source": "jqlang/jq", + "mechanism": "binary", + "status": "missing", + "notes": [AWKWARD], + }, + { + "tool": "extra", + "installed": "2.0", + "available": "2.0", + "source": "apt:extra-package", + "mechanism": "apt", + "status": "current", + "notes": [], + }, + ], + ) + self.assertEqual(len(report["notes"]), 1) + self.assertIn("curl is not installed", report["notes"][0]) + + def test_json_string_drops_bytes_that_are_not_utf8(self) -> None: + never_valid = b"\xff" + above_the_last_code_point = b"\xf4\x90\x80\x80" + overlong = b"\xe0\x80\x80" + surrogate = b"\xed\xa0\x80" + truncated = b"\xe2\x82" + lead_before_ascii = b"\xc3" + malformed = ( + b"a" + + never_valid + + above_the_last_code_point + + overlong + + surrogate + + lead_before_ascii + + "b\u00e9\U0001f600".encode() + + truncated + ) + for locale in ("C", "C.UTF-8"): + with self.subTest(locale=locale): + result = subprocess.run( + [ + "bash", + "-c", + f'source "{self.functions}"\njson_string "$1"', + "bash", + malformed, + ], + capture_output=True, + check=False, + timeout=30, + env={"PATH": os.environ["PATH"], "LC_ALL": locale}, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stderr, b"") + self.assertTrue(result.stdout.isascii(), result.stdout) + self.assertEqual(json.loads(result.stdout), "ab\u00e9\U0001f600") + + def test_docker_inside_wsl_names_docker_desktop_as_its_mechanism(self) -> None: + for is_wsl, expected in (("true", "docker-desktop"), ("false", "apt")): + with self.subTest(is_wsl=is_wsl): + result = self.run_bash(f"IS_WSL={is_wsl}\ntool_mechanism docker") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, expected) + + def test_report_with_no_rows_is_still_an_object(self) -> None: + result = self.run_bash("JSON_OUTPUT=true\nSELECTED=()\nreport") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["tools"], []) + + def test_json_is_refused_beside_another_action(self) -> None: + for action in ("--install", "--upgrade", "--list", "--sudo-timestamp"): + with self.subTest(action=action): + result = subprocess.run( + [str(LINUX_INSTALLER), action, "--json"], + capture_output=True, + text=True, + encoding="utf-8", + check=False, + timeout=30, + ) + self.assertEqual(result.returncode, 1) + self.assertIn("--json", result.stderr) + self.assertEqual(result.stdout, "") + + +WINDOWS_HARNESS = r""" +param([string]$Installer, [string]$Awkward, [string]$Mode) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$tokens = $null +$errors = $null +$ast = [System.Management.Automation.Language.Parser]::ParseFile($Installer, [ref]$tokens, [ref]$errors) +$wanted = @('note', 'Get-NoteText', 'Show-Report', 'Resolve-Mode', 'die') +foreach ($definition in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $wanted -contains $node.Name }, $true)) { + . ([scriptblock]::Create($definition.Extent.Text)) +} +function log { param([string]$Message = '') Write-Host $Message } +function info { param([string]$Message) Write-Host " $Message" } +function Get-Tool { param([string]$Name) @{ Name = $Name } } +function Get-ToolState { + param([hashtable]$Tool) + if ($Tool.Name -eq 'jq') { + return @{ Package = 'jqlang.jq'; Installed = $null; Rows = @(); Available = '1.8.2'; Scope = @(); Status = 'missing' } + } + if ($Tool.Name -eq 'dotnet') { + return @{ Package = 'Microsoft.DotNet.SDK.10'; Installed = $null; Rows = @('8.0.1', '10.0.1'); Available = '10.0.1'; Scope = @('machine'); Status = 'multiple' } + } + return @{ Package = 'astral-sh.uv'; Installed = '0.12.4'; Rows = @('0.12.4'); Available = '0.12.4'; Scope = @('user', 'machine'); Status = 'current' } +} +function Add-ToolNote { param([hashtable]$Tool, [hashtable]$State) if ($Tool.Name -eq 'jq') { note 'jq' $Awkward } } +$NOTES = @() +$NOTE_TEXTS = @() +$JSON_OUTPUT = $true +$ELEVATED = $true +$SELECTED = @('jq', 'uv', 'dotnet') +if ($Mode) { + $ACTIONS = [ordered]@{ report = $false; install = $false; list = $false } + $ACTIONS[$Mode] = $true + Resolve-Mode +} else { + Show-Report +} +""" + + +@unittest.skipUnless( + shutil.which("pwsh"), "needs pwsh to drive the Windows installer's own functions" +) +class TestWindowsJsonReport(unittest.TestCase): + """`install-tools.ps1 -Json`, driven through the script's own functions with winget stubbed.""" + + def run_harness(self, mode: str = "") -> subprocess.CompletedProcess[str]: + with tempfile.TemporaryDirectory() as directory: + harness = Path(directory, "harness.ps1") + harness.write_text(WINDOWS_HARNESS, encoding="utf-8") + return subprocess.run( + [ + "pwsh", + "-NoProfile", + "-NonInteractive", + "-File", + str(harness), + "-Installer", + str(WINDOWS_INSTALLER), + "-Awkward", + AWKWARD, + "-Mode", + mode, + ], + capture_output=True, + text=True, + encoding="utf-8", + check=False, + timeout=120, + ) + + def test_report_writes_each_row_and_files_each_note(self) -> None: + result = self.run_harness() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(result.stdout.isascii(), result.stdout) + report = json.loads(result.stdout) + self.assertEqual(report["schema"], 1) + self.assertEqual(report["platform"], "windows") + self.assertEqual( + report["tools"], + [ + { + "tool": "jq", + "installed": None, + "available": "1.8.2", + "source": "jqlang.jq", + "mechanism": "winget", + "status": "missing", + "scope": [], + "notes": [AWKWARD], + }, + { + "tool": "uv", + "installed": "0.12.4", + "available": "0.12.4", + "source": "astral-sh.uv", + "mechanism": "winget", + "status": "current", + "scope": ["user", "machine"], + "notes": [], + }, + { + "tool": "dotnet", + "installed": None, + "available": "10.0.1", + "source": "Microsoft.DotNet.SDK.10", + "mechanism": "winget", + "status": "multiple", + "scope": ["machine"], + "notes": [], + }, + ], + ) + self.assertEqual(len(report["notes"]), 1) + self.assertIn("elevated", report["notes"][0]) + + def test_json_is_refused_beside_another_action(self) -> None: + for mode in ("install", "list"): + with self.subTest(mode=mode): + result = self.run_harness(mode) + self.assertEqual(result.returncode, 1) + self.assertIn("-Json", result.stderr) + + +if __name__ == "__main__": + unittest.main()