Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / install.bat

install.bat664 lines · 28.2 KiBRaw
1<# :
2@echo off
3setlocal
4where pwsh >nul 2>nul
5if %errorlevel%==0 ( set "PSBIN=pwsh" ) else ( set "PSBIN=powershell" )
6%PSBIN% -NoProfile -ExecutionPolicy Bypass -Command "$env:_BATROOT='%~dp0'; $env:_BATPATH='%~f0'; & ([scriptblock]::Create((Get-Content -Raw '%~f0'))) %*"
7exit /b %errorlevel%
8: end batch #>
9# install.bat - Ergonomic wrapper around gradlew assemble + adb session install.
10# (PowerShell twin of ./install.)
11#
12# Usage (cmd):
13# install.bat [dev|release] <module> [module...]
14# install.bat <module> [module...] # defaults to dev
15# install.bat [dev|release] all # installs all app modules
16# install.bat all # same, defaults to dev
17# install.bat [dev|release] [8|9] <module> # Pixel 8 or Pixel 9 (by model)
18$ErrorActionPreference = 'Stop'
19
20$InstallRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }
21
22function Show-InstallHelp {
23 @'
24Usage:
25 install.bat [dev|release] <module> [module...]
26 install.bat <module> [module...] # defaults to dev
27 install.bat [dev|release] all # installs all app modules
28 install.bat all # same, defaults to dev
29 install.bat [dev|release] [8|9] <module> # Pixel 8 or Pixel 9 (by model)
30
31Description:
32 Ergonomic wrapper around gradlew :module:assembleDev + adb session install.
33 - Variant is swappable and optional (defaults to dev)
34 - Supports both slash and colon notations: games/voxels == games:voxels
35 - Supports games shorthand: install.bat voxels -> games:voxels (auto-prefixed if games/<name> is a game)
36 - Supports personal shorthand: install.bat dooraccess -> personal:dooraccess (auto-prefixed if personal/<name> is a personal app)
37 - Supports "all" keyword: install.bat all -> installs every app module
38 - Supports multiple modules in one call (single gradlew invocation)
39 - 8|9 selects the Pixel 8 or Pixel 9 by model (optional; defaults to the
40 first non-emulator device). Also accepts --device 8|9 / --device=8|9.
41 - Installs via adb package sessions with the .idsig sidecar staged, so
42 updates to preinstalled MAOS system apps get fs-verity (plain
43 installDev/installRelease and `adb install` never stage it and always fail
44 those updates). Auto-passes -PversionCodeOverride when the on-device
45 package is at the same versionCode as the build: +1 for system apps,
46 exactly the on-device version for user apps.
47
48Examples:
49 install.bat dev contacts -> :contacts:assembleDev + session install
50 install.bat release games:voxels -> :games:voxels:assembleRelease + session install
51 install.bat dev games/voxels -> :games:voxels:assembleDev (slash normalized)
52 install.bat dev :games:voxels: -> :games:voxels:assembleDev (colon trimming)
53 install.bat voxels -> :games:voxels:assembleDev (shorthand auto games:)
54 install.bat chess -> :games:chess:assembleDev (shorthand auto games:)
55 install.bat dooraccess -> :personal:dooraccess:assembleDev (shorthand auto personal:)
56 install.bat all -> :contacts:assembleDev :games:chess:assembleDev ... (all modules)
57 install.bat dev all -> same as above with dev variant
58 install.bat contacts calendar -> :contacts:assembleDev :calendar:assembleDev
59 install.bat release contacts -> :contacts:assembleRelease + session install
60 install.bat contacts dev -> :contacts:assembleDev (variant anywhere)
61 install.bat 9 maps -> :maps:assembleDev + session install to the Pixel 9
62 install.bat dev 8 maps -> :maps:assembleDev + session install to the Pixel 8
63 install.bat --help
64 install.bat --dry-run dev contacts # prints what would run without executing gradle
65 install.bat --dry-run all # preview all modules
66
67Variant rules:
68 - dev (default): assembleDev + session install unless explicitly asked for release
69 - release: assembleRelease + session install when explicitly requested
70 - debug: BLOCKED - never use assembleDebug
71
72Notes:
73 - NEVER uninstalls an app (no uninstall tasks)
74 - Validates modules against app modules (those applying common-conventions-app)
75 - Installs to the first connected device whose serial does not start with 'emulator'
76 (unless 8|9 selects the Pixel 8 or Pixel 9)
77 - Set INSTALL_DRY_RUN=1 or pass --dry-run for dry-run mode
78'@
79}
80
81function Normalize-InstallModule([string]$M) {
82 $M = $M.Trim()
83 $M = [regex]::Replace($M, '^[/:]+', '')
84 $M = [regex]::Replace($M, '[/:]+$', '')
85 $M = $M.Replace('/', ':')
86 while ($M.Contains('::')) { $M = $M.Replace('::', ':') }
87 return $M.ToLowerInvariant()
88}
89
90function Get-InstallAppModulesSlash {
91 $InstallSettings = Join-Path $InstallRoot 'settings.gradle.kts'
92 $InstallFound = @()
93 if (-not (Test-Path -LiteralPath $InstallSettings)) { return $InstallFound }
94 foreach ($InstallLine in [System.IO.File]::ReadLines($InstallSettings)) {
95 if ($InstallLine -match 'include\(":([^"]+)"\)') {
96 $InstallP = $Matches[1].Replace(':', '/')
97 if (-not $InstallP) { continue }
98 $InstallBuild = Join-Path $InstallRoot "$InstallP/build.gradle.kts"
99 if ((Test-Path -LiteralPath $InstallBuild) -and
100 (Select-String -LiteralPath $InstallBuild -Pattern 'id("common-conventions-app")' -SimpleMatch -Quiet)) {
101 $InstallFound += $InstallP
102 }
103 }
104 }
105 return @($InstallFound | Sort-Object -Unique)
106}
107
108function Show-InstallValidModules {
109 $InstallSlash = Get-InstallAppModulesSlash
110 if ($InstallSlash.Count -eq 0) {
111 Write-Output ' (could not discover app modules)'
112 return
113 }
114 Write-Output ''
115 Write-Output 'Valid app modules (slash notation for filesystem, colon for Gradle):'
116 Write-Output ''
117 Write-Output (' {0,-30} {1}' -f 'Filesystem (slash)', 'Gradle (colon)')
118 Write-Output (' {0,-30} {1}' -f '--------------------', '-------------------')
119 foreach ($InstallSm in $InstallSlash) {
120 if (-not $InstallSm) { continue }
121 Write-Output (' {0,-30} :{1}' -f $InstallSm, $InstallSm.Replace('/', ':'))
122 }
123 Write-Output ''
124 Write-Output 'Tip: Use either notation: install.bat dev games/voxels OR install.bat dev games:voxels'
125 Write-Output 'Shorthand: install.bat dev voxels (auto-expands to games:voxels if games/<name> exists)'
126 Write-Output ' install.bat dev dooraccess (auto-expands to personal:dooraccess if personal/<name> exists)'
127 Write-Output 'All: install.bat all (installs every app module)'
128}
129
130function Get-InstallAdb {
131 $InstallAdbCmd = Get-Command adb -ErrorAction SilentlyContinue
132 if ($InstallAdbCmd) { return $InstallAdbCmd.Source }
133 $InstallSdkBases = @()
134 if ($env:ANDROID_HOME) { $InstallSdkBases += $env:ANDROID_HOME }
135 if ($env:ANDROID_SDK_ROOT) { $InstallSdkBases += $env:ANDROID_SDK_ROOT }
136 $InstallSdkBases += (Join-Path $HOME 'Android/Sdk')
137 $InstallSdkBases += (Join-Path $HOME 'Library/Android/sdk')
138 if ($env:LOCALAPPDATA) { $InstallSdkBases += (Join-Path $env:LOCALAPPDATA 'Android/Sdk') }
139 foreach ($InstallBase in $InstallSdkBases) {
140 if (-not $InstallBase) { continue }
141 foreach ($InstallName in @('platform-tools/adb', 'platform-tools/adb.exe')) {
142 $InstallCand = Join-Path $InstallBase $InstallName
143 if (Test-Path -LiteralPath $InstallCand -PathType Leaf) { return $InstallCand }
144 }
145 }
146 return ''
147}
148
149# applicationId for a module (all are string literals in build.gradle.kts).
150function Get-InstallApplicationId([string]$Mod) {
151 $InstallBuild = Join-Path $InstallRoot "$($Mod.Replace(':', '/'))/build.gradle.kts"
152 if (-not (Test-Path -LiteralPath $InstallBuild)) { return '' }
153 foreach ($InstallLine in [System.IO.File]::ReadLines($InstallBuild)) {
154 if ($InstallLine -match '^\s*applicationId\s*=\s*"([^"]+)"') { return $Matches[1] }
155 }
156 return ''
157}
158
159# APK built for a module; output-metadata.json names the file authoritatively
160# (nested modules like cast:tv build tv-dev.apk, not cast-tv-dev.apk).
161function Get-InstallBuiltApk([string]$Mod, [string]$VariantLc) {
162 $InstallFs = $Mod.Replace(':', '/')
163 $InstallOutDir = Join-Path $InstallRoot "$InstallFs/build/outputs/apk/$VariantLc"
164 $InstallMeta = Join-Path $InstallOutDir 'output-metadata.json'
165 $InstallBaseName = ($Mod -split ':')[-1]
166 $InstallFileName = "$InstallBaseName-$VariantLc.apk"
167 if (Test-Path -LiteralPath $InstallMeta -PathType Leaf) {
168 $InstallMetaText = [System.IO.File]::ReadAllText($InstallMeta)
169 $InstallM = [regex]::Match($InstallMetaText, '"outputFile"\s*:\s*"([^"]+)"')
170 if ($InstallM.Success -and $InstallM.Groups[1].Value) { $InstallFileName = $InstallM.Groups[1].Value }
171 }
172 $InstallApk = Join-Path $InstallOutDir $InstallFileName
173 if (Test-Path -LiteralPath $InstallApk -PathType Leaf) { return $InstallApk }
174 return ''
175}
176
177# --- Handle zero args early ---
178if ($args.Count -eq 0) {
179 Show-InstallHelp
180 Write-Output ''
181 Write-Output 'Error: No modules specified.'
182 Show-InstallValidModules
183 exit 1
184}
185
186# --- Detect --help/-h/help anywhere ---
187foreach ($InstallA in $args) {
188 if ($InstallA -eq '--help' -or $InstallA -eq '-h' -or $InstallA -eq 'help') {
189 Show-InstallHelp
190 exit 0
191 }
192}
193
194# --- Early DRY_RUN detection ---
195$InstallDryRun = ($env:INSTALL_DRY_RUN -eq '1')
196foreach ($InstallA in $args) {
197 if ([string]$InstallA -eq '--dry-run') { $InstallDryRun = $true }
198}
199
200# --- Build FILTERED_ARGS (exclude --dry-run) ---
201$InstallFiltered = @()
202foreach ($InstallA in $args) {
203 if ([string]$InstallA -eq '--dry-run') { continue }
204 $InstallFiltered += [string]$InstallA
205}
206if ($InstallFiltered.Count -eq 0) {
207 Show-InstallHelp
208 Write-Output ''
209 Write-Output 'Error: No modules specified (dry-run mode).'
210 Show-InstallValidModules
211 exit 1
212}
213
214# --- Device hint: bare 8|9 anywhere, or --device 8|9 / --device=8|9 (optional) ---
215$InstallDeviceHint = ''
216$InstallPrescan = @()
217$InstallIdx = 0
218while ($InstallIdx -lt $InstallFiltered.Count) {
219 $InstallArg = $InstallFiltered[$InstallIdx]
220 $InstallLc = $InstallArg.ToLowerInvariant()
221 if ($InstallLc -eq '--device') {
222 if ($InstallIdx + 1 -ge $InstallFiltered.Count) {
223 Write-Output 'Error: --device requires a value: 8 (Pixel 8) or 9 (Pixel 9).'
224 exit 1
225 }
226 $InstallDeviceHint = $InstallFiltered[$InstallIdx + 1].ToLowerInvariant()
227 $InstallIdx += 2
228 continue
229 }
230 elseif ($InstallLc -like '--device=*') {
231 $InstallDeviceHint = $InstallLc.Substring('--device='.Length)
232 $InstallIdx++
233 continue
234 }
235 elseif ($InstallLc -eq '8' -or $InstallLc -eq '9') {
236 $InstallDeviceHint = $InstallLc
237 $InstallIdx++
238 continue
239 }
240 elseif ($InstallLc -match '^[0-9]+$') {
241 Write-Output "Error: Invalid device '$InstallArg'. Use 8 (Pixel 8) or 9 (Pixel 9)."
242 exit 1
243 }
244 $InstallPrescan += $InstallArg
245 $InstallIdx++
246}
247$InstallFiltered = $InstallPrescan
248if ($InstallDeviceHint -and ($InstallDeviceHint -ne '8') -and ($InstallDeviceHint -ne '9')) {
249 Write-Output "Error: Invalid device '$InstallDeviceHint'. Use 8 (Pixel 8) or 9 (Pixel 9)."
250 exit 1
251}
252
253# --- Arg parsing: variant detection anywhere ---
254$InstallVariantLc = ''
255$InstallModulesRaw = @()
256foreach ($InstallArg in $InstallFiltered) {
257 $InstallLc = $InstallArg.ToLowerInvariant()
258 if (($InstallLc -eq 'dev') -or ($InstallLc -eq 'release') -or ($InstallLc -eq 'debug')) {
259 if (-not $InstallVariantLc) {
260 $InstallVariantLc = $InstallLc
261 }
262 elseif ($InstallVariantLc -ne $InstallLc) {
263 Write-Output "Error: Multiple distinct variants specified: '$InstallVariantLc' and '$InstallLc'."
264 Write-Output 'Please specify only one variant: dev or release.'
265 Write-Output ''
266 Show-InstallHelp
267 exit 1
268 }
269 }
270 else {
271 $InstallModulesRaw += $InstallArg
272 }
273}
274if (-not $InstallVariantLc) { $InstallVariantLc = 'dev' }
275
276if ($InstallVariantLc -eq 'debug') {
277 Write-Output "Error: 'debug' variant is blocked."
278 Write-Output ''
279 Write-Output ' - Never assemble or install a debug variant'
280 Write-Output ' - Always install the dev build, unless specifically asked for release'
281 Write-Output ''
282 Write-Output 'Use ''dev'' (default) or ''release'' instead:'
283 Write-Output ' install.bat dev <module>'
284 Write-Output ' install.bat release <module>'
285 exit 1
286}
287
288if ($InstallModulesRaw.Count -eq 0) {
289 Write-Output "Error: No modules specified (only variant '$InstallVariantLc' found)."
290 Write-Output ''
291 Show-InstallHelp
292 Show-InstallValidModules
293 exit 1
294}
295
296# --- Normalization + Dedup + Shorthand + "all" + auto games: prefix ---
297# (dedup via hashtable: insertion-ordered enumeration is NOT relied on; order
298# follows first-seen via a companion list.)
299$InstallNormalized = @()
300$InstallSeenNorm = @{}
301$InstallAllExpanded = $false
302foreach ($InstallRaw in $InstallModulesRaw) {
303 $InstallNorm = Normalize-InstallModule $InstallRaw
304 if (-not $InstallNorm) {
305 Write-Output "Warning: Skipping empty/invalid module token '$InstallRaw' after normalization."
306 continue
307 }
308
309 if ($InstallNorm -eq 'all') {
310 if (-not $InstallAllExpanded) {
311 Write-Output "Info: Expanding 'all' to all app modules..."
312 $InstallAllSlash = Get-InstallAppModulesSlash
313 if ($InstallAllSlash.Count -eq 0) {
314 Write-Output "Error: Could not discover app modules for 'all' expansion."
315 Show-InstallValidModules
316 exit 1
317 }
318 foreach ($InstallSm in $InstallAllSlash) {
319 if (-not $InstallSm) { continue }
320 $InstallColon = $InstallSm.Replace('/', ':')
321 if (-not $InstallSeenNorm.ContainsKey($InstallColon)) {
322 $InstallSeenNorm[$InstallColon] = $true
323 $InstallNormalized += $InstallColon
324 }
325 }
326 $InstallAllExpanded = $true
327 }
328 continue
329 }
330
331 # Auto games:/personal: prefix
332 if (-not $InstallNorm.Contains(':')) {
333 foreach ($InstallAutoPrefix in @('games', 'personal')) {
334 $InstallPrefPath = Join-Path $InstallRoot "$InstallAutoPrefix/$InstallNorm"
335 $InstallPrefBuild = Join-Path $InstallPrefPath 'build.gradle.kts'
336 $InstallRootAsDir = Join-Path $InstallRoot $InstallNorm
337 if ((Test-Path -LiteralPath $InstallPrefBuild) -and
338 (Select-String -LiteralPath $InstallPrefBuild -Pattern 'id("common-conventions-app")' -SimpleMatch -Quiet)) {
339 $InstallExpanded = "$InstallAutoPrefix`:$InstallNorm"
340 Write-Output "Info: Expanding shorthand '$InstallRaw' ($InstallNorm) -> $InstallExpanded (found $InstallAutoPrefix/$InstallNorm)"
341 $InstallNorm = $InstallExpanded
342 break
343 }
344 elseif ((-not (Test-Path -LiteralPath $InstallRootAsDir)) -and (Test-Path -LiteralPath $InstallPrefPath)) {
345 $InstallExpanded = "$InstallAutoPrefix`:$InstallNorm"
346 Write-Output "Info: Expanding shorthand '$InstallRaw' ($InstallNorm) -> $InstallExpanded (found $InstallAutoPrefix/$InstallNorm)"
347 $InstallNorm = $InstallExpanded
348 break
349 }
350 }
351 }
352
353 if (-not $InstallSeenNorm.ContainsKey($InstallNorm)) {
354 $InstallSeenNorm[$InstallNorm] = $true
355 $InstallNormalized += $InstallNorm
356 }
357}
358
359if ($InstallNormalized.Count -eq 0) {
360 Write-Output 'Error: No valid modules after normalization.'
361 Show-InstallValidModules
362 exit 1
363}
364
365# --- Validation ---
366$InstallInvalid = @()
367foreach ($InstallMod in $InstallNormalized) {
368 $InstallFsPath = $InstallMod.Replace(':', '/')
369 $InstallFullPath = Join-Path $InstallRoot $InstallFsPath
370 $InstallBuildFile = Join-Path $InstallFullPath 'build.gradle.kts'
371 if (-not (Test-Path -LiteralPath $InstallBuildFile)) {
372 $InstallInvalid += "$InstallMod (not found: $InstallFsPath/build.gradle.kts)"
373 }
374 elseif (-not (Select-String -LiteralPath $InstallBuildFile -Pattern 'id("common-conventions-app")' -SimpleMatch -Quiet)) {
375 $InstallInvalid += "$InstallMod (exists but is not an app module - missing common-conventions-app)"
376 }
377}
378if ($InstallInvalid.Count -gt 0) {
379 Write-Output 'Error: Some modules are invalid:'
380 foreach ($InstallBad in $InstallInvalid) { Write-Output " - $InstallBad" }
381 Show-InstallValidModules
382 exit 1
383}
384
385# --- Build Gradle tasks (assemble only; install happens below via adb sessions) ---
386$InstallVariantCap = $InstallVariantLc.Substring(0, 1).ToUpperInvariant() + $InstallVariantLc.Substring(1)
387$InstallTasks = @()
388foreach ($InstallMod in $InstallNormalized) {
389 $InstallTasks += ":${InstallMod}:assemble${InstallVariantCap}"
390}
391
392Write-Output "Variant: $InstallVariantLc (assemble + adb session install)"
393Write-Output "Modules ($($InstallNormalized.Count)): $($InstallNormalized -join ' ')"
394Write-Output "Gradle tasks: $($InstallTasks -join ' ')"
395Write-Output ''
396
397# --- Device selection: first connected device whose serial doesn't start with 'emulator' ---
398$InstallAdbBin = Get-InstallAdb
399$InstallTargetSerial = ''
400if ($InstallAdbBin) {
401 # hint '' = first non-emulator device; '8' = model Pixel_8;
402 # '9' = model Pixel_9* (covers Pixel_9 and Pixel_9_Pro_XL).
403 $InstallPrevPref = $ErrorActionPreference
404 $ErrorActionPreference = 'Continue'
405 $InstallDevLines = & $InstallAdbBin devices -l 2>$null
406 $ErrorActionPreference = $InstallPrevPref
407 foreach ($InstallDevLine in @($InstallDevLines)) {
408 $InstallParts = ([string]$InstallDevLine -split '\s+')
409 if ($InstallParts.Count -lt 2) { continue }
410 $InstallDevSerial = $InstallParts[0]
411 $InstallDevState = $InstallParts[1]
412 if ($InstallDevState -ne 'device') { continue }
413 if ($InstallDevSerial -like 'emulator*') { continue }
414 if ($InstallDevSerial -eq 'List') { continue }
415 if (-not $InstallDeviceHint) {
416 $InstallTargetSerial = $InstallDevSerial
417 break
418 }
419 $InstallDevModel = ''
420 $InstallModelM = [regex]::Match([string]$InstallDevLine, 'model:([^\s]+)')
421 if ($InstallModelM.Success) { $InstallDevModel = $InstallModelM.Groups[1].Value }
422 if (($InstallDeviceHint -eq '8') -and ($InstallDevModel -eq 'Pixel_8')) {
423 $InstallTargetSerial = $InstallDevSerial
424 break
425 }
426 if (($InstallDeviceHint -eq '9') -and ($InstallDevModel -like 'Pixel_9*')) {
427 $InstallTargetSerial = $InstallDevSerial
428 break
429 }
430 }
431}
432
433if (-not $InstallAdbBin) {
434 if ($InstallDryRun) {
435 Write-Output '[DRY-RUN] Warning: adb not found; a device could not be selected.'
436 }
437 else {
438 Write-Output 'Error: adb not found; cannot select a target device.'
439 Write-Output 'Install Android platform-tools and put adb on PATH (or set ANDROID_HOME).'
440 exit 1
441 }
442}
443elseif ($InstallTargetSerial) {
444 $env:ANDROID_SERIAL = $InstallTargetSerial
445 if ($InstallDeviceHint) {
446 Write-Output "Target device: $($env:ANDROID_SERIAL) (Pixel $InstallDeviceHint)"
447 }
448 else {
449 Write-Output "Target device: $($env:ANDROID_SERIAL) (first connected device not starting with 'emulator')"
450 }
451}
452elseif ($InstallDeviceHint) {
453 Write-Output "Error: No connected Pixel $InstallDeviceHint found (check 'adb devices')."
454 exit 1
455}
456elseif ($InstallDryRun) {
457 Write-Output '[DRY-RUN] Warning: no non-emulator device connected; ANDROID_SERIAL not set.'
458}
459else {
460 Write-Output 'Error: No non-emulator device connected.'
461 Write-Output "Connect a physical device (check 'adb devices'); refusing to install to an emulator."
462 exit 1
463}
464
465# --- Extra Gradle args: --continue so one broken module doesn't block the rest ---
466$InstallGradleArgs = @('--continue')
467$InstallGradleArgsStr = ' --continue'
468if (($InstallVariantLc -eq 'release') -and $InstallAllExpanded) {
469 $InstallGradleArgs += '-Pandroid.r8.maxWorkers=8'
470 $InstallGradleArgsStr += ' -Pandroid.r8.maxWorkers=8'
471}
472
473# --- Big-build heap (see ./install comments): escalate only for ALL_EXPANDED ---
474if ($InstallAllExpanded) {
475 $InstallGradleArgs += '-Dorg.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8'
476 $InstallGradleArgs += '--max-workers=32'
477 $InstallGradleArgsStr += ' -Dorg.gradle.jvmargs=<46g-big-build-heap> --max-workers=32'
478}
479
480# --- versionCodeOverride (see ./install comments) ---
481$InstallRepoVersion = [int]([System.IO.File]::ReadLines((Join-Path $InstallRoot 'version.txt')) | Select-Object -First 1).Trim()
482$InstallNeedBump = $InstallRepoVersion
483if ($InstallTargetSerial) {
484 $InstallPrevPref = $ErrorActionPreference
485 $ErrorActionPreference = 'Continue'
486 foreach ($InstallMod in $InstallNormalized) {
487 $InstallPkg = Get-InstallApplicationId $InstallMod
488 if (-not $InstallPkg) { continue }
489 $InstallListOut = & $InstallAdbBin -s $InstallTargetSerial shell pm list packages --show-versioncode $InstallPkg 2>$null
490 $InstallDevV = 0
491 foreach ($InstallListLine in @($InstallListOut)) {
492 $InstallVm = [regex]::Match([string]$InstallListLine, 'versionCode:([0-9]+)')
493 if ($InstallVm.Success) { $InstallDevV = [int]$InstallVm.Groups[1].Value; break }
494 }
495 if (($InstallDevV -gt 0) -and ($InstallDevV -ge $InstallNeedBump)) {
496 $InstallSysOut = & $InstallAdbBin -s $InstallTargetSerial shell pm list packages -s $InstallPkg 2>$null
497 $InstallIsSystem = $false
498 foreach ($InstallSysLine in @($InstallSysOut)) {
499 if ([string]$InstallSysLine.Trim() -eq "package:$InstallPkg") { $InstallIsSystem = $true; break }
500 }
501 if ($InstallIsSystem) { $InstallTarget = $InstallDevV + 1; $InstallKind = 'system app' }
502 else { $InstallTarget = $InstallDevV; $InstallKind = 'user app' }
503 if ($InstallTarget -gt $InstallNeedBump) {
504 $InstallNeedBump = $InstallTarget
505 Write-Output "Info: $InstallPkg is a $InstallKind at versionCode $InstallDevV on-device (>= repo $InstallRepoVersion); will build with -PversionCodeOverride=$InstallTarget."
506 }
507 }
508 }
509 $ErrorActionPreference = $InstallPrevPref
510}
511if ($InstallNeedBump -gt $InstallRepoVersion) {
512 $InstallGradleArgs += "-PversionCodeOverride=$InstallNeedBump"
513 $InstallGradleArgsStr += " -PversionCodeOverride=$InstallNeedBump"
514}
515
516function Install-ApkViaSession([string]$Apk, [string]$PackageId, [string]$AdbBin, [string]$Serial, [string]$Cur = '', [string]$Total = '') {
517 $InstallApkName = Split-Path -Leaf $Apk
518 $InstallApkSize = (Get-Item -LiteralPath $Apk).Length
519 $InstallApkMb = '{0:N1}' -f ($InstallApkSize / 1MB)
520 $InstallDeviceApk = "/data/local/tmp/install_${PackageId}.apk"
521 $InstallPrefix = ''
522 if ($Cur -and $Total) { $InstallPrefix = "[$Cur/$Total] " }
523 Write-Output "$InstallPrefix Installing $PackageId ($InstallApkName, ${InstallApkMb} MB)..."
524 Write-Output " $InstallPrefix[1/4] Pushing APK to device..."
525 $InstallPrevPref = $ErrorActionPreference
526 $ErrorActionPreference = 'Continue'
527 & $AdbBin -s $Serial push $Apk $InstallDeviceApk >$null 2>&1
528 if ($LASTEXITCODE -ne 0) {
529 $ErrorActionPreference = $InstallPrevPref
530 Write-Output " $InstallPrefix Error: adb push failed for $InstallApkName."
531 return $false
532 }
533 Write-Output " $InstallPrefix[2/4] Creating install session..."
534 $InstallCreateOut = & $AdbBin -s $Serial shell pm install-create -r 2>&1
535 $InstallSession = ''
536 $InstallSm = [regex]::Match(($InstallCreateOut -join "`n"), 'created install session \[([0-9]+)\]')
537 if ($InstallSm.Success) { $InstallSession = $InstallSm.Groups[1].Value }
538 if (-not $InstallSession) {
539 Write-Output " $InstallPrefix Error: could not create install session."
540 & $AdbBin -s $Serial shell rm -f $InstallDeviceApk >$null 2>&1
541 $ErrorActionPreference = $InstallPrevPref
542 return $false
543 }
544 # Stage the APK first, then its .idsig sidecar (V4 signature) under the
545 # matching name. PackageManager enables fs-verity from a staged idsig, which
546 # MAOS/GrapheneOS requires for updates to preinstalled system apps. Plain
547 # `adb install` never stages the sidecar, so those updates always fail.
548 Write-Output " $InstallPrefix[3/4] Staging APK into session $InstallSession..."
549 & $AdbBin -s $Serial shell pm install-write -S $InstallApkSize $InstallSession base.apk $InstallDeviceApk >$null 2>&1
550 if ($LASTEXITCODE -ne 0) {
551 Write-Output " $InstallPrefix Error: failed to stage $InstallApkName into session $InstallSession."
552 & $AdbBin -s $Serial shell pm install-abandon $InstallSession >$null 2>&1
553 & $AdbBin -s $Serial shell rm -f $InstallDeviceApk >$null 2>&1
554 $ErrorActionPreference = $InstallPrevPref
555 return $false
556 }
557 $InstallIdsig = "$Apk.idsig"
558 if (Test-Path -LiteralPath $InstallIdsig -PathType Leaf) {
559 $InstallDeviceIdsig = "$InstallDeviceApk.idsig"
560 Write-Output " $InstallPrefix Staging .idsig sidecar..."
561 & $AdbBin -s $Serial push $InstallIdsig $InstallDeviceIdsig >$null 2>&1
562 if ($LASTEXITCODE -eq 0) {
563 $InstallIdsigSize = (Get-Item -LiteralPath $InstallIdsig).Length
564 & $AdbBin -s $Serial shell pm install-write -S $InstallIdsigSize $InstallSession base.apk.idsig $InstallDeviceIdsig >$null 2>&1
565 if ($LASTEXITCODE -ne 0) {
566 Write-Output " $InstallPrefix Warning: could not stage .idsig; system-app updates may fail fs-verity."
567 }
568 }
569 else {
570 Write-Output " $InstallPrefix Warning: could not push .idsig; system-app updates may fail fs-verity."
571 }
572 & $AdbBin -s $Serial shell rm -f $InstallDeviceIdsig >$null 2>&1
573 }
574 else {
575 Write-Output " $InstallPrefix Warning: no .idsig sidecar next to the APK; system-app updates may fail fs-verity."
576 }
577 Write-Output " $InstallPrefix[4/4] Committing install session $InstallSession..."
578 $InstallCommitOut = & $AdbBin -s $Serial shell pm install-commit $InstallSession 2>&1
579 & $AdbBin -s $Serial shell rm -f $InstallDeviceApk >$null 2>&1
580 # `pm install-commit` prints "Success" but exits 0 either way; fail on absence.
581 if (-not (($InstallCommitOut -join "`n") -match '(?im)^Success')) {
582 Write-Output " $InstallPrefix Error: install failed for ${PackageId}: $($InstallCommitOut -join ' ')"
583 $ErrorActionPreference = $InstallPrevPref
584 return $false
585 }
586 if ($Cur -and $Total) {
587 Write-Output " Installed $PackageId. [$Cur/$Total done]"
588 }
589 else {
590 Write-Output " Installed $PackageId."
591 }
592 $ErrorActionPreference = $InstallPrevPref
593 return $true
594}
595
596if ($InstallDryRun) {
597 $InstallGradlewDisp = if (Test-Path -LiteralPath (Join-Path $InstallRoot 'gradlew.bat')) { Join-Path $InstallRoot 'gradlew.bat' } else { Join-Path $InstallRoot 'gradlew' }
598 Write-Output "[DRY-RUN] Would execute: $InstallGradlewDisp $($InstallTasks -join ' ')$InstallGradleArgsStr"
599 foreach ($InstallMod in $InstallNormalized) {
600 $InstallApk = Get-InstallBuiltApk $InstallMod $InstallVariantLc
601 if ($InstallApk) {
602 Write-Output "[DRY-RUN] Would session-install $(Get-InstallApplicationId $InstallMod) from $InstallApk"
603 }
604 else {
605 Write-Output "[DRY-RUN] Would session-install $(Get-InstallApplicationId $InstallMod) (APK expected after assemble)"
606 }
607 }
608 exit 0
609}
610
611# gradlew: gradlew.bat on Windows when present, else extensionless via bash.
612$InstallGradlewBat = Join-Path $InstallRoot 'gradlew.bat'
613$InstallGradlewSh = Join-Path $InstallRoot 'gradlew'
614$InstallBashCmd = Get-Command bash -ErrorAction SilentlyContinue
615$InstallPrevPref = $ErrorActionPreference
616$ErrorActionPreference = 'Continue'
617if (Test-Path -LiteralPath $InstallGradlewBat) {
618 Write-Output "Running: $InstallGradlewBat $($InstallTasks -join ' ')$InstallGradleArgsStr"
619 Write-Output ''
620 & $InstallGradlewBat @InstallTasks @InstallGradleArgs
621 $InstallBuildExit = $LASTEXITCODE
622}
623elseif ($InstallBashCmd -and (Test-Path -LiteralPath $InstallGradlewSh)) {
624 Write-Output "Running: $InstallGradlewSh $($InstallTasks -join ' ')$InstallGradleArgsStr"
625 Write-Output ''
626 & $InstallBashCmd.Source $InstallGradlewSh @InstallTasks @InstallGradleArgs
627 $InstallBuildExit = $LASTEXITCODE
628}
629else {
630 Write-Output 'Error: no Gradle wrapper found (gradlew.bat / gradlew).'
631 exit 1
632}
633$ErrorActionPreference = $InstallPrevPref
634Write-Output ''
635
636# Install whichever APKs were (re)built, even if sibling modules failed (--continue).
637$InstallFailures = 0
638if ($InstallBuildExit -ne 0) {
639 Write-Output 'Warning: assemble reported failures; installing whatever APKs exist.'
640}
641$InstallTotal = $InstallNormalized.Count
642Write-Output ''
643Write-Output "Installing $InstallTotal app(s) to $InstallTargetSerial..."
644$InstallCur = 0
645foreach ($InstallMod in $InstallNormalized) {
646 $InstallCur++
647 $InstallApk = Get-InstallBuiltApk $InstallMod $InstallVariantLc
648 if ($InstallApk) {
649 if (-not (Install-ApkViaSession $InstallApk (Get-InstallApplicationId $InstallMod) $InstallAdbBin $InstallTargetSerial "$InstallCur" "$InstallTotal")) {
650 $InstallFailures++
651 }
652 }
653 else {
654 Write-Output "[$InstallCur/$InstallTotal] Error: no APK found for :${InstallMod} (assemble failed?)."
655 $InstallFailures++
656 }
657}
658Write-Output ''
659if ($InstallFailures -gt 0) {
660 Write-Output "Install complete: $($InstallTotal - $InstallFailures)/$InstallTotal succeeded, $InstallFailures failed."
661 exit 1
662}
663Write-Output "Install complete: $InstallTotal/$InstallTotal installed successfully."
664exit $InstallBuildExit