Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions host-setup/linux/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
156 changes: 144 additions & 12 deletions host-setup/linux/install-tools.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -48,6 +49,7 @@ REPO=""
declare -A REPO_PACKAGES=()
declare -A REPO_KEYS=()
NOTES=()
NOTE_TEXTS=()
FAILED=()
CHANGED=()

Expand All @@ -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'
Expand All @@ -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
Expand All @@ -94,13 +172,21 @@ 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
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
Expand Down Expand Up @@ -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:"
Expand Down Expand Up @@ -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 ;;
Expand All @@ -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"
Expand Down
2 changes: 2 additions & 0 deletions host-setup/windows/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down
65 changes: 57 additions & 8 deletions host-setup/windows/install-tools.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -51,13 +52,15 @@ $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
$REPO = $Repo
$ELEVATED = $false
$SELECTED = @()
$NOTES = @()
$NOTE_TEXTS = @()
$FAILED = @()
$CHANGED = @()
$EXPLICIT = $null
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:'
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading