From cc812b26c7644c5171b9e4c873c12dbc3ea2b5dd Mon Sep 17 00:00:00 2001 From: ablaszkiewicz Date: Thu, 26 Nov 2026 15:52:07 +0100 Subject: [PATCH 01/14] feat(maven-plugin): add posthog-maven-plugin to upload jvm sources The upload-sources goal runs posthog-cli jvm upload on the project's sources and the source directories of kotlin-maven-plugin, and packages the id they were uploaded under in posthog-meta.properties, which posthog-server reads. The release version defaults to the git commit. When posthog-cli is missing or too old, or no credentials are set, the goal skips with a warning unless requireUpload is set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FkuJA9vNowLRRGH1hbFyhv --- .changeset/maven-plugin-upload-sources.md | 5 + .github/workflows/release.yml | 9 +- AGENTS.md | 1 + Makefile | 6 + README.md | 1 + gradle.properties | 1 + pnpm-lock.yaml | 2 + pnpm-workspace.yaml | 1 + posthog-maven-plugin/README.md | 76 ++++ posthog-maven-plugin/build.gradle.kts | 66 +++ posthog-maven-plugin/gradle.lockfile | 73 +++ posthog-maven-plugin/package.json | 5 + .../java/com/posthog/maven/PostHogCli.java | 111 +++++ .../com/posthog/maven/UploadSourcesMojo.java | 360 +++++++++++++++ .../posthog/maven/UploadSourcesMojoTest.java | 426 ++++++++++++++++++ settings.gradle.kts | 1 + 16 files changed, 1143 insertions(+), 1 deletion(-) create mode 100644 .changeset/maven-plugin-upload-sources.md create mode 100644 posthog-maven-plugin/README.md create mode 100644 posthog-maven-plugin/build.gradle.kts create mode 100644 posthog-maven-plugin/gradle.lockfile create mode 100644 posthog-maven-plugin/package.json create mode 100644 posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java create mode 100644 posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java create mode 100644 posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java diff --git a/.changeset/maven-plugin-upload-sources.md b/.changeset/maven-plugin-upload-sources.md new file mode 100644 index 000000000..03011a025 --- /dev/null +++ b/.changeset/maven-plugin-upload-sources.md @@ -0,0 +1,5 @@ +--- +"posthog-maven-plugin": minor +--- + +Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `posthog-cli jvm upload` to upload the project's sources and writes the id they were uploaded under into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures. When `posthog-cli` is missing or too old, or PostHog credentials are missing, the goal skips the upload with a warning. Set `requireUpload` to fail the build instead. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index de7ef1dd4..dc200b320 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -127,6 +127,7 @@ jobs: SURVEYS_COMPOSE_VERSION=$(node -p "require('./posthog-android-surveys-compose/package.json').version") SERVER_VERSION=$(node -p "require('./posthog-server/package.json').version") SERVER_OPENFEATURE_VERSION=$(node -p "require('./posthog-server-openfeature/package.json').version") + MAVEN_PLUGIN_VERSION=$(node -p "require('./posthog-maven-plugin/package.json').version") PLUGIN_VERSION=$(node -p "require('./posthog-android-gradle-plugin/package.json').version") sed -i "s/^coreVersion=.*/coreVersion=$CORE_VERSION/" gradle.properties @@ -134,6 +135,7 @@ jobs: sed -i "s/^surveysComposeVersion=.*/surveysComposeVersion=$SURVEYS_COMPOSE_VERSION/" gradle.properties sed -i "s/^serverVersion=.*/serverVersion=$SERVER_VERSION/" gradle.properties sed -i "s/^serverOpenFeatureVersion=.*/serverOpenFeatureVersion=$SERVER_OPENFEATURE_VERSION/" gradle.properties + sed -i "s/^mavenPluginVersion=.*/mavenPluginVersion=$MAVEN_PLUGIN_VERSION/" gradle.properties sed -i "s/^androidPluginVersion=.*/androidPluginVersion=$PLUGIN_VERSION/" posthog-android-gradle-plugin/gradle.properties - name: 'Set up Java 17' @@ -192,7 +194,7 @@ jobs: package_name="" package_version="" separator="" - for package_json in posthog/package.json posthog-android/package.json posthog-android-surveys-compose/package.json posthog-server/package.json posthog-server-openfeature/package.json posthog-android-gradle-plugin/package.json; do + for package_json in posthog/package.json posthog-android/package.json posthog-android-surveys-compose/package.json posthog-server/package.json posthog-server-openfeature/package.json posthog-maven-plugin/package.json posthog-android-gradle-plugin/package.json; do if [ -f "$package_json" ]; then package_name_part=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("name", ""))' "$package_json") version=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("version", ""))' "$package_json") @@ -314,6 +316,11 @@ jobs: make_dry_target: dryReleaseServerOpenFeature make_release_target: releaseServerOpenFeature changelog: posthog-server-openfeature/CHANGELOG.md + - name: posthog-maven-plugin + tag_prefix: mavenPlugin + make_dry_target: dryReleaseMavenPlugin + make_release_target: releaseMavenPlugin + changelog: posthog-maven-plugin/CHANGELOG.md - name: posthog-android-gradle-plugin tag_prefix: androidPlugin make_dry_target: dryReleaseAndroidPlugin diff --git a/AGENTS.md b/AGENTS.md index e9090ddbe..7cfea6f72 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,7 @@ PostHog Android SDK monorepo. Kotlin-first, targets JVM and Android. - `posthog-android/` — Android-specific SDK (depends on `posthog/`) - `posthog-android-surveys-compose/` — Compose survey UI (depends on `posthog-android/`, transitively on `posthog/`) - `posthog-server/` — Server-side SDK (depends on `posthog/`) +- `posthog-maven-plugin/` — Maven plugin that uploads JVM sources for error tracking source context (pure Java, runs `posthog-cli`) - `posthog-server-openfeature/` — OpenFeature provider for the server-side SDK (depends on `posthog-server/`, Java 11+) - `posthog-android-gradle-plugin/` — Gradle plugin for Android integrations - `posthog-samples/` — Sample apps diff --git a/Makefile b/Makefile index e13212d66..06afc598d 100644 --- a/Makefile +++ b/Makefile @@ -38,6 +38,9 @@ dryReleaseServer: dryReleaseServerOpenFeature: ./gradlew :posthog-server-openfeature:publishToMavenLocal +dryReleaseMavenPlugin: + ./gradlew :posthog-maven-plugin:publishToMavenLocal + dryReleaseAndroidPlugin: ./gradlew :posthog-android-gradle-plugin:publishToMavenLocal @@ -59,6 +62,9 @@ releaseServer: releaseServerOpenFeature: ./gradlew :posthog-server-openfeature:publishToSonatype closeAndReleaseSonatypeStagingRepository +releaseMavenPlugin: + ./gradlew :posthog-maven-plugin:publishToSonatype closeAndReleaseSonatypeStagingRepository + releaseAndroidPlugin: ./gradlew :posthog-android-gradle-plugin:publishToSonatype :posthog-android-gradle-plugin:closeAndReleaseSonatypeStagingRepository diff --git a/README.md b/README.md index c440f8603..e719c0332 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ | posthog-android-surveys-compose | [![Maven Central](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-android-surveys-compose/badge.svg)](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-android-surveys-compose) | Android API 23 | | posthog (core) | [![Maven Central](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog/badge.svg)](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog) | Java 8 | | posthog-server | [![Maven Central](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-server/badge.svg)](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-server) | Java 8 | +| posthog-maven-plugin | [![Maven Central](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-maven-plugin/badge.svg)](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-maven-plugin) | Maven 3 · Java 8 · `0.x.x` | | posthog-server-openfeature | [![Maven Central](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-server-openfeature/badge.svg)](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-server-openfeature) | Java 11 · `0.x.x` | | posthog-android-gradle-plugin | [![Maven Central](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-android-gradle-plugin/badge.svg)](https://maven-badges.herokuapp.com/sonatype-central/com.posthog/posthog-android-gradle-plugin) | Java 8 | diff --git a/gradle.properties b/gradle.properties index d17781bc4..e087c27cf 100644 --- a/gradle.properties +++ b/gradle.properties @@ -27,6 +27,7 @@ androidVersion=4.0.3 surveysComposeVersion=1.1.0 serverVersion=2.26.1 serverOpenFeatureVersion=0.1.3 +mavenPluginVersion=0.0.0 # Shared build versions (single source of truth for buildSrc, PosthogBuildConfig, and gradle plugin) kotlinVersion=2.1.21 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8c7e72148..ee6f14397 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -20,6 +20,8 @@ importers: posthog-android-surveys-compose: {} + posthog-maven-plugin: {} + posthog-server: {} posthog-server-openfeature: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 0dec79eec..4b36bddd6 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,6 +4,7 @@ packages: - "posthog-android-surveys-compose" - "posthog-server" - "posthog-server-openfeature" + - "posthog-maven-plugin" - "posthog-android-gradle-plugin" minimumReleaseAge: 10080 diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md new file mode 100644 index 000000000..e12fc4341 --- /dev/null +++ b/posthog-maven-plugin/README.md @@ -0,0 +1,76 @@ +# posthog-maven-plugin + +Uploads your application's Java and Kotlin sources to PostHog, so error tracking shows the source code around each frame of the exceptions your app captures. + +On every build, the `upload-sources` goal runs [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) `jvm upload`. The CLI bundles the sources, uploads them under an id derived from their content and the release, and writes that id into `posthog-meta.properties` in a generated resources directory. The file is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads it and sends the id on every exception frame, and PostHog looks up the uploaded sources by that id. + +A build of unchanged code in the same release reuses the existing upload and sends no source files. Changed code, or a new release, gets a new id and a new upload, so exceptions are attributed to the release that threw them. Because the file is written on every build, it always matches the code that was compiled. + +## Requirements + +- [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli), installed with `npm install -g @posthog/cli`, `brew install posthog/tap/posthog-cli`, or the install script. +- `posthog-server` with `posthog-meta.properties` support, and no `releaseIdentifier` set in code (an explicit value wins over the file). +- A personal API key with error tracking write access, for the upload. + +## Usage + +```xml + + + + com.posthog + posthog-maven-plugin + 0.1.0 + + + + upload-sources + + + + + + +``` + +The goal binds to the `generate-resources` phase, so `mvn package` uploads before it packages. + +### Releases + +Each upload belongs to a release, and exceptions are attributed to it. The release name defaults to the artifact id, and the version defaults to the current git commit: `posthog-cli` reads it from the repository, or from the CI environment on GitHub Actions. So every deployed commit is its own release, even when the project version stays at `0.0.1-SNAPSHOT`. A build with no git commit, such as a Docker build that copies only the sources, uploads without a release unless you set `releaseVersion`. Its exceptions still show source code. + +### Credentials + +`posthog-cli` reads them from the environment, from a dotenv file, or from `posthog-cli login`: + +- `POSTHOG_CLI_HOST`: your PostHog app host, for example `https://us.posthog.com` +- `POSTHOG_CLI_PROJECT_ID`: your project id +- `POSTHOG_CLI_API_KEY`: a personal API key with error tracking write access + +To use a dotenv file, set `.env` or pass `-Dposthog.dotenvFile=.env`. + +### Builds without credentials + +When `posthog-cli` is missing or too old to have `jvm upload`, or the credentials are missing, the plugin skips the upload with a warning and the build continues. Developers can build without setting up PostHog. A skipped build ships no id, so its exceptions show no source code. It also deletes the `posthog-meta.properties` an earlier build left behind, so the app never reports an id that belongs to other code. + +In CI, set `true` or pass `-Dposthog.requireUpload=true`. Then a missing or outdated CLI, or a missing token, fails the build instead of shipping a build without source code. A failed upload fails the build either way. + +A developer who has run `posthog-cli login` uploads from local builds too. Pass `-Dposthog.skip=true` to turn the upload off. + +## Parameters + +| Parameter | User property | Default | Description | +|---|---|---|---| +| `skip` | `posthog.skip` | `false` | Skip the upload. | +| `requireUpload` | `posthog.requireUpload` | `false` | Fail the build when `posthog-cli` is missing or too old, or the credentials are missing, instead of skipping the upload. | +| `cliExecutable` | `posthog.cliExecutable` | found automatically | Path to `posthog-cli`. Without it, the plugin checks `~/.posthog/posthog-cli`, then `PATH`, then Homebrew, `~/.cargo/bin` and `~/.local/bin`. | +| `dotenvFile` | `posthog.dotenvFile` | none | A dotenv file `posthog-cli` reads credentials from. | +| `releaseName` | `posthog.releaseName` | `${project.artifactId}` | The release the upload is associated with. | +| `releaseVersion` | `posthog.releaseVersion` | the git commit | The version of that release. Set it to `${project.version}` if you bump the project version on every release. | +| `outputDirectory` | `posthog.outputDirectory` | `${project.build.directory}/generated-resources/posthog` | Where `posthog-meta.properties` is written. The plugin adds it as a resource directory. | +| `sourceRoots` | none | the project's compile source roots, plus the `` of `kotlin-maven-plugin` | The directories to upload. Setting it replaces the default. | + +## What it doesn't cover yet + +- The SDK sends one id, the one in the application's `posthog-meta.properties`. Frames from other modules show source code only when their sources are in that upload, so in a multi-module build, run the goal in the application module and list the other modules' source directories in `sourceRoots`. Frames from a library built somewhere else show no source code. +- GraalVM native images don't include `posthog-meta.properties` unless you register it as a resource. diff --git a/posthog-maven-plugin/build.gradle.kts b/posthog-maven-plugin/build.gradle.kts new file mode 100644 index 000000000..10b26b073 --- /dev/null +++ b/posthog-maven-plugin/build.gradle.kts @@ -0,0 +1,66 @@ +// The generated plugin descriptor takes its groupId from the project, and Maven refuses a plugin +// whose descriptor and coordinates disagree. +group = "com.posthog" +version = properties["mavenPluginVersion"].toString() + +plugins { + `java-library` + + // Generates META-INF/maven/plugin.xml from the @Mojo and @Parameter annotations. + id("org.gradlex.maven-plugin-development") version "1.0.3" + + // publish + `maven-publish` + signing +} + +java { + withSourcesJar() + withJavadocJar() + sourceCompatibility = PosthogBuildConfig.Build.JAVA_VERSION + targetCompatibility = PosthogBuildConfig.Build.JAVA_VERSION +} + +mavenPlugin { + name.set("PostHog Maven Plugin") + description.set("Uploads JVM sources to PostHog so error tracking can show source code on exception frames") + goalPrefix.set("posthog") +} + +// Maven supplies its own API at runtime, so these stay off the published POM. The plugin has no +// runtime dependencies of its own, which keeps it free of version clashes with the build it runs in. +val mavenVersion = "3.9.9" +val mavenPluginToolsVersion = "3.15.1" + +dependencies { + compileOnly("org.apache.maven:maven-plugin-api:$mavenVersion") + compileOnly("org.apache.maven:maven-core:$mavenVersion") + compileOnly("org.apache.maven.plugin-tools:maven-plugin-annotations:$mavenPluginToolsVersion") + + testImplementation("org.apache.maven:maven-plugin-api:$mavenVersion") + testImplementation("org.apache.maven:maven-core:$mavenVersion") + testCompileOnly("org.apache.maven.plugin-tools:maven-plugin-annotations:$mavenPluginToolsVersion") + testImplementation("junit:junit:4.13.2") +} + +publishing { + publications { + create("maven") { + from(components["java"]) + + postHogConfig(project.name, project.version.toString()) + pom.postHogConfig( + project.name, + moduleDescription = "Official PostHog Maven plugin: uploads JVM sources for error tracking source context", + ) + pom.packaging = "maven-plugin" + } + } + signing.postHogConfig("maven", this) +} + +tasks.javadoc { + if (JavaVersion.current().isJava9Compatible) { + (options as StandardJavadocDocletOptions).addBooleanOption("html5", true) + } +} diff --git a/posthog-maven-plugin/gradle.lockfile b/posthog-maven-plugin/gradle.lockfile new file mode 100644 index 000000000..aa673341a --- /dev/null +++ b/posthog-maven-plugin/gradle.lockfile @@ -0,0 +1,73 @@ +# This is a Gradle generated file for dependency locking. +# Manual edits can break the build and are not advised. +# This file is expected to be part of source control. +# To regenerate this file, run: ./gradlew :posthog-maven-plugin:dependencies --write-locks +aopalliance:aopalliance:1.0=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.12.7=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +com.fasterxml.jackson.core:jackson-core:2.12.7=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +com.fasterxml.jackson.core:jackson-databind:2.12.7.1=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.12.7=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +com.fasterxml.jackson.module:jackson-module-jaxb-annotations:2.12.7=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +com.fasterxml.jackson.module:jackson-module-kotlin:2.12.7=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +com.fasterxml.jackson:jackson-bom:2.12.7=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +com.fasterxml.woodstox:woodstox-core:6.2.4=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +com.google.guava:failureaccess:1.0.2=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.google.guava:guava:33.2.1-jre=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.google.inject:guice:5.1.0=compileClasspath,testCompileClasspath,testRuntimeClasspath +it.unimi.dsi:fastutil-core:8.5.12=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +jakarta.activation:jakarta.activation-api:1.2.1=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +jakarta.xml.bind:jakarta.xml.bind-api:2.3.2=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +javax.inject:javax.inject:1=compileClasspath,testCompileClasspath,testRuntimeClasspath +junit:junit:4.13.2=testCompileClasspath,testRuntimeClasspath +org.apache.maven.plugin-tools:maven-plugin-annotations:3.15.1=compileClasspath,testCompileClasspath +org.apache.maven.resolver:maven-resolver-api:1.9.22=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.resolver:maven-resolver-impl:1.9.22=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.resolver:maven-resolver-named-locks:1.9.22=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.resolver:maven-resolver-spi:1.9.22=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.resolver:maven-resolver-util:1.9.22=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.shared:maven-shared-utils:3.4.2=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-artifact:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-builder-support:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-core:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-model-builder:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-model:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-plugin-api:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-repository-metadata:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-resolver-provider:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-settings-builder:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven:maven-settings:3.9.9=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-cipher:2.0=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-classworlds:2.8.0=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-component-annotations:2.1.0=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-interpolation:1.27=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-sec-dispatcher:2.0=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-utils:3.5.1=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.codehaus.plexus:plexus-xml:3.0.0=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.codehaus.woodstox:stax2-api:4.2.1=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +org.eclipse.sisu:org.eclipse.sisu.inject:0.9.0.M3=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.eclipse.sisu:org.eclipse.sisu.plexus:0.9.0.M3=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.freemarker:freemarker:2.3.32=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.hamcrest:hamcrest-core:1.3=testCompileClasspath,testRuntimeClasspath +org.jetbrains.dokka:analysis-kotlin-descriptors:1.9.20=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.jetbrains.dokka:analysis-markdown:1.9.20=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.jetbrains.dokka:dokka-base:1.9.20=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.jetbrains.dokka:dokka-core:1.9.20=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +org.jetbrains.kotlin:kotlin-reflect:1.9.22=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +org.jetbrains.kotlin:kotlin-stdlib-common:1.9.22=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.20=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.0=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.20=dokkaGfmPartialRuntime,dokkaGfmRuntime,dokkaHtmlPartialRuntime,dokkaHtmlRuntime,dokkaJavadocPartialRuntime,dokkaJavadocRuntime,dokkaJekyllPartialRuntime,dokkaJekyllRuntime +org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.0=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.jetbrains.kotlin:kotlin-stdlib:1.9.22=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.7.3=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.7.3=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +org.jetbrains.kotlinx:kotlinx-html-jvm:0.9.1=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.jetbrains:annotations:23.0.0=dokkaGfmPartialPlugin,dokkaGfmPartialRuntime,dokkaGfmPlugin,dokkaGfmRuntime,dokkaHtmlPartialPlugin,dokkaHtmlPartialRuntime,dokkaHtmlPlugin,dokkaHtmlRuntime,dokkaJavadocPartialPlugin,dokkaJavadocPartialRuntime,dokkaJavadocPlugin,dokkaJavadocRuntime,dokkaJekyllPartialPlugin,dokkaJekyllPartialRuntime,dokkaJekyllPlugin,dokkaJekyllRuntime +org.jetbrains:markdown-jvm:0.5.2=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.jetbrains:markdown:0.5.2=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.jsoup:jsoup:1.16.1=dokkaGfmPartialPlugin,dokkaGfmPlugin,dokkaHtmlPartialPlugin,dokkaHtmlPlugin,dokkaJavadocPartialPlugin,dokkaJavadocPlugin,dokkaJekyllPartialPlugin,dokkaJekyllPlugin +org.ow2.asm:asm-tree:9.6=bcv-rt-jvm-cp-resolver +org.ow2.asm:asm:9.6=bcv-rt-jvm-cp-resolver +org.slf4j:slf4j-api:1.7.36=compileClasspath,testCompileClasspath,testRuntimeClasspath +empty=annotationProcessor,dokkaPlugin,dokkaRuntime,runtimeClasspath,testAnnotationProcessor diff --git a/posthog-maven-plugin/package.json b/posthog-maven-plugin/package.json new file mode 100644 index 000000000..22ef50ffc --- /dev/null +++ b/posthog-maven-plugin/package.json @@ -0,0 +1,5 @@ +{ + "name": "posthog-maven-plugin", + "version": "0.0.0", + "private": true +} diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java new file mode 100644 index 000000000..e42ffb391 --- /dev/null +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java @@ -0,0 +1,111 @@ +package com.posthog.maven; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** Finds posthog-cli and builds the command line that runs it. */ +final class PostHogCli { + static final String DEFAULT_EXECUTABLE = "posthog-cli"; + + private PostHogCli() {} + + /** + * Returns the posthog-cli to run, or null when none is installed. A configured path is used + * verbatim. Otherwise this checks {@code ~/.posthog/posthog-cli} first, the override location + * PostHog's Xcode build script also checks first, then PATH, then the common install + * locations (Homebrew, the installer script's {@code ~/.cargo/bin}) that a build launched from + * an IDE may not have on PATH. + */ + static String resolve( + String configured, Map environment, File home, boolean isWindows) { + if (configured != null && !configured.trim().isEmpty()) { + return configured.trim(); + } + + if (isWindows) { + // A native posthog-cli.exe runs directly. The npm posthog-cli.cmd shim runs only + // through cmd, which finds it by the bare name. + File exe = findOnPath(DEFAULT_EXECUTABLE + ".exe", environment, true); + if (exe != null) { + return exe.getAbsolutePath(); + } + return findOnPath(DEFAULT_EXECUTABLE + ".cmd", environment, true) != null + ? DEFAULT_EXECUTABLE + : null; + } + + File installed = new File(home, ".posthog/" + DEFAULT_EXECUTABLE); + if (isRunnable(installed)) { + return installed.getAbsolutePath(); + } + + File onPath = findOnPath(DEFAULT_EXECUTABLE, environment, false); + if (onPath != null) { + return onPath.getAbsolutePath(); + } + + List knownLocations = + Arrays.asList( + new File("/opt/homebrew/bin/" + DEFAULT_EXECUTABLE), + new File("/usr/local/bin/" + DEFAULT_EXECUTABLE), + new File(home, ".cargo/bin/" + DEFAULT_EXECUTABLE), + new File(home, ".local/bin/" + DEFAULT_EXECUTABLE)); + for (File candidate : knownLocations) { + if (isRunnable(candidate)) { + return candidate.getAbsolutePath(); + } + } + + return null; + } + + /** + * On Windows a bare name may be the npm posthog-cli.cmd shim, which only cmd can find and run. + * An .exe runs directly, which also keeps cmd from mangling a quoted path with spaces. + */ + static List commandLine(String executable, List args, boolean isWindows) { + List command = new ArrayList<>(); + if (isWindows && !executable.toLowerCase().endsWith(".exe")) { + command.add("cmd"); + command.add("/c"); + } + command.add(executable); + command.addAll(args); + return command; + } + + static boolean isWindows() { + return System.getProperty("os.name", "").toLowerCase().contains("win"); + } + + private static File findOnPath(String name, Map environment, boolean isWindows) { + String path = null; + for (Map.Entry entry : environment.entrySet()) { + // Windows spells it Path, and environment lookups there are case-insensitive. + if (isWindows ? entry.getKey().equalsIgnoreCase("PATH") : entry.getKey().equals("PATH")) { + path = entry.getValue(); + break; + } + } + if (path == null) { + return null; + } + for (String dir : path.split(File.pathSeparator)) { + if (dir.isEmpty()) { + continue; + } + File candidate = new File(dir, name); + if (isRunnable(candidate)) { + return candidate; + } + } + return null; + } + + private static boolean isRunnable(File file) { + return file.isFile() && file.canExecute(); + } +} diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java new file mode 100644 index 000000000..67791e63b --- /dev/null +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -0,0 +1,360 @@ +package com.posthog.maven; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.PluginExecution; +import org.apache.maven.model.Resource; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +/** + * Uploads the project's sources to PostHog, so error tracking can show source code on the frames + * of exceptions this build throws, and writes the id they were uploaded under into {@code + * posthog-meta.properties}. The PostHog server SDK reads that file at startup and sends the id on + * every exception frame. + * + *

Runs {@code posthog-cli jvm upload}. The file goes into a generated resources directory, never + * into {@code src}, so every build carries the id of the sources it compiled. + */ +@Mojo(name = "upload-sources", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true) +public class UploadSourcesMojo extends AbstractMojo { + static final String META_PROPERTIES_FILE = "posthog-meta.properties"; + + private static final String KOTLIN_MAVEN_PLUGIN = "org.jetbrains.kotlin:kotlin-maven-plugin"; + + private static final String INSTALL_HINT = + ". Install it (npm install -g @posthog/cli) or set posthog.cliExecutable."; + private static final String UPDATE_HINT = + ". Update it (npm install -g @posthog/cli@latest or brew upgrade posthog-cli) or set" + + " posthog.cliExecutable."; + + @Parameter(defaultValue = "${project}", readonly = true, required = true) + MavenProject project; + + /** Skips the upload. The build then ships no id, so its exceptions show no source code. */ + @Parameter(property = "posthog.skip", defaultValue = "false") + boolean skip; + + /** + * Fails the build when posthog-cli is missing or has no jvm upload command, or PostHog + * credentials are missing. By default the upload is skipped with a warning instead, so that + * builds on machines without PostHog set up keep working. Set it in CI, so that a missing token + * fails the build instead of shipping a build whose exceptions show no source code. A failed + * upload fails the build either way. + */ + @Parameter(property = "posthog.requireUpload", defaultValue = "false") + boolean requireUpload; + + /** + * Path to posthog-cli. When unset, the plugin looks in {@code ~/.posthog/posthog-cli}, then on + * PATH, then in common install locations. + */ + @Parameter(property = "posthog.cliExecutable") + String cliExecutable; + + /** + * A dotenv file posthog-cli reads its credentials from ({@code POSTHOG_CLI_HOST}, {@code + * POSTHOG_CLI_PROJECT_ID}, {@code POSTHOG_CLI_API_KEY}). Without one, posthog-cli reads the + * environment and the credentials saved by {@code posthog-cli login}. + */ + @Parameter(property = "posthog.dotenvFile") + File dotenvFile; + + /** The release the uploaded sources are associated with. */ + @Parameter(property = "posthog.releaseName", defaultValue = "${project.artifactId}") + String releaseName; + + /** + * The version of that release. When unset, posthog-cli uses the current git commit, from the + * repository or from the CI environment, so every deployed commit is its own release. A + * project version such as {@code 0.0.1-SNAPSHOT} often stays the same across deploys. A build + * with no git commit and no version uploads its sources without a release. + */ + @Parameter(property = "posthog.releaseVersion") + String releaseVersion; + + /** Where posthog-cli writes {@code posthog-meta.properties}. Added as a resource directory. */ + @Parameter( + property = "posthog.outputDirectory", + defaultValue = "${project.build.directory}/generated-resources/posthog", + required = true) + File outputDirectory; + + /** + * The source directories to upload. Defaults to the project's compile source roots and the + * {@code } that kotlin-maven-plugin compiles. + */ + @Parameter + List sourceRoots; + + @Override + public void execute() throws MojoExecutionException { + // A file left by an earlier build would point this build's exceptions at that build's + // sources, so it goes first, and a skipped or failed run leaves no id behind. + deleteStaleMetaProperties(); + + if (skip) { + getLog().info("Skipping the PostHog source upload (posthog.skip is true)"); + return; + } + + List roots = existingSourceRoots(); + if (roots.isEmpty()) { + getLog().info("Skipping the PostHog source upload: none of the source roots exist"); + return; + } + + boolean isWindows = PostHogCli.isWindows(); + String executable = + PostHogCli.resolve( + cliExecutable, + System.getenv(), + new File(System.getProperty("user.home")), + isWindows); + if (executable == null) { + skipOrFail("posthog-cli was not found" + INSTALL_HINT, null); + return; + } + + Process process; + try { + // A posthog-cli from before `jvm upload` exits with an error on the unknown + // subcommand, which would fail the build even when the upload is optional. + if (!supportsJvmUpload(executable, isWindows)) { + skipOrFail( + "posthog-cli (" + + executable + + ") is too old: it has no jvm upload command" + + UPDATE_HINT, + null); + return; + } + process = start(PostHogCli.commandLine(executable, cliArguments(roots), isWindows)); + } catch (IOException e) { + skipOrFail("Could not run posthog-cli (" + executable + ")" + INSTALL_HINT, e); + return; + } + waitFor(process); + + File written = new File(outputDirectory, META_PROPERTIES_FILE); + if (!written.isFile()) { + if (requireUpload) { + throw new MojoExecutionException( + "posthog-cli exited successfully but did not write " + written); + } + // posthog-cli skips the upload when it finds no credentials, and logs why. + getLog().warn( + "The PostHog source upload was skipped, so exceptions from this build show no" + + " source code. Set posthog.requireUpload to fail the build instead."); + return; + } + registerResourceDirectory(); + } + + List cliArguments(List roots) { + List args = new ArrayList<>(); + // A global option, so it goes before the subcommand. + if (dotenvFile != null) { + args.add("--dotenv-file"); + args.add(dotenvFile.getAbsolutePath()); + } + args.add("jvm"); + args.add("upload"); + for (File root : roots) { + args.add("--source"); + args.add(root.getAbsolutePath()); + } + args.add("--meta-out"); + args.add(outputDirectory.getAbsolutePath()); + if (!requireUpload) { + args.add("--skip-without-credentials"); + } + if (isNotBlank(releaseName)) { + args.add("--release-name"); + args.add(releaseName); + } + if (isNotBlank(releaseVersion)) { + args.add("--release-version"); + args.add(releaseVersion); + } + return args; + } + + private List existingSourceRoots() { + Set configured = new LinkedHashSet<>(); + if (sourceRoots != null && !sourceRoots.isEmpty()) { + configured.addAll(sourceRoots); + } else { + for (String root : project.getCompileSourceRoots()) { + configured.add(new File(root).getAbsoluteFile()); + } + configured.addAll(kotlinSourceDirs()); + } + + List existing = new ArrayList<>(); + for (File root : configured) { + if (root.isDirectory()) { + existing.add(root); + } else { + getLog().debug("Skipping missing source root " + root); + } + } + return existing; + } + + /** + * The directories that kotlin-maven-plugin compiles from its {@code }. A project + * with Java and Kotlin sources usually lists {@code src/main/kotlin} there, as the Kotlin docs + * show, and that list never becomes a compile source root of the project. + */ + private List kotlinSourceDirs() { + List dirs = new ArrayList<>(); + Plugin kotlin = project.getPlugin(KOTLIN_MAVEN_PLUGIN); + if (kotlin == null) { + return dirs; + } + addSourceDirs(kotlin.getConfiguration(), dirs); + for (PluginExecution execution : kotlin.getExecutions()) { + if (execution.getGoals().contains("compile")) { + addSourceDirs(execution.getConfiguration(), dirs); + } + } + return dirs; + } + + private void addSourceDirs(Object configuration, List dirs) { + if (!(configuration instanceof Xpp3Dom)) { + return; + } + Xpp3Dom sourceDirs = ((Xpp3Dom) configuration).getChild("sourceDirs"); + if (sourceDirs == null) { + return; + } + for (Xpp3Dom sourceDir : sourceDirs.getChildren()) { + String value = sourceDir.getValue(); + if (value == null || value.trim().isEmpty()) { + continue; + } + File dir = new File(value.trim()); + dirs.add(dir.isAbsolute() ? dir : new File(project.getBasedir(), value.trim())); + } + } + + private void deleteStaleMetaProperties() throws MojoExecutionException { + List stale = new ArrayList<>(); + stale.add(new File(outputDirectory, META_PROPERTIES_FILE)); + // process-resources copies a resource only when the copy is missing or older, so the copy + // in the classes directory has to go too. A posthog-meta.properties the project keeps in + // its own resources is copied back right after this. + if (project.getBuild() != null && project.getBuild().getOutputDirectory() != null) { + stale.add(new File(project.getBuild().getOutputDirectory(), META_PROPERTIES_FILE)); + } + for (File file : stale) { + if (file.exists() && !file.delete()) { + throw new MojoExecutionException("Could not delete the stale " + file); + } + } + } + + private void skipOrFail(String message, Exception cause) throws MojoExecutionException { + if (requireUpload) { + throw new MojoExecutionException(message, cause); + } + getLog().warn( + message + + " Skipping the PostHog source upload, so exceptions from this build show" + + " no source code. Set posthog.requireUpload to fail the build instead."); + } + + /** + * Whether this posthog-cli has {@code jvm upload} with every option the plugin passes. It asks + * for the command's help, which needs no credentials and sends nothing to PostHog. + */ + private boolean supportsJvmUpload(String executable, boolean isWindows) + throws IOException, MojoExecutionException { + Process process = + start( + PostHogCli.commandLine( + executable, Arrays.asList("jvm", "upload", "--help"), isWindows)); + StringBuilder help = new StringBuilder(); + try (BufferedReader reader = + new BufferedReader( + new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + help.append(line).append('\n'); + } + return process.waitFor() == 0 && help.toString().contains("--skip-without-credentials"); + } catch (InterruptedException e) { + process.destroy(); + Thread.currentThread().interrupt(); + throw new MojoExecutionException("Interrupted while waiting for posthog-cli", e); + } + } + + private Process start(List command) throws IOException { + getLog().debug("Running " + String.join(" ", command)); + + ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); + if (project.getBasedir() != null) { + // posthog-cli reads the release's git details from its working directory. + builder.directory(project.getBasedir()); + } + return builder.start(); + } + + private void waitFor(Process process) throws MojoExecutionException { + try (BufferedReader reader = + new BufferedReader( + new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + getLog().info("[posthog-cli] " + line); + } + int exitCode = process.waitFor(); + if (exitCode != 0) { + throw new MojoExecutionException("posthog-cli exited with code " + exitCode); + } + } catch (IOException e) { + process.destroy(); + throw new MojoExecutionException("Could not read the posthog-cli output", e); + } catch (InterruptedException e) { + process.destroy(); + Thread.currentThread().interrupt(); + throw new MojoExecutionException("Interrupted while waiting for posthog-cli", e); + } + } + + private void registerResourceDirectory() { + String directory = outputDirectory.getAbsolutePath(); + for (Resource resource : project.getResources()) { + if (resource.getDirectory() != null + && new File(resource.getDirectory()).getAbsolutePath().equals(directory)) { + return; + } + } + + Resource resource = new Resource(); + resource.setDirectory(directory); + resource.addInclude(META_PROPERTIES_FILE); + project.addResource(resource); + } + + private static boolean isNotBlank(String value) { + return value != null && !value.trim().isEmpty(); + } +} diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java new file mode 100644 index 000000000..1567220c8 --- /dev/null +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -0,0 +1,426 @@ +package com.posthog.maven; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.maven.model.Build; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.PluginExecution; +import org.apache.maven.model.Resource; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.xml.Xpp3Dom; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class UploadSourcesMojoTest { + @Rule public TemporaryFolder temp = new TemporaryFolder(); + + private File basedir; + private File argsFile; + private UploadSourcesMojo mojo; + + @Before + public void setUp() throws IOException { + basedir = temp.newFolder("project"); + argsFile = new File(temp.getRoot(), "cli-args.txt"); + + MavenProject project = new MavenProject(); + project.setFile(new File(basedir, "pom.xml")); + Build build = new Build(); + build.setDirectory(new File(basedir, "target").getAbsolutePath()); + build.setOutputDirectory(new File(basedir, "target/classes").getAbsolutePath()); + project.getModel().setBuild(build); + + mojo = new UploadSourcesMojo(); + mojo.project = project; + mojo.releaseName = "demo-app"; + mojo.releaseVersion = "1.2.3"; + mojo.outputDirectory = new File(basedir, "target/generated-resources/posthog"); + } + + @Test + public void uploadsExistingSourceRootsAndRegistersTheResourceDirectory() throws Exception { + assumeUnix(); + File java = sourceRoot("src/main/java"); + File kotlin = sourceRoot("src/main/kotlin"); + mojo.project.addCompileSourceRoot(java.getAbsolutePath()); + mojo.project.addCompileSourceRoot(new File(basedir, "src/main/missing").getAbsolutePath()); + mojo.project.addCompileSourceRoot(kotlin.getAbsolutePath()); + mojo.dotenvFile = new File(basedir, ".env"); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + + mojo.execute(); + + assertEquals( + Arrays.asList( + "--dotenv-file", + mojo.dotenvFile.getAbsolutePath(), + "jvm", + "upload", + "--source", + java.getAbsolutePath(), + "--source", + kotlin.getAbsolutePath(), + "--meta-out", + mojo.outputDirectory.getAbsolutePath(), + "--skip-without-credentials", + "--release-name", + "demo-app", + "--release-version", + "1.2.3"), + recordedArgs()); + + List resources = mojo.project.getResources(); + assertEquals(1, resources.size()); + assertEquals(mojo.outputDirectory.getAbsolutePath(), resources.get(0).getDirectory()); + assertEquals( + Collections.singletonList("posthog-meta.properties"), + resources.get(0).getIncludes()); + } + + @Test + public void kotlinSourceDirsAreUploadedWithTheCompileSourceRoots() throws Exception { + assumeUnix(); + File java = sourceRoot("src/main/java"); + File kotlin = sourceRoot("src/main/kotlin"); + mojo.project.addCompileSourceRoot(java.getAbsolutePath()); + // The mixed Java and Kotlin setup from the Kotlin docs, which lists both directories. + Xpp3Dom sourceDirs = new Xpp3Dom("sourceDirs"); + for (String dir : Arrays.asList("src/main/kotlin", java.getAbsolutePath())) { + Xpp3Dom sourceDir = new Xpp3Dom("sourceDir"); + sourceDir.setValue(dir); + sourceDirs.addChild(sourceDir); + } + Xpp3Dom configuration = new Xpp3Dom("configuration"); + configuration.addChild(sourceDirs); + PluginExecution compile = new PluginExecution(); + compile.addGoal("compile"); + compile.setConfiguration(configuration); + Plugin plugin = new Plugin(); + plugin.setGroupId("org.jetbrains.kotlin"); + plugin.setArtifactId("kotlin-maven-plugin"); + plugin.addExecution(compile); + mojo.project.getBuild().addPlugin(plugin); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + + mojo.execute(); + + assertEquals( + Arrays.asList( + "--source", java.getAbsolutePath(), "--source", kotlin.getAbsolutePath()), + recordedArgs().subList(2, 6)); + assertEquals("--meta-out", recordedArgs().get(6)); + } + + @Test + public void configuredSourceRootsReplaceTheCompileSourceRoots() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + File custom = sourceRoot("custom"); + mojo.sourceRoots = Collections.singletonList(custom); + mojo.releaseName = " "; + mojo.releaseVersion = null; + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + + mojo.execute(); + + assertEquals( + Arrays.asList( + "jvm", + "upload", + "--source", + custom.getAbsolutePath(), + "--meta-out", + mojo.outputDirectory.getAbsolutePath(), + "--skip-without-credentials"), + recordedArgs()); + } + + @Test + public void registersTheResourceDirectoryOnce() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + + mojo.execute(); + mojo.execute(); + + assertEquals(1, mojo.project.getResources().size()); + } + + @Test + public void failsTheBuildWhenTheCliFails() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(3, false).getAbsolutePath(); + + try { + mojo.execute(); + fail("expected a MojoExecutionException"); + } catch (MojoExecutionException e) { + assertTrue(e.getMessage(), e.getMessage().contains("exited with code 3")); + } + assertTrue(mojo.project.getResources().isEmpty()); + } + + @Test + public void skipsWhenTheCliUploadsNothing() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, false).getAbsolutePath(); + + mojo.execute(); + + assertTrue(mojo.project.getResources().isEmpty()); + } + + @Test + public void aRequiredUploadFailsTheBuildWhenTheCliWritesNoFile() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, false).getAbsolutePath(); + mojo.requireUpload = true; + + try { + mojo.execute(); + fail("expected a MojoExecutionException"); + } catch (MojoExecutionException e) { + assertTrue(e.getMessage(), e.getMessage().contains("did not write")); + } + assertFalse(recordedArgs().contains("--skip-without-credentials")); + assertTrue(mojo.project.getResources().isEmpty()); + } + + @Test + public void skipsWhenTheCliIsMissing() throws Exception { + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = new File(temp.getRoot(), "no-such-posthog-cli").getAbsolutePath(); + File stale = staleMetaProperties(mojo.outputDirectory); + + mojo.execute(); + + assertFalse(stale.exists()); + assertTrue(mojo.project.getResources().isEmpty()); + } + + @Test + public void anOldCliSkipsTheUploadUnlessItIsRequired() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = oldCli().getAbsolutePath(); + + mojo.execute(); + + assertTrue(mojo.project.getResources().isEmpty()); + + mojo.requireUpload = true; + try { + mojo.execute(); + fail("expected a MojoExecutionException"); + } catch (MojoExecutionException e) { + assertTrue(e.getMessage(), e.getMessage().contains("too old")); + } + } + + @Test + public void aRequiredUploadFailsWithAnInstallHintWhenTheCliIsMissing() throws Exception { + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = new File(temp.getRoot(), "no-such-posthog-cli").getAbsolutePath(); + mojo.requireUpload = true; + + try { + mojo.execute(); + fail("expected a MojoExecutionException"); + } catch (MojoExecutionException e) { + assertTrue(e.getMessage(), e.getMessage().contains("posthog.cliExecutable")); + } + } + + @Test + public void skipRunsNothingAndRemovesAStaleId() throws Exception { + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + File staleGenerated = staleMetaProperties(mojo.outputDirectory); + File staleClasses = staleMetaProperties(new File(basedir, "target/classes")); + mojo.skip = true; + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(staleGenerated.exists()); + assertFalse(staleClasses.exists()); + assertTrue(mojo.project.getResources().isEmpty()); + } + + @Test + public void skipsWhenNoSourceRootExists() throws Exception { + mojo.project.addCompileSourceRoot(new File(basedir, "src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertTrue(mojo.project.getResources().isEmpty()); + } + + @Test + public void resolveUsesTheConfiguredExecutableVerbatim() { + assertEquals( + "/custom/posthog-cli", + PostHogCli.resolve(" /custom/posthog-cli ", env(""), temp.getRoot(), false)); + } + + @Test + public void resolvePrefersTheDotPosthogInstallOverPath() throws Exception { + assumeUnix(); + File home = temp.newFolder("home"); + File installed = executable(new File(home, ".posthog/posthog-cli")); + File pathDir = temp.newFolder("bin"); + executable(new File(pathDir, "posthog-cli")); + + assertEquals( + installed.getAbsolutePath(), + PostHogCli.resolve(null, env(pathDir.getAbsolutePath()), home, false)); + } + + @Test + public void resolveFallsBackToPathThenNothing() throws Exception { + assumeUnix(); + File home = temp.newFolder("home"); + File pathDir = temp.newFolder("bin"); + File onPath = executable(new File(pathDir, "posthog-cli")); + + assertEquals( + onPath.getAbsolutePath(), + PostHogCli.resolve("", env(pathDir.getAbsolutePath()), home, false)); + // A temp home and an empty PATH only leave the machine-wide install locations, so no + // CLI is expected unless this machine has one installed in one of them. + String resolved = PostHogCli.resolve(null, env(""), home, false); + assertTrue(resolved, resolved == null || resolved.startsWith("/")); + } + + @Test + public void resolveOnWindowsPrefersTheExeThenTheNpmShim() throws Exception { + File home = temp.newFolder("home"); + File exeDir = temp.newFolder("exe"); + File exe = executable(new File(exeDir, "posthog-cli.exe")); + File shimDir = temp.newFolder("shim"); + executable(new File(shimDir, "posthog-cli.cmd")); + String both = exeDir.getAbsolutePath() + File.pathSeparator + shimDir.getAbsolutePath(); + + assertEquals(exe.getAbsolutePath(), PostHogCli.resolve(null, env(both), home, true)); + assertEquals( + "posthog-cli", + PostHogCli.resolve(null, env(shimDir.getAbsolutePath()), home, true)); + assertEquals(null, PostHogCli.resolve(null, env(""), home, true)); + } + + @Test + public void commandLineWrapsABareNameInCmdOnWindows() { + List args = Arrays.asList("jvm", "upload"); + + assertEquals( + Arrays.asList("cmd", "/c", "posthog-cli", "jvm", "upload"), + PostHogCli.commandLine("posthog-cli", args, true)); + assertEquals( + Arrays.asList("C:\\bin\\posthog-cli.exe", "jvm", "upload"), + PostHogCli.commandLine("C:\\bin\\posthog-cli.exe", args, true)); + assertEquals( + Arrays.asList("/bin/posthog-cli", "jvm", "upload"), + PostHogCli.commandLine("/bin/posthog-cli", args, false)); + } + + private File sourceRoot(String relative) { + File dir = new File(basedir, relative); + assertTrue(dir.mkdirs()); + return dir; + } + + private File staleMetaProperties(File dir) throws IOException { + assertTrue(dir.isDirectory() || dir.mkdirs()); + File file = new File(dir, "posthog-meta.properties"); + Files.write(file.toPath(), "io.posthog.proguard.mapid=stale\n".getBytes(StandardCharsets.UTF_8)); + return file; + } + + /** + * A shell script standing in for posthog-cli. It answers the plugin's help probe like a CLI + * with jvm upload. Otherwise it records its arguments one per line, writes + * posthog-meta.properties into the --meta-out directory when asked to, and exits with the + * given code. + */ + private File fakeCli(int exitCode, boolean writeMetaProperties) throws IOException { + String script = + "#!/bin/sh\n" + + "case \" $* \" in *' --help '*) echo ' --skip-without-credentials'; exit 0;; esac\n" + + "printf '%s\\n' \"$@\" > '" + + argsFile.getAbsolutePath() + + "'\n" + + "meta=''\n" + + "prev=''\n" + + "for arg in \"$@\"; do\n" + + " if [ \"$prev\" = '--meta-out' ]; then meta=\"$arg\"; fi\n" + + " prev=\"$arg\"\n" + + "done\n" + + (writeMetaProperties + ? "mkdir -p \"$meta\"\n" + + "printf 'io.posthog.proguard.mapid=fake-id\\n' > \"$meta/posthog-meta.properties\"\n" + : "") + + "echo fake-id\n" + + "exit " + + exitCode + + "\n"; + File cli = new File(temp.getRoot(), "fake-posthog-cli-" + exitCode + "-" + writeMetaProperties); + Files.write(cli.toPath(), script.getBytes(StandardCharsets.UTF_8)); + assertTrue(cli.setExecutable(true)); + return cli; + } + + /** A posthog-cli from before jvm upload, which rejects the subcommand like clap does. */ + private File oldCli() throws IOException { + String script = + "#!/bin/sh\n" + + "echo \"error: unrecognized subcommand 'jvm'\" >&2\n" + + "exit 2\n"; + File cli = new File(temp.getRoot(), "old-posthog-cli"); + Files.write(cli.toPath(), script.getBytes(StandardCharsets.UTF_8)); + assertTrue(cli.setExecutable(true)); + return cli; + } + + private List recordedArgs() throws IOException { + return Files.readAllLines(argsFile.toPath(), StandardCharsets.UTF_8); + } + + private static File executable(File file) throws IOException { + assertTrue(file.getParentFile().isDirectory() || file.getParentFile().mkdirs()); + Files.write(file.toPath(), "#!/bin/sh\n".getBytes(StandardCharsets.UTF_8)); + assertTrue(file.setExecutable(true)); + return file; + } + + private static Map env(String path) { + Map env = new HashMap<>(); + env.put("PATH", path); + return env; + } + + private static void assumeUnix() { + Assume.assumeFalse(PostHogCli.isWindows()); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index b90ad7dfb..cb485a11e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -20,6 +20,7 @@ include(":posthog-android") include(":posthog-android-surveys-compose") include(":posthog-server") include(":posthog-server-openfeature") +include(":posthog-maven-plugin") // samples include(":posthog-samples:posthog-android-sample") From f1b79e6d4f0da28b3eca5c16e36dc315d524872a Mon Sep 17 00:00:00 2001 From: ablaszkiewicz Date: Thu, 26 Nov 2026 18:55:53 +0100 Subject: [PATCH 02/14] fix(maven-plugin): upload generated and non-utf-8 sources, avoid cmd - Run upload-sources in process-classes, after compilation, so the sources that annotation processors generate are uploaded. The id goes straight into the classes directory, because process-resources has already run. - Upload UTF-8 copies of Java sources whose declared encoding is not UTF-8. posthog-cli reads every file as UTF-8 and skips the others. - Put the CLI's directory and node's directory on the child PATH, so an npm launcher found outside PATH can start node. - On Windows, run the native binary of the npm package instead of its .cmd shim, so no argument passes through cmd. When only the shim can run, refuse values that hold cmd operators. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FkuJA9vNowLRRGH1hbFyhv --- posthog-maven-plugin/README.md | 9 +- .../java/com/posthog/maven/PostHogCli.java | 188 ++++++++++++++++-- .../com/posthog/maven/UploadSourcesMojo.java | 159 ++++++++++----- .../java/com/posthog/maven/Utf8Sources.java | 108 ++++++++++ .../posthog/maven/UploadSourcesMojoTest.java | 166 +++++++++++++--- 5 files changed, 538 insertions(+), 92 deletions(-) create mode 100644 posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index e12fc4341..99e4d1519 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -2,7 +2,7 @@ Uploads your application's Java and Kotlin sources to PostHog, so error tracking shows the source code around each frame of the exceptions your app captures. -On every build, the `upload-sources` goal runs [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) `jvm upload`. The CLI bundles the sources, uploads them under an id derived from their content and the release, and writes that id into `posthog-meta.properties` in a generated resources directory. The file is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads it and sends the id on every exception frame, and PostHog looks up the uploaded sources by that id. +On every build, the `upload-sources` goal runs [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) `jvm upload`. The CLI bundles the sources, uploads them under an id derived from their content and the release, and writes that id into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads it and sends the id on every exception frame, and PostHog looks up the uploaded sources by that id. A build of unchanged code in the same release reuses the existing upload and sends no source files. Changed code, or a new release, gets a new id and a new upload, so exceptions are attributed to the release that threw them. Because the file is written on every build, it always matches the code that was compiled. @@ -33,7 +33,9 @@ A build of unchanged code in the same release reuses the existing upload and sen ``` -The goal binds to the `generate-resources` phase, so `mvn package` uploads before it packages. +The goal binds to the `process-classes` phase. It runs after compilation, so the upload includes the sources that annotation processors such as MapStruct generate, and `mvn package` uploads before it packages. A command that stops before that phase uploads nothing: run `mvn package jib:build` or `mvn process-classes jib:build`, not `mvn compile jib:build`. + +`posthog-cli` reads sources as UTF-8. When `project.build.sourceEncoding` or the compiler's `encoding` names another encoding, the plugin uploads UTF-8 copies of the Java sources from `target/posthog/utf8-sources`. ### Releases @@ -63,11 +65,10 @@ A developer who has run `posthog-cli login` uploads from local builds too. Pass |---|---|---|---| | `skip` | `posthog.skip` | `false` | Skip the upload. | | `requireUpload` | `posthog.requireUpload` | `false` | Fail the build when `posthog-cli` is missing or too old, or the credentials are missing, instead of skipping the upload. | -| `cliExecutable` | `posthog.cliExecutable` | found automatically | Path to `posthog-cli`. Without it, the plugin checks `~/.posthog/posthog-cli`, then `PATH`, then Homebrew, `~/.cargo/bin` and `~/.local/bin`. | +| `cliExecutable` | `posthog.cliExecutable` | found automatically | Path to `posthog-cli`. Without it, the plugin checks `~/.posthog/posthog-cli`, then `PATH`, then Homebrew, `~/.cargo/bin` and `~/.local/bin`. On Windows, it runs `posthog-cli.exe` from `PATH`, or the binary of the npm package behind `posthog-cli.cmd`. | | `dotenvFile` | `posthog.dotenvFile` | none | A dotenv file `posthog-cli` reads credentials from. | | `releaseName` | `posthog.releaseName` | `${project.artifactId}` | The release the upload is associated with. | | `releaseVersion` | `posthog.releaseVersion` | the git commit | The version of that release. Set it to `${project.version}` if you bump the project version on every release. | -| `outputDirectory` | `posthog.outputDirectory` | `${project.build.directory}/generated-resources/posthog` | Where `posthog-meta.properties` is written. The plugin adds it as a resource directory. | | `sourceRoots` | none | the project's compile source roots, plus the `` of `kotlin-maven-plugin` | The directories to upload. Setting it replaces the default. | ## What it doesn't cover yet diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java index e42ffb391..dd2c8d05e 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java @@ -3,6 +3,7 @@ import java.io.File; import java.util.ArrayList; import java.util.Arrays; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -10,6 +11,8 @@ final class PostHogCli { static final String DEFAULT_EXECUTABLE = "posthog-cli"; + private static final String CMD_UNSAFE_CHARACTERS = "&|<>^%!\"()\r\n"; + private PostHogCli() {} /** @@ -26,15 +29,20 @@ static String resolve( } if (isWindows) { - // A native posthog-cli.exe runs directly. The npm posthog-cli.cmd shim runs only - // through cmd, which finds it by the bare name. File exe = findOnPath(DEFAULT_EXECUTABLE + ".exe", environment, true); if (exe != null) { return exe.getAbsolutePath(); } - return findOnPath(DEFAULT_EXECUTABLE + ".cmd", environment, true) != null - ? DEFAULT_EXECUTABLE - : null; + File shim = findOnPath(DEFAULT_EXECUTABLE + ".cmd", environment, true); + if (shim == null) { + return null; + } + // The npm shim only starts the native binary that the package installed. Running that + // binary directly keeps the arguments away from cmd, which would run a `&` in a path + // or a release version as a second command. + File npmExe = npmInstalledExe(shim); + // Without it, cmd finds the shim by its bare name. + return npmExe != null ? npmExe.getAbsolutePath() : DEFAULT_EXECUTABLE; } File installed = new File(home, ".posthog/" + DEFAULT_EXECUTABLE); @@ -68,7 +76,7 @@ static String resolve( */ static List commandLine(String executable, List args, boolean isWindows) { List command = new ArrayList<>(); - if (isWindows && !executable.toLowerCase().endsWith(".exe")) { + if (runsThroughCmd(executable, isWindows)) { command.add("cmd"); command.add("/c"); } @@ -77,19 +85,134 @@ static List commandLine(String executable, List args, boolean is return command; } + static boolean runsThroughCmd(String executable, boolean isWindows) { + return isWindows && !executable.toLowerCase().endsWith(".exe"); + } + + /** + * The first of {@code values} that cmd would not pass through unchanged, or null when all are + * safe. Java quotes an argument with spaces, but cmd still reads operators such as {@code &} + * and {@code |}, expands {@code %VAR%}, and ends the command at a line break. + */ + static String firstUnsafeForCmd(List values) { + for (String value : values) { + for (int i = 0; i < value.length(); i++) { + if (CMD_UNSAFE_CHARACTERS.indexOf(value.charAt(i)) >= 0) { + return value; + } + } + } + return null; + } + + /** + * The PATH for the CLI process, with the CLI's directory and node's directory first when PATH + * lacks them. An npm install of posthog-cli is a {@code #!/usr/bin/env node} launcher, and a + * build started from an IDE may have neither the launcher's directory nor node on its PATH. + * Returns null when the PATH needs no change. + */ + static String launcherPath( + String executable, + Map environment, + File home, + boolean isWindows, + List knownNodeLocations) { + String path = pathValue(environment, isWindows); + List onPath = + path == null ? new ArrayList<>() : Arrays.asList(path.split(File.pathSeparator)); + List missing = new ArrayList<>(); + File executableFile = new File(executable); + if (executableFile.isAbsolute() && executableFile.getParent() != null) { + missing.add(executableFile.getParent()); + } + File node = resolveNode(environment, home, isWindows, knownNodeLocations); + if (node != null) { + missing.add(node.getParent()); + } + missing.removeAll(onPath); + if (missing.isEmpty()) { + return null; + } + List entries = new ArrayList<>(new LinkedHashSet<>(missing)); + if (path != null && !path.isEmpty()) { + entries.add(path); + } + return String.join(File.pathSeparator, entries); + } + + /** node on PATH, else (outside Windows) in nvm, Homebrew and the other common locations. */ + static File resolveNode( + Map environment, + File home, + boolean isWindows, + List knownLocations) { + File onPath = findOnPath(isWindows ? "node.exe" : "node", environment, isWindows); + if (onPath != null || isWindows) { + return onPath; + } + List candidates = knownLocations; + if (candidates == null) { + candidates = new ArrayList<>(nvmNodes(new File(home, ".nvm/versions/node"))); + File[] cellars = new File("/opt/homebrew/Cellar/nvm").listFiles(); + if (cellars != null) { + for (File cellar : cellars) { + candidates.addAll(nvmNodes(new File(cellar, "versions/node"))); + } + } + candidates.add(new File("/opt/homebrew/bin/node")); + candidates.add(new File("/usr/local/bin/node")); + candidates.add(new File(home, ".local/bin/node")); + } + for (File candidate : candidates) { + if (isRunnable(candidate)) { + return candidate.getAbsoluteFile(); + } + } + return null; + } + + /** + * The native binary of the npm package, which npm installs into + * {@code node_modules/@posthog/cli/node_modules/.bin_real}. A global install puts the shim in + * the npm prefix, next to {@code node_modules}. A project install puts it in {@code + * node_modules/.bin}. + */ + static File npmInstalledExe(File shim) { + File shimDirectory = shim.getAbsoluteFile().getParentFile(); + String binary = "@posthog/cli/node_modules/.bin_real/" + DEFAULT_EXECUTABLE + ".exe"; + List candidates = new ArrayList<>(); + candidates.add(new File(shimDirectory, "node_modules/" + binary)); + if (shimDirectory.getParentFile() != null) { + candidates.add(new File(shimDirectory.getParentFile(), binary)); + } + for (File candidate : candidates) { + if (candidate.isFile()) { + return candidate; + } + } + return null; + } + static boolean isWindows() { return System.getProperty("os.name", "").toLowerCase().contains("win"); } - private static File findOnPath(String name, Map environment, boolean isWindows) { - String path = null; - for (Map.Entry entry : environment.entrySet()) { - // Windows spells it Path, and environment lookups there are case-insensitive. - if (isWindows ? entry.getKey().equalsIgnoreCase("PATH") : entry.getKey().equals("PATH")) { - path = entry.getValue(); - break; + /** The PATH key of {@code environment}. Windows spells it Path, and is case-insensitive. */ + static String pathKey(Map environment, boolean isWindows) { + for (String key : environment.keySet()) { + if (isWindows ? key.equalsIgnoreCase("PATH") : key.equals("PATH")) { + return key; } } + return "PATH"; + } + + private static String pathValue(Map environment, boolean isWindows) { + return environment.get(pathKey(environment, isWindows)); + } + + private static File findOnPath(String name, Map environment, boolean isWindows) { + String path = pathValue(environment, isWindows); if (path == null) { return null; } @@ -108,4 +231,43 @@ private static File findOnPath(String name, Map environment, boo private static boolean isRunnable(File file) { return file.isFile() && file.canExecute(); } + + /** {@code /vX.Y.Z/bin/node}, newest version first. */ + private static List nvmNodes(File root) { + List nodes = new ArrayList<>(); + File[] versions = root.listFiles(); + if (versions == null) { + return nodes; + } + List sorted = new ArrayList<>(Arrays.asList(versions)); + sorted.sort((a, b) -> compareVersions(versionParts(b.getName()), versionParts(a.getName()))); + for (File version : sorted) { + nodes.add(new File(version, "bin/node")); + } + return nodes; + } + + private static List versionParts(String name) { + List parts = new ArrayList<>(); + for (String part : name.split("\\D+")) { + if (!part.isEmpty()) { + try { + parts.add(Long.parseLong(part)); + } catch (NumberFormatException e) { + parts.add(Long.MAX_VALUE); + } + } + } + return parts; + } + + private static int compareVersions(List a, List b) { + for (int i = 0; i < Math.max(a.size(), b.size()); i++) { + int cmp = Long.compare(i < a.size() ? a.get(i) : 0L, i < b.size() ? b.get(i) : 0L); + if (cmp != 0) { + return cmp; + } + } + return 0; + } } diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index 67791e63b..d7978a2c0 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -4,15 +4,16 @@ import java.io.File; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Set; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; -import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -27,14 +28,16 @@ * posthog-meta.properties}. The PostHog server SDK reads that file at startup and sends the id on * every exception frame. * - *

Runs {@code posthog-cli jvm upload}. The file goes into a generated resources directory, never - * into {@code src}, so every build carries the id of the sources it compiled. + *

Runs {@code posthog-cli jvm upload} after compilation, so the upload includes the sources that + * annotation processors generate. The file goes into the classes directory, never into {@code + * src}, so every build carries the id of the sources it compiled. */ -@Mojo(name = "upload-sources", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true) +@Mojo(name = "upload-sources", defaultPhase = LifecyclePhase.PROCESS_CLASSES, threadSafe = true) public class UploadSourcesMojo extends AbstractMojo { static final String META_PROPERTIES_FILE = "posthog-meta.properties"; private static final String KOTLIN_MAVEN_PLUGIN = "org.jetbrains.kotlin:kotlin-maven-plugin"; + private static final String COMPILER_PLUGIN = "org.apache.maven.plugins:maven-compiler-plugin"; private static final String INSTALL_HINT = ". Install it (npm install -g @posthog/cli) or set posthog.cliExecutable."; @@ -87,13 +90,6 @@ public class UploadSourcesMojo extends AbstractMojo { @Parameter(property = "posthog.releaseVersion") String releaseVersion; - /** Where posthog-cli writes {@code posthog-meta.properties}. Added as a resource directory. */ - @Parameter( - property = "posthog.outputDirectory", - defaultValue = "${project.build.directory}/generated-resources/posthog", - required = true) - File outputDirectory; - /** * The source directories to upload. Defaults to the project's compile source roots and the * {@code } that kotlin-maven-plugin compiles. @@ -130,6 +126,25 @@ public void execute() throws MojoExecutionException { return; } + roots = utf8Roots(roots); + List args = cliArguments(roots); + if (PostHogCli.runsThroughCmd(executable, isWindows)) { + List values = new ArrayList<>(args); + values.add(0, executable); + String unsafe = PostHogCli.firstUnsafeForCmd(values); + if (unsafe != null) { + skipOrFail( + "posthog-cli (" + + executable + + ") runs through cmd, which would not pass this value unchanged: " + + unsafe + + ". Set posthog.cliExecutable to posthog-cli.exe, which runs" + + " directly.", + null); + return; + } + } + Process process; try { // A posthog-cli from before `jvm upload` exits with an error on the unknown @@ -143,14 +158,14 @@ public void execute() throws MojoExecutionException { null); return; } - process = start(PostHogCli.commandLine(executable, cliArguments(roots), isWindows)); + process = start(executable, args, isWindows); } catch (IOException e) { skipOrFail("Could not run posthog-cli (" + executable + ")" + INSTALL_HINT, e); return; } waitFor(process); - File written = new File(outputDirectory, META_PROPERTIES_FILE); + File written = new File(classesDirectory(), META_PROPERTIES_FILE); if (!written.isFile()) { if (requireUpload) { throw new MojoExecutionException( @@ -160,9 +175,7 @@ public void execute() throws MojoExecutionException { getLog().warn( "The PostHog source upload was skipped, so exceptions from this build show no" + " source code. Set posthog.requireUpload to fail the build instead."); - return; } - registerResourceDirectory(); } List cliArguments(List roots) { @@ -178,8 +191,10 @@ List cliArguments(List roots) { args.add("--source"); args.add(root.getAbsolutePath()); } + // process-resources has already copied the resources, so the file goes straight into the + // classes directory that the jar, war and Spring Boot archive are built from. args.add("--meta-out"); - args.add(outputDirectory.getAbsolutePath()); + args.add(classesDirectory().getAbsolutePath()); if (!requireUpload) { args.add("--skip-without-credentials"); } @@ -236,6 +251,64 @@ private List kotlinSourceDirs() { return dirs; } + /** + * Copies of the roots with UTF-8 text when the compiler reads the sources in another encoding, + * otherwise the roots themselves. + */ + private List utf8Roots(List roots) throws MojoExecutionException { + Charset encoding = sourceEncoding(); + if (encoding == null || Utf8Sources.isUtf8(encoding)) { + return roots; + } + File buildDirectory = new File(project.getBuild().getDirectory()); + try { + return Utf8Sources.copy( + roots, encoding, new File(buildDirectory, "posthog/utf8-sources"), buildDirectory); + } catch (IOException e) { + throw new MojoExecutionException("Could not copy the sources as UTF-8", e); + } + } + + /** + * The encoding maven-compiler-plugin reads the sources in: its {@code encoding} parameter, + * else {@code project.build.sourceEncoding}. Null when neither is set, so the platform default + * applies, which is UTF-8 from Java 18 on. + */ + private Charset sourceEncoding() { + String encoding = null; + Plugin compiler = project.getPlugin(COMPILER_PLUGIN); + if (compiler != null) { + for (PluginExecution execution : compiler.getExecutions()) { + if (encoding == null && execution.getGoals().contains("compile")) { + encoding = childValue(execution.getConfiguration(), "encoding"); + } + } + if (encoding == null) { + encoding = childValue(compiler.getConfiguration(), "encoding"); + } + } + if (encoding == null) { + encoding = project.getProperties().getProperty("project.build.sourceEncoding"); + } + if (!isNotBlank(encoding)) { + return null; + } + try { + return Charset.forName(encoding.trim()); + } catch (IllegalArgumentException e) { + getLog().warn("Unknown source encoding " + encoding + ", uploading the sources as is"); + return null; + } + } + + private static String childValue(Object configuration, String name) { + if (!(configuration instanceof Xpp3Dom)) { + return null; + } + Xpp3Dom child = ((Xpp3Dom) configuration).getChild(name); + return child != null && isNotBlank(child.getValue()) ? child.getValue().trim() : null; + } + private void addSourceDirs(Object configuration, List dirs) { if (!(configuration instanceof Xpp3Dom)) { return; @@ -255,21 +328,16 @@ private void addSourceDirs(Object configuration, List dirs) { } private void deleteStaleMetaProperties() throws MojoExecutionException { - List stale = new ArrayList<>(); - stale.add(new File(outputDirectory, META_PROPERTIES_FILE)); - // process-resources copies a resource only when the copy is missing or older, so the copy - // in the classes directory has to go too. A posthog-meta.properties the project keeps in - // its own resources is copied back right after this. - if (project.getBuild() != null && project.getBuild().getOutputDirectory() != null) { - stale.add(new File(project.getBuild().getOutputDirectory(), META_PROPERTIES_FILE)); - } - for (File file : stale) { - if (file.exists() && !file.delete()) { - throw new MojoExecutionException("Could not delete the stale " + file); - } + File stale = new File(classesDirectory(), META_PROPERTIES_FILE); + if (stale.exists() && !stale.delete()) { + throw new MojoExecutionException("Could not delete the stale " + stale); } } + private File classesDirectory() { + return new File(project.getBuild().getOutputDirectory()); + } + private void skipOrFail(String message, Exception cause) throws MojoExecutionException { if (requireUpload) { throw new MojoExecutionException(message, cause); @@ -286,10 +354,7 @@ private void skipOrFail(String message, Exception cause) throws MojoExecutionExc */ private boolean supportsJvmUpload(String executable, boolean isWindows) throws IOException, MojoExecutionException { - Process process = - start( - PostHogCli.commandLine( - executable, Arrays.asList("jvm", "upload", "--help"), isWindows)); + Process process = start(executable, Arrays.asList("jvm", "upload", "--help"), isWindows); StringBuilder help = new StringBuilder(); try (BufferedReader reader = new BufferedReader( @@ -306,7 +371,9 @@ private boolean supportsJvmUpload(String executable, boolean isWindows) } } - private Process start(List command) throws IOException { + private Process start(String executable, List args, boolean isWindows) + throws IOException { + List command = PostHogCli.commandLine(executable, args, isWindows); getLog().debug("Running " + String.join(" ", command)); ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); @@ -314,6 +381,17 @@ private Process start(List command) throws IOException { // posthog-cli reads the release's git details from its working directory. builder.directory(project.getBasedir()); } + Map environment = builder.environment(); + String path = + PostHogCli.launcherPath( + executable, + environment, + new File(System.getProperty("user.home")), + isWindows, + null); + if (path != null) { + environment.put(PostHogCli.pathKey(environment, isWindows), path); + } return builder.start(); } @@ -339,21 +417,6 @@ private void waitFor(Process process) throws MojoExecutionException { } } - private void registerResourceDirectory() { - String directory = outputDirectory.getAbsolutePath(); - for (Resource resource : project.getResources()) { - if (resource.getDirectory() != null - && new File(resource.getDirectory()).getAbsolutePath().equals(directory)) { - return; - } - } - - Resource resource = new Resource(); - resource.setDirectory(directory); - resource.addInclude(META_PROPERTIES_FILE); - project.addResource(resource); - } - private static boolean isNotBlank(String value) { return value != null && !value.trim().isEmpty(); } diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java new file mode 100644 index 000000000..6a7fb4da8 --- /dev/null +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java @@ -0,0 +1,108 @@ +package com.posthog.maven; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Stream; + +/** + * Copies source roots with UTF-8 text. posthog-cli reads every source file as UTF-8 and skips a + * file it cannot decode, so a project whose Java sources use another encoding would upload + * without them. + */ +final class Utf8Sources { + private Utf8Sources() {} + + static boolean isUtf8(Charset encoding) { + return encoding.equals(StandardCharsets.UTF_8) || encoding.equals(StandardCharsets.US_ASCII); + } + + /** + * Copies each root into {@code /}, with the same relative + * paths, and returns the copies. Java files are decoded from {@code encoding} and written as + * UTF-8. Kotlin files are copied unchanged, because the Kotlin compiler reads only UTF-8. + * Characters and line breaks stay the same, so every line keeps its number. + */ + static List copy( + List roots, Charset encoding, File outputDirectory, File buildDirectory) + throws IOException { + deleteRecursively(outputDirectory.toPath()); + Path output = outputDirectory.toPath().toAbsolutePath(); + Path build = buildDirectory.toPath().toAbsolutePath(); + List copies = new ArrayList<>(); + for (int index = 0; index < roots.size(); index++) { + Path root = roots.get(index).toPath().toAbsolutePath(); + Path copyRoot = output.resolve(String.valueOf(index)); + Files.createDirectories(copyRoot); + Files.walkFileTree( + root, + new SimpleFileVisitor() { + @Override + public FileVisitResult preVisitDirectory( + Path dir, BasicFileAttributes attributes) { + if (dir.equals(root)) { + return FileVisitResult.CONTINUE; + } + // A root such as the project directory holds the build directory, and + // with it these copies. + boolean buildOutput = dir.equals(build) && !root.startsWith(build); + boolean hidden = dir.getFileName().toString().startsWith("."); + return buildOutput || hidden || dir.equals(output) + ? FileVisitResult.SKIP_SUBTREE + : FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) + throws IOException { + String name = file.getFileName().toString(); + Path target = copyRoot.resolve(root.relativize(file).toString()); + if (name.endsWith(".java")) { + Files.createDirectories(target.getParent()); + Files.write(target, decode(Files.readAllBytes(file), encoding)); + } else if (name.endsWith(".kt")) { + Files.createDirectories(target.getParent()); + Files.copy(file, target); + } + return FileVisitResult.CONTINUE; + } + }); + copies.add(copyRoot.toFile()); + } + return copies; + } + + // A byte the encoding cannot map becomes U+FFFD, as javac would report it, instead of dropping + // the file. + private static byte[] decode(byte[] bytes, Charset encoding) throws IOException { + String text = + encoding.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + return text.getBytes(StandardCharsets.UTF_8); + } + + private static void deleteRecursively(Path path) throws IOException { + if (!Files.exists(path)) { + return; + } + try (Stream paths = Files.walk(path)) { + for (Path each : (Iterable) paths.sorted(Comparator.reverseOrder())::iterator) { + Files.delete(each); + } + } + } +} diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index 1567220c8..cc0501647 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -1,5 +1,6 @@ package com.posthog.maven; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -17,7 +18,6 @@ import org.apache.maven.model.Build; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; -import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; @@ -32,6 +32,7 @@ public class UploadSourcesMojoTest { private File basedir; private File argsFile; + private File classes; private UploadSourcesMojo mojo; @Before @@ -50,11 +51,11 @@ public void setUp() throws IOException { mojo.project = project; mojo.releaseName = "demo-app"; mojo.releaseVersion = "1.2.3"; - mojo.outputDirectory = new File(basedir, "target/generated-resources/posthog"); + classes = new File(basedir, "target/classes"); } @Test - public void uploadsExistingSourceRootsAndRegistersTheResourceDirectory() throws Exception { + public void uploadsExistingSourceRootsAndWritesTheIdIntoTheClasses() throws Exception { assumeUnix(); File java = sourceRoot("src/main/java"); File kotlin = sourceRoot("src/main/kotlin"); @@ -77,20 +78,14 @@ public void uploadsExistingSourceRootsAndRegistersTheResourceDirectory() throws "--source", kotlin.getAbsolutePath(), "--meta-out", - mojo.outputDirectory.getAbsolutePath(), + classes.getAbsolutePath(), "--skip-without-credentials", "--release-name", "demo-app", "--release-version", "1.2.3"), recordedArgs()); - - List resources = mojo.project.getResources(); - assertEquals(1, resources.size()); - assertEquals(mojo.outputDirectory.getAbsolutePath(), resources.get(0).getDirectory()); - assertEquals( - Collections.singletonList("posthog-meta.properties"), - resources.get(0).getIncludes()); + assertTrue(metaProperties().isFile()); } @Test @@ -146,21 +141,71 @@ public void configuredSourceRootsReplaceTheCompileSourceRoots() throws Exception "--source", custom.getAbsolutePath(), "--meta-out", - mojo.outputDirectory.getAbsolutePath(), + classes.getAbsolutePath(), "--skip-without-credentials"), recordedArgs()); } @Test - public void registersTheResourceDirectoryOnce() throws Exception { + public void javaSourcesInAnotherEncodingAreUploadedAsUtf8() throws Exception { assumeUnix(); - mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + File java = sourceRoot("src/main/java"); + File javaFile = new File(java, "com/acme/Price.java"); + assertTrue(javaFile.getParentFile().mkdirs()); + // 0x80 is the euro sign in windows-1252 and a control character in ISO-8859-1. + byte[] cp1252 = "package com.acme;\n// 5 \u20ac\nclass Price {}\n".getBytes("windows-1252"); + Files.write(javaFile.toPath(), cp1252); + File kotlinFile = new File(java, "com/acme/Tax.kt"); + byte[] kotlin = "package com.acme\n// 5 \u20ac\n".getBytes(StandardCharsets.UTF_8); + Files.write(kotlinFile.toPath(), kotlin); + mojo.project.addCompileSourceRoot(java.getAbsolutePath()); + // The compiler's own encoding wins over the project property. + mojo.project.getProperties().setProperty("project.build.sourceEncoding", "ISO-8859-1"); + Xpp3Dom encoding = new Xpp3Dom("encoding"); + encoding.setValue("windows-1252"); + Xpp3Dom configuration = new Xpp3Dom("configuration"); + configuration.addChild(encoding); + Plugin compiler = new Plugin(); + compiler.setGroupId("org.apache.maven.plugins"); + compiler.setArtifactId("maven-compiler-plugin"); + compiler.setConfiguration(configuration); + mojo.project.getBuild().addPlugin(compiler); mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); mojo.execute(); + + File copy = new File(basedir, "target/posthog/utf8-sources/0"); + assertEquals(Arrays.asList("--source", copy.getAbsolutePath()), recordedArgs().subList(2, 4)); + assertEquals( + "package com.acme;\n// 5 \u20ac\nclass Price {}\n", + new String( + Files.readAllBytes(new File(copy, "com/acme/Price.java").toPath()), + StandardCharsets.UTF_8)); + assertArrayEquals(kotlin, Files.readAllBytes(new File(copy, "com/acme/Tax.kt").toPath())); + assertArrayEquals(cp1252, Files.readAllBytes(javaFile.toPath())); + } + + @Test + public void anNpmLauncherRunsWhenNeitherItNorNodeIsOnPath() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + // npm links posthog-cli to a `#!/usr/bin/env node` script next to node, in a directory + // such as /opt/homebrew/bin that a build started from an IDE may not have on PATH. + File npmBin = temp.newFolder("npm-bin"); + File node = new File(npmBin, "node"); + Files.write(node.toPath(), "#!/bin/sh\nexec /bin/sh \"$@\"\n".getBytes(StandardCharsets.UTF_8)); + assertTrue(node.setExecutable(true)); + File launcher = new File(npmBin, "posthog-cli"); + String script = new String(Files.readAllBytes(fakeCli(0, true).toPath()), StandardCharsets.UTF_8); + Files.write( + launcher.toPath(), + script.replace("#!/bin/sh", "#!/usr/bin/env node").getBytes(StandardCharsets.UTF_8)); + assertTrue(launcher.setExecutable(true)); + mojo.cliExecutable = launcher.getAbsolutePath(); + mojo.execute(); - assertEquals(1, mojo.project.getResources().size()); + assertTrue(metaProperties().isFile()); } @Test @@ -175,7 +220,7 @@ public void failsTheBuildWhenTheCliFails() throws Exception { } catch (MojoExecutionException e) { assertTrue(e.getMessage(), e.getMessage().contains("exited with code 3")); } - assertTrue(mojo.project.getResources().isEmpty()); + assertFalse(metaProperties().exists()); } @Test @@ -186,7 +231,7 @@ public void skipsWhenTheCliUploadsNothing() throws Exception { mojo.execute(); - assertTrue(mojo.project.getResources().isEmpty()); + assertFalse(metaProperties().exists()); } @Test @@ -203,19 +248,19 @@ public void aRequiredUploadFailsTheBuildWhenTheCliWritesNoFile() throws Exceptio assertTrue(e.getMessage(), e.getMessage().contains("did not write")); } assertFalse(recordedArgs().contains("--skip-without-credentials")); - assertTrue(mojo.project.getResources().isEmpty()); + assertFalse(metaProperties().exists()); } @Test public void skipsWhenTheCliIsMissing() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.cliExecutable = new File(temp.getRoot(), "no-such-posthog-cli").getAbsolutePath(); - File stale = staleMetaProperties(mojo.outputDirectory); + File stale = staleMetaProperties(classes); mojo.execute(); assertFalse(stale.exists()); - assertTrue(mojo.project.getResources().isEmpty()); + assertFalse(metaProperties().exists()); } @Test @@ -226,7 +271,7 @@ public void anOldCliSkipsTheUploadUnlessItIsRequired() throws Exception { mojo.execute(); - assertTrue(mojo.project.getResources().isEmpty()); + assertFalse(metaProperties().exists()); mojo.requireUpload = true; try { @@ -255,16 +300,13 @@ public void aRequiredUploadFailsWithAnInstallHintWhenTheCliIsMissing() throws Ex public void skipRunsNothingAndRemovesAStaleId() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); - File staleGenerated = staleMetaProperties(mojo.outputDirectory); - File staleClasses = staleMetaProperties(new File(basedir, "target/classes")); + File stale = staleMetaProperties(classes); mojo.skip = true; mojo.execute(); assertFalse(argsFile.exists()); - assertFalse(staleGenerated.exists()); - assertFalse(staleClasses.exists()); - assertTrue(mojo.project.getResources().isEmpty()); + assertFalse(stale.exists()); } @Test @@ -275,7 +317,7 @@ public void skipsWhenNoSourceRootExists() throws Exception { mojo.execute(); assertFalse(argsFile.exists()); - assertTrue(mojo.project.getResources().isEmpty()); + assertFalse(metaProperties().exists()); } @Test @@ -328,6 +370,72 @@ public void resolveOnWindowsPrefersTheExeThenTheNpmShim() throws Exception { "posthog-cli", PostHogCli.resolve(null, env(shimDir.getAbsolutePath()), home, true)); assertEquals(null, PostHogCli.resolve(null, env(""), home, true)); + + // The shim starts the binary the npm package installed, so that binary runs instead, + // without cmd: from a global install, and from a project's node_modules/.bin. + String binary = "@posthog/cli/node_modules/.bin_real/posthog-cli.exe"; + File globalPrefix = temp.newFolder("npm-global"); + executable(new File(globalPrefix, "posthog-cli.cmd")); + File globalExe = executable(new File(globalPrefix, "node_modules/" + binary)); + File projectBin = temp.newFolder("project-npm", "node_modules", ".bin"); + executable(new File(projectBin, "posthog-cli.cmd")); + File projectExe = executable(new File(projectBin.getParentFile(), binary)); + + assertEquals( + globalExe.getAbsolutePath(), + PostHogCli.resolve(null, env(globalPrefix.getAbsolutePath()), home, true)); + assertEquals( + projectExe.getAbsolutePath(), + PostHogCli.resolve(null, env(projectBin.getAbsolutePath()), home, true)); + } + + @Test + public void cmdUnsafeValuesAreFound() { + for (String unsafe : + Arrays.asList( + "v1&whoami", + "C:\\work\\R&D\\src", + "a|b", + "a>b", + "%PATH%", + "!x!", + "say \"hi\"", + "a^b", + "(a)", + "a\nb")) { + assertEquals(unsafe, PostHogCli.firstUnsafeForCmd(Arrays.asList("--source", unsafe))); + } + assertEquals( + null, + PostHogCli.firstUnsafeForCmd( + Arrays.asList( + "posthog-cli", + "--source", + "C:\\My Projects\\app-1\\src\\main\\java", + "--release-version", + "1.2.3+build.4"))); + } + + @Test + public void launcherPathPrependsOnlyTheDirectoriesPathLacks() throws Exception { + assumeUnix(); + File cliDir = temp.newFolder("cli-bin"); + File nodeDir = temp.newFolder("node-bin"); + File node = executable(new File(nodeDir, "node")); + List nodeLocations = Collections.singletonList(node); + String cli = new File(cliDir, "posthog-cli").getAbsolutePath(); + String otherDir = temp.newFolder("other-bin").getAbsolutePath(); + + assertEquals( + cliDir.getAbsolutePath() + + File.pathSeparator + + nodeDir.getAbsolutePath() + + File.pathSeparator + + otherDir, + PostHogCli.launcherPath(cli, env(otherDir), temp.getRoot(), false, nodeLocations)); + String both = cliDir.getAbsolutePath() + File.pathSeparator + nodeDir.getAbsolutePath(); + assertEquals( + null, PostHogCli.launcherPath(cli, env(both), temp.getRoot(), false, nodeLocations)); } @Test @@ -351,6 +459,10 @@ private File sourceRoot(String relative) { return dir; } + private File metaProperties() { + return new File(classes, "posthog-meta.properties"); + } + private File staleMetaProperties(File dir) throws IOException { assertTrue(dir.isDirectory() || dir.mkdirs()); File file = new File(dir, "posthog-meta.properties"); From 13ffa60057fbb98f381efc87fb2b5c67da25dea9 Mon Sep 17 00:00:00 2001 From: ablaszkiewicz Date: Thu, 26 Nov 2026 22:14:20 +0100 Subject: [PATCH 03/14] fix(maven-plugin): allow parentheses in arguments that run through cmd Parentheses start no command in cmd, and versions such as 1.0(5) hold them. Refuse the same characters as the Gradle plugin. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FkuJA9vNowLRRGH1hbFyhv --- .../src/main/java/com/posthog/maven/PostHogCli.java | 6 ++++-- .../test/java/com/posthog/maven/UploadSourcesMojoTest.java | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java index dd2c8d05e..2cd1dfce9 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java @@ -11,7 +11,7 @@ final class PostHogCli { static final String DEFAULT_EXECUTABLE = "posthog-cli"; - private static final String CMD_UNSAFE_CHARACTERS = "&|<>^%!\"()\r\n"; + private static final String CMD_UNSAFE_CHARACTERS = "&|<>^%!\"\r\n"; private PostHogCli() {} @@ -92,7 +92,9 @@ static boolean runsThroughCmd(String executable, boolean isWindows) { /** * The first of {@code values} that cmd would not pass through unchanged, or null when all are * safe. Java quotes an argument with spaces, but cmd still reads operators such as {@code &} - * and {@code |}, expands {@code %VAR%}, and ends the command at a line break. + * and {@code |}, expands {@code %VAR%}, and ends the command at a line break. Parentheses are + * allowed, because they start no command, and versions such as {@code 1.0(5)} hold them. The + * Gradle plugin uses the same characters. */ static String firstUnsafeForCmd(List values) { for (String value : values) { diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index cc0501647..252c9f40a 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -401,7 +401,6 @@ public void cmdUnsafeValuesAreFound() { "!x!", "say \"hi\"", "a^b", - "(a)", "a\nb")) { assertEquals(unsafe, PostHogCli.firstUnsafeForCmd(Arrays.asList("--source", unsafe))); } @@ -413,7 +412,8 @@ public void cmdUnsafeValuesAreFound() { "--source", "C:\\My Projects\\app-1\\src\\main\\java", "--release-version", - "1.2.3+build.4"))); + "1.2.3+build.4", + "1.0(5)"))); } @Test From af0a6fc35acc7bb053c0381e11e2f06b134d3a56 Mon Sep 17 00:00:00 2001 From: ablaszkiewicz Date: Fri, 27 Nov 2026 14:28:32 +0100 Subject: [PATCH 04/14] fix(maven-plugin): skip a windows npm shim whose binary is missing Without the native binary, the plugin ran the bare name through cmd, and cmd looks in the project directory before PATH. The plugin now treats the shim as no install, so the build skips or fails with the install hint. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FkuJA9vNowLRRGH1hbFyhv --- .../src/main/java/com/posthog/maven/PostHogCli.java | 9 +++++---- .../java/com/posthog/maven/UploadSourcesMojoTest.java | 4 +--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java index 2cd1dfce9..e63fc7ec5 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java @@ -17,7 +17,7 @@ private PostHogCli() {} /** * Returns the posthog-cli to run, or null when none is installed. A configured path is used - * verbatim. Otherwise this checks {@code ~/.posthog/posthog-cli} first, the override location + * verbatim. On Windows, an npm shim counts only when the native binary it starts is found. Otherwise this checks {@code ~/.posthog/posthog-cli} first, the override location * PostHog's Xcode build script also checks first, then PATH, then the common install * locations (Homebrew, the installer script's {@code ~/.cargo/bin}) that a build launched from * an IDE may not have on PATH. @@ -39,10 +39,11 @@ static String resolve( } // The npm shim only starts the native binary that the package installed. Running that // binary directly keeps the arguments away from cmd, which would run a `&` in a path - // or a release version as a second command. + // or a release version as a second command. Without the binary there is nothing to + // run: cmd would look up a bare name in the project directory before PATH, and could + // run a posthog-cli there instead of the installed one. File npmExe = npmInstalledExe(shim); - // Without it, cmd finds the shim by its bare name. - return npmExe != null ? npmExe.getAbsolutePath() : DEFAULT_EXECUTABLE; + return npmExe != null ? npmExe.getAbsolutePath() : null; } File installed = new File(home, ".posthog/" + DEFAULT_EXECUTABLE); diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index 252c9f40a..a8bea31c9 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -366,9 +366,7 @@ public void resolveOnWindowsPrefersTheExeThenTheNpmShim() throws Exception { String both = exeDir.getAbsolutePath() + File.pathSeparator + shimDir.getAbsolutePath(); assertEquals(exe.getAbsolutePath(), PostHogCli.resolve(null, env(both), home, true)); - assertEquals( - "posthog-cli", - PostHogCli.resolve(null, env(shimDir.getAbsolutePath()), home, true)); + assertEquals(null, PostHogCli.resolve(null, env(shimDir.getAbsolutePath()), home, true)); assertEquals(null, PostHogCli.resolve(null, env(""), home, true)); // The shim starts the binary the npm package installed, so that binary runs instead, From e7ab10495fe7819753cc999d693615f9cba89273 Mon Sep 17 00:00:00 2001 From: ablaszkiewicz Date: Mon, 30 Nov 2026 15:45:16 +0100 Subject: [PATCH 05/14] docs(maven-plugin): describe the release id in posthog-meta.properties posthog-cli now uploads the sources without a release, so unchanged sources in a new release reuse the existing upload, and writes the release id into posthog-meta.properties for posthog-server to send with each exception. The README, the goal's javadoc and the changeset now say so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FkuJADQzM8ma8T9RauvMg5 --- .changeset/maven-plugin-upload-sources.md | 2 +- posthog-maven-plugin/README.md | 8 ++++---- .../java/com/posthog/maven/UploadSourcesMojo.java | 11 ++++++----- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/.changeset/maven-plugin-upload-sources.md b/.changeset/maven-plugin-upload-sources.md index 03011a025..70844e49d 100644 --- a/.changeset/maven-plugin-upload-sources.md +++ b/.changeset/maven-plugin-upload-sources.md @@ -2,4 +2,4 @@ "posthog-maven-plugin": minor --- -Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `posthog-cli jvm upload` to upload the project's sources and writes the id they were uploaded under into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures. When `posthog-cli` is missing or too old, or PostHog credentials are missing, the goal skips the upload with a warning. Set `requireUpload` to fail the build instead. +Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `posthog-cli jvm upload` to upload the project's sources and writes the id they were uploaded under and the id of the build's release into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures, and reports the build's release. When `posthog-cli` is missing or too old, or PostHog credentials are missing, the goal skips the upload with a warning. Set `requireUpload` to fail the build instead. diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index 99e4d1519..b356f3de4 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -2,9 +2,9 @@ Uploads your application's Java and Kotlin sources to PostHog, so error tracking shows the source code around each frame of the exceptions your app captures. -On every build, the `upload-sources` goal runs [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) `jvm upload`. The CLI bundles the sources, uploads them under an id derived from their content and the release, and writes that id into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads it and sends the id on every exception frame, and PostHog looks up the uploaded sources by that id. +On every build, the `upload-sources` goal runs [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) `jvm upload`. The CLI bundles the sources, uploads them under an id derived from their content, and writes that id and the id of the build's release into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads the file. It sends the first id on every exception frame, and PostHog looks up the uploaded sources by it. It sends the release id with every exception, and PostHog reports that release. -A build of unchanged code in the same release reuses the existing upload and sends no source files. Changed code, or a new release, gets a new id and a new upload, so exceptions are attributed to the release that threw them. Because the file is written on every build, it always matches the code that was compiled. +A build of unchanged code reuses the existing upload and sends no source files, also in a new release. Changed code gets a new id and a new upload. Because the file is written on every build, it always matches the code that was compiled and the release it belongs to. ## Requirements @@ -39,7 +39,7 @@ The goal binds to the `process-classes` phase. It runs after compilation, so the ### Releases -Each upload belongs to a release, and exceptions are attributed to it. The release name defaults to the artifact id, and the version defaults to the current git commit: `posthog-cli` reads it from the repository, or from the CI environment on GitHub Actions. So every deployed commit is its own release, even when the project version stays at `0.0.1-SNAPSHOT`. A build with no git commit, such as a Docker build that copies only the sources, uploads without a release unless you set `releaseVersion`. Its exceptions still show source code. +Each build belongs to a release, and its exceptions are attributed to it. The release name defaults to the artifact id, and the version defaults to the current git commit: `posthog-cli` reads it from the repository, or from the CI environment on GitHub Actions. So every deployed commit is its own release, even when the project version stays at `0.0.1-SNAPSHOT`. A build with no git commit, such as a Docker build that copies only the sources, has no release unless you set `releaseVersion`. Its exceptions still show source code. ### Credentials @@ -67,7 +67,7 @@ A developer who has run `posthog-cli login` uploads from local builds too. Pass | `requireUpload` | `posthog.requireUpload` | `false` | Fail the build when `posthog-cli` is missing or too old, or the credentials are missing, instead of skipping the upload. | | `cliExecutable` | `posthog.cliExecutable` | found automatically | Path to `posthog-cli`. Without it, the plugin checks `~/.posthog/posthog-cli`, then `PATH`, then Homebrew, `~/.cargo/bin` and `~/.local/bin`. On Windows, it runs `posthog-cli.exe` from `PATH`, or the binary of the npm package behind `posthog-cli.cmd`. | | `dotenvFile` | `posthog.dotenvFile` | none | A dotenv file `posthog-cli` reads credentials from. | -| `releaseName` | `posthog.releaseName` | `${project.artifactId}` | The release the upload is associated with. | +| `releaseName` | `posthog.releaseName` | `${project.artifactId}` | The release the build belongs to. | | `releaseVersion` | `posthog.releaseVersion` | the git commit | The version of that release. Set it to `${project.version}` if you bump the project version on every release. | | `sourceRoots` | none | the project's compile source roots, plus the `` of `kotlin-maven-plugin` | The directories to upload. Setting it replaces the default. | diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index d7978a2c0..2e99b6406 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -24,9 +24,10 @@ /** * Uploads the project's sources to PostHog, so error tracking can show source code on the frames - * of exceptions this build throws, and writes the id they were uploaded under into {@code - * posthog-meta.properties}. The PostHog server SDK reads that file at startup and sends the id on - * every exception frame. + * of exceptions this build throws. Writes the id they were uploaded under, and the id of the + * build's release, into {@code posthog-meta.properties}. The PostHog server SDK reads that file at + * startup, sends the first id on every exception frame, and sends the release id with every + * exception. * *

Runs {@code posthog-cli jvm upload} after compilation, so the upload includes the sources that * annotation processors generate. The file goes into the classes directory, never into {@code @@ -77,7 +78,7 @@ public class UploadSourcesMojo extends AbstractMojo { @Parameter(property = "posthog.dotenvFile") File dotenvFile; - /** The release the uploaded sources are associated with. */ + /** The release the build belongs to. Exceptions from the build report it. */ @Parameter(property = "posthog.releaseName", defaultValue = "${project.artifactId}") String releaseName; @@ -85,7 +86,7 @@ public class UploadSourcesMojo extends AbstractMojo { * The version of that release. When unset, posthog-cli uses the current git commit, from the * repository or from the CI environment, so every deployed commit is its own release. A * project version such as {@code 0.0.1-SNAPSHOT} often stays the same across deploys. A build - * with no git commit and no version uploads its sources without a release. + * with no git commit and no version has no release, so its exceptions report none. */ @Parameter(property = "posthog.releaseVersion") String releaseVersion; From 56d12b4b4f6c77013d9e85cc21d4238f3e0fe25e Mon Sep 17 00:00:00 2001 From: ablaszkiewicz Date: Tue, 1 Dec 2026 11:41:14 +0100 Subject: [PATCH 06/14] fix(maven-plugin): upload only from ci, and never fail an optional upload A failed upload failed the build even without requireUpload, so a PostHog outage, a revoked key or rate limiting broke deploys. It now warns and ships no id. Local builds uploaded too, so a developer who ran posthog-cli login uploaded work in progress on every mvn test or mvn install, and could not build offline. Without requireUpload, the goal now uploads only from a CI build, not offline, and not in a module that another module of the build depends on, whose posthog-meta.properties could replace the application's on the classpath. requireUpload uploads from every build and fails it when the upload can't run, for deploy builds such as a Dockerfile. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FkuJADQzM8ma8T9RauvMg5 --- .changeset/maven-plugin-upload-sources.md | 2 +- posthog-maven-plugin/README.md | 22 ++- .../java/com/posthog/maven/CiEnvironment.java | 30 ++++ .../com/posthog/maven/UploadSourcesMojo.java | 89 +++++++++-- .../posthog/maven/UploadSourcesMojoTest.java | 147 +++++++++++++++++- 5 files changed, 268 insertions(+), 22 deletions(-) create mode 100644 posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java diff --git a/.changeset/maven-plugin-upload-sources.md b/.changeset/maven-plugin-upload-sources.md index 70844e49d..95502fc12 100644 --- a/.changeset/maven-plugin-upload-sources.md +++ b/.changeset/maven-plugin-upload-sources.md @@ -2,4 +2,4 @@ "posthog-maven-plugin": minor --- -Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `posthog-cli jvm upload` to upload the project's sources and writes the id they were uploaded under and the id of the build's release into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures, and reports the build's release. When `posthog-cli` is missing or too old, or PostHog credentials are missing, the goal skips the upload with a warning. Set `requireUpload` to fail the build instead. +Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `posthog-cli jvm upload` to upload the project's sources and writes the id they were uploaded under and the id of the build's release into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures, and reports the build's release. By default only a CI build of an application module uploads, and a missing `posthog-cli`, missing credentials or a failed upload only logs a warning. Set `requireUpload` to upload from every build and fail it when the upload can't run. diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index b356f3de4..36c7ca807 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -2,9 +2,9 @@ Uploads your application's Java and Kotlin sources to PostHog, so error tracking shows the source code around each frame of the exceptions your app captures. -On every build, the `upload-sources` goal runs [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) `jvm upload`. The CLI bundles the sources, uploads them under an id derived from their content, and writes that id and the id of the build's release into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads the file. It sends the first id on every exception frame, and PostHog looks up the uploaded sources by it. It sends the release id with every exception, and PostHog reports that release. +On each CI build, the `upload-sources` goal runs [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) `jvm upload`. The CLI bundles the sources, uploads them under an id derived from their content, and writes that id and the id of the build's release into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads the file. It sends the first id on every exception frame, and PostHog looks up the uploaded sources by it. It sends the release id with every exception, and PostHog reports that release. -A build of unchanged code reuses the existing upload and sends no source files, also in a new release. Changed code gets a new id and a new upload. Because the file is written on every build, it always matches the code that was compiled and the release it belongs to. +A build of unchanged code reuses the existing upload and sends no source files, also in a new release. Changed code gets a new id and a new upload. The goal rewrites or deletes the file on every build, so it always matches the code that was compiled and the release it belongs to. ## Requirements @@ -41,6 +41,8 @@ The goal binds to the `process-classes` phase. It runs after compilation, so the Each build belongs to a release, and its exceptions are attributed to it. The release name defaults to the artifact id, and the version defaults to the current git commit: `posthog-cli` reads it from the repository, or from the CI environment on GitHub Actions. So every deployed commit is its own release, even when the project version stays at `0.0.1-SNAPSHOT`. A build with no git commit, such as a Docker build that copies only the sources, has no release unless you set `releaseVersion`. Its exceptions still show source code. +Every build that uploads creates its release, also a build of a pull request. To keep your releases to what you deploy, pass `-Dposthog.skip=true` in CI jobs that don't deploy. + ### Credentials `posthog-cli` reads them from the environment, from a dotenv file, or from `posthog-cli login`: @@ -51,20 +53,24 @@ Each build belongs to a release, and its exceptions are attributed to it. The re To use a dotenv file, set `.env` or pass `-Dposthog.dotenvFile=.env`. -### Builds without credentials +### When it uploads + +By default, only a CI build uploads. A build counts as CI when the `CI` environment variable is set, as GitHub Actions, GitLab CI, CircleCI, Bitbucket Pipelines and most other services set it, or when it runs on Jenkins, Azure Pipelines, TeamCity or AWS CodeBuild. A local build skips the upload, so it doesn't upload work in progress or need the network. An offline build (`mvn -o`) skips it too. + +In a multi-module build, a module that another module of the build depends on is a library, and it skips the upload. The SDK reads the first `posthog-meta.properties` on the classpath, so a library's file could replace the application's. Run the goal in the application module, and add the library's source directories to its `sourceRoots`. -When `posthog-cli` is missing or too old to have `jvm upload`, or the credentials are missing, the plugin skips the upload with a warning and the build continues. Developers can build without setting up PostHog. A skipped build ships no id, so its exceptions show no source code. It also deletes the `posthog-meta.properties` an earlier build left behind, so the app never reports an id that belongs to other code. +When the upload can't run, the plugin warns and the build continues. That happens when `posthog-cli` is missing or too old to have `jvm upload`, the credentials are missing, or the upload fails, for example because PostHog can't be reached. That build ships no id, so its exceptions show no source code. Every build also deletes the `posthog-meta.properties` an earlier build left behind, so the app never reports an id that belongs to other code. -In CI, set `true` or pass `-Dposthog.requireUpload=true`. Then a missing or outdated CLI, or a missing token, fails the build instead of shipping a build without source code. A failed upload fails the build either way. +### Requiring the upload -A developer who has run `posthog-cli login` uploads from local builds too. Pass `-Dposthog.skip=true` to turn the upload off. +In the build that deploys your application, set `true` or pass `-Dposthog.requireUpload=true`. That build uploads wherever it runs, also outside CI, for example in a Dockerfile, and each of the problems above fails it instead of shipping a build without source code. ## Parameters | Parameter | User property | Default | Description | |---|---|---|---| | `skip` | `posthog.skip` | `false` | Skip the upload. | -| `requireUpload` | `posthog.requireUpload` | `false` | Fail the build when `posthog-cli` is missing or too old, or the credentials are missing, instead of skipping the upload. | +| `requireUpload` | `posthog.requireUpload` | `false` | Upload from every build, also outside CI and in library modules, and fail the build when the upload can't run. | | `cliExecutable` | `posthog.cliExecutable` | found automatically | Path to `posthog-cli`. Without it, the plugin checks `~/.posthog/posthog-cli`, then `PATH`, then Homebrew, `~/.cargo/bin` and `~/.local/bin`. On Windows, it runs `posthog-cli.exe` from `PATH`, or the binary of the npm package behind `posthog-cli.cmd`. | | `dotenvFile` | `posthog.dotenvFile` | none | A dotenv file `posthog-cli` reads credentials from. | | `releaseName` | `posthog.releaseName` | `${project.artifactId}` | The release the build belongs to. | @@ -73,5 +79,5 @@ A developer who has run `posthog-cli login` uploads from local builds too. Pass ## What it doesn't cover yet -- The SDK sends one id, the one in the application's `posthog-meta.properties`. Frames from other modules show source code only when their sources are in that upload, so in a multi-module build, run the goal in the application module and list the other modules' source directories in `sourceRoots`. Frames from a library built somewhere else show no source code. +- The SDK sends one id, the one in the application's `posthog-meta.properties`. Frames from other modules show source code only when their sources are in that upload, and frames from a library built somewhere else show none. - GraalVM native images don't include `posthog-meta.properties` unless you register it as a resource. diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java new file mode 100644 index 000000000..196e70e17 --- /dev/null +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java @@ -0,0 +1,30 @@ +package com.posthog.maven; + +import java.util.Map; + +/** Tells a CI build from a local one by the environment variables CI services set. */ +final class CiEnvironment { + // Most CI services set CI. These are the ones that do not. + private static final String[] CI_SERVICE_VARIABLES = { + "JENKINS_URL", "TF_BUILD", "TEAMCITY_VERSION", "CODEBUILD_BUILD_ID" + }; + + private CiEnvironment() {} + + static boolean isCi(Map environment) { + String ci = environment.get("CI"); + if (isSet(ci) && !ci.trim().equalsIgnoreCase("false") && !ci.trim().equals("0")) { + return true; + } + for (String name : CI_SERVICE_VARIABLES) { + if (isSet(environment.get(name))) { + return true; + } + } + return false; + } + + private static boolean isSet(String value) { + return value != null && !value.trim().isEmpty(); + } +} diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index 2e99b6406..cd8cc2cbc 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -8,10 +8,13 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.plugin.AbstractMojo; @@ -32,6 +35,9 @@ *

Runs {@code posthog-cli jvm upload} after compilation, so the upload includes the sources that * annotation processors generate. The file goes into the classes directory, never into {@code * src}, so every build carries the id of the sources it compiled. + * + *

Unless {@code requireUpload} is set, only a CI build of an application module uploads, and a + * problem with the upload never fails the build. */ @Mojo(name = "upload-sources", defaultPhase = LifecyclePhase.PROCESS_CLASSES, threadSafe = true) public class UploadSourcesMojo extends AbstractMojo { @@ -49,16 +55,23 @@ public class UploadSourcesMojo extends AbstractMojo { @Parameter(defaultValue = "${project}", readonly = true, required = true) MavenProject project; + @Parameter(defaultValue = "${session}", readonly = true) + MavenSession session; + + /** The environment the build runs in. Tests replace it. */ + Map environment = System.getenv(); + /** Skips the upload. The build then ships no id, so its exceptions show no source code. */ @Parameter(property = "posthog.skip", defaultValue = "false") boolean skip; /** - * Fails the build when posthog-cli is missing or has no jvm upload command, or PostHog - * credentials are missing. By default the upload is skipped with a warning instead, so that - * builds on machines without PostHog set up keep working. Set it in CI, so that a missing token - * fails the build instead of shipping a build whose exceptions show no source code. A failed - * upload fails the build either way. + * Makes the upload required. By default only a CI build of an application module uploads, so + * local builds do not upload work in progress or need the network. When posthog-cli or PostHog + * credentials are missing, or the upload fails, the plugin warns and the build goes on without + * an id. With this set, every build uploads, also outside CI, and each of those problems fails + * the build. Set it in the build that deploys the application, for example in a Dockerfile, + * so that it never ships a build whose exceptions show no source code. */ @Parameter(property = "posthog.requireUpload", defaultValue = "false") boolean requireUpload; @@ -109,6 +122,21 @@ public void execute() throws MojoExecutionException { return; } + if ("pom".equals(project.getPackaging())) { + getLog().info("Skipping the PostHog source upload: the project has pom packaging"); + return; + } + if (!requireUpload) { + String reason = reasonToSkipOptionalUpload(); + if (reason != null) { + getLog().info( + "Skipping the PostHog source upload: " + + reason + + ". Set posthog.requireUpload to upload anyway."); + return; + } + } + List roots = existingSourceRoots(); if (roots.isEmpty()) { getLog().info("Skipping the PostHog source upload: none of the source roots exist"); @@ -164,7 +192,21 @@ public void execute() throws MojoExecutionException { skipOrFail("Could not run posthog-cli (" + executable + ")" + INSTALL_HINT, e); return; } - waitFor(process); + int exitCode; + try { + exitCode = waitFor(process); + } catch (IOException e) { + deleteStaleMetaProperties(); + skipOrFail("Could not read the posthog-cli output.", e); + return; + } + if (exitCode != 0) { + // posthog-cli writes the file only after a successful upload, but an id from a failed + // run must never ship. + deleteStaleMetaProperties(); + skipOrFail("posthog-cli exited with code " + exitCode + ".", null); + return; + } File written = new File(classesDirectory(), META_PROPERTIES_FILE); if (!written.isFile()) { @@ -179,6 +221,32 @@ public void execute() throws MojoExecutionException { } } + /** Why an upload that is not required should not run in this build, or null when it should. */ + private String reasonToSkipOptionalUpload() { + if (!CiEnvironment.isCi(environment)) { + return "this is not a CI build"; + } + if (session == null) { + return null; + } + if (session.isOffline()) { + return "Maven runs offline"; + } + // The SDK reads the first posthog-meta.properties on the classpath, so a library's file + // can replace the application's. + ProjectDependencyGraph graph = session.getProjectDependencyGraph(); + List dependents = + graph == null + ? Collections.emptyList() + : graph.getDownstreamProjects(project, false); + if (!dependents.isEmpty()) { + return dependents.get(0).getArtifactId() + + " depends on this module, so it is a library. Upload its sources from the" + + " application module with sourceRoots"; + } + return null; + } + List cliArguments(List roots) { List args = new ArrayList<>(); // A global option, so it goes before the subcommand. @@ -396,7 +464,7 @@ private Process start(String executable, List args, boolean isWindows) return builder.start(); } - private void waitFor(Process process) throws MojoExecutionException { + private int waitFor(Process process) throws IOException, MojoExecutionException { try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { @@ -404,13 +472,10 @@ private void waitFor(Process process) throws MojoExecutionException { while ((line = reader.readLine()) != null) { getLog().info("[posthog-cli] " + line); } - int exitCode = process.waitFor(); - if (exitCode != 0) { - throw new MojoExecutionException("posthog-cli exited with code " + exitCode); - } + return process.waitFor(); } catch (IOException e) { process.destroy(); - throw new MojoExecutionException("Could not read the posthog-cli output", e); + throw e; } catch (InterruptedException e) { process.destroy(); Thread.currentThread().interrupt(); diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index a8bea31c9..04efcbbc0 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -15,6 +15,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.maven.execution.DefaultMavenExecutionRequest; +import org.apache.maven.execution.DefaultMavenExecutionResult; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.model.Build; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; @@ -49,6 +53,7 @@ public void setUp() throws IOException { mojo = new UploadSourcesMojo(); mojo.project = project; + mojo.environment = Collections.singletonMap("CI", "true"); mojo.releaseName = "demo-app"; mojo.releaseVersion = "1.2.3"; classes = new File(basedir, "target/classes"); @@ -209,10 +214,22 @@ public void anNpmLauncherRunsWhenNeitherItNorNodeIsOnPath() throws Exception { } @Test - public void failsTheBuildWhenTheCliFails() throws Exception { + public void aFailedUploadThatIsNotRequiredWarnsAndShipsNoId() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(3, true).getAbsolutePath(); + + mojo.execute(); + + assertFalse(metaProperties().exists()); + } + + @Test + public void aRequiredUploadFailsTheBuildWhenTheCliFails() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.cliExecutable = fakeCli(3, false).getAbsolutePath(); + mojo.requireUpload = true; try { mojo.execute(); @@ -223,6 +240,101 @@ public void failsTheBuildWhenTheCliFails() throws Exception { assertFalse(metaProperties().exists()); } + @Test + public void skipsOutsideCiAndDeletesTheStaleFile() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.environment = Collections.singletonMap("CI", "false"); + File stale = staleMetaProperties(classes); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(stale.exists()); + } + + @Test + public void aRequiredUploadRunsOutsideCi() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.environment = Collections.emptyMap(); + mojo.requireUpload = true; + + mojo.execute(); + + assertTrue(metaProperties().isFile()); + } + + @Test + public void skipsWhenMavenRunsOffline() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.session = session(true, Collections.emptyList()); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(metaProperties().exists()); + } + + @Test + public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + MavenProject app = new MavenProject(); + app.setArtifactId("demo-app"); + mojo.session = session(false, Collections.singletonList(app)); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(metaProperties().exists()); + + mojo.requireUpload = true; + mojo.execute(); + + assertTrue(metaProperties().isFile()); + } + + @Test + public void uploadsAnApplicationThatNoModuleOfTheBuildDependsOn() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.session = session(false, Collections.emptyList()); + + mojo.execute(); + + assertTrue(metaProperties().isFile()); + } + + @Test + public void skipsAProjectWithPomPackaging() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.project.setPackaging("pom"); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + + mojo.execute(); + + assertFalse(argsFile.exists()); + } + + @Test + public void ciIsDetectedFromTheVariablesCiServicesSet() { + assertTrue(CiEnvironment.isCi(Collections.singletonMap("CI", "true"))); + assertTrue(CiEnvironment.isCi(Collections.singletonMap("CI", "1"))); + assertTrue(CiEnvironment.isCi(Collections.singletonMap("JENKINS_URL", "https://ci.example.com/"))); + assertTrue(CiEnvironment.isCi(Collections.singletonMap("TF_BUILD", "True"))); + assertFalse(CiEnvironment.isCi(Collections.singletonMap("CI", "false"))); + assertFalse(CiEnvironment.isCi(Collections.singletonMap("CI", ""))); + assertFalse(CiEnvironment.isCi(Collections.emptyMap())); + } + @Test public void skipsWhenTheCliUploadsNothing() throws Exception { assumeUnix(); @@ -513,6 +625,39 @@ private File oldCli() throws IOException { return cli; } + @SuppressWarnings("deprecation") + private static MavenSession session(boolean offline, final List dependents) { + DefaultMavenExecutionRequest request = new DefaultMavenExecutionRequest(); + request.setOffline(offline); + MavenSession session = + new MavenSession(null, null, request, new DefaultMavenExecutionResult()); + session.setProjectDependencyGraph( + new ProjectDependencyGraph() { + @Override + public List getAllProjects() { + return Collections.emptyList(); + } + + @Override + public List getSortedProjects() { + return Collections.emptyList(); + } + + @Override + public List getDownstreamProjects( + MavenProject project, boolean transitive) { + return dependents; + } + + @Override + public List getUpstreamProjects( + MavenProject project, boolean transitive) { + return Collections.emptyList(); + } + }); + return session; + } + private List recordedArgs() throws IOException { return Files.readAllLines(argsFile.toPath(), StandardCharsets.UTF_8); } From f82d85891c7f4d1aed3af8200749b0a14c986996 Mon Sep 17 00:00:00 2001 From: ablaszkiewicz Date: Tue, 1 Dec 2026 12:53:53 +0100 Subject: [PATCH 07/14] fix(maven-plugin): address review of the source upload goal - Normalize source roots, so ${project.basedir}/. no longer makes the UTF-8 copy walk into the build directory and copy itself. - Add additionalSourceRoots, which adds to the default roots, for the other modules of a multi-module build. sourceRoots still replaces them. - A configured source root that does not exist warns, and fails a required upload. - An unset source encoding falls back to the platform charset, which javac also uses, so windows-1252 sources on Java 17 get UTF-8 copies. - The help probe calls the CLI too old only when clap rejects the command, and otherwise reports the exit code and first output line. - Resolve a relative cliExecutable against the project, report a configured path that does not exist, look for the CLI in nvm, strip quotes from Windows PATH entries, and refuse a cmd line that would cut a path with spaces short. - Compile with --release 8, and test the generated plugin.xml in the jar. - Test the session checks through two hooks instead of the deprecated MavenSession constructor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FkuJADQzM8ma8T9RauvMg5 --- posthog-maven-plugin/README.md | 21 +- posthog-maven-plugin/build.gradle.kts | 13 + .../java/com/posthog/maven/PostHogCli.java | 87 +++-- .../com/posthog/maven/UploadSourcesMojo.java | 187 ++++++++--- .../java/com/posthog/maven/Utf8Sources.java | 8 +- .../posthog/maven/UploadSourcesMojoTest.java | 299 +++++++++++++++--- 6 files changed, 503 insertions(+), 112 deletions(-) diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index 36c7ca807..e88b7e1be 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -8,7 +8,7 @@ A build of unchanged code reuses the existing upload and sends no source files, ## Requirements -- [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli), installed with `npm install -g @posthog/cli`, `brew install posthog/tap/posthog-cli`, or the install script. +- [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) with the `jvm upload` command, installed with `npm install -g @posthog/cli`, `brew install posthog/tap/posthog-cli`, or the install script. - `posthog-server` with `posthog-meta.properties` support, and no `releaseIdentifier` set in code (an explicit value wins over the file). - A personal API key with error tracking write access, for the upload. @@ -57,13 +57,23 @@ To use a dotenv file, set `.env` or pass `-Dposthog.dot By default, only a CI build uploads. A build counts as CI when the `CI` environment variable is set, as GitHub Actions, GitLab CI, CircleCI, Bitbucket Pipelines and most other services set it, or when it runs on Jenkins, Azure Pipelines, TeamCity or AWS CodeBuild. A local build skips the upload, so it doesn't upload work in progress or need the network. An offline build (`mvn -o`) skips it too. -In a multi-module build, a module that another module of the build depends on is a library, and it skips the upload. The SDK reads the first `posthog-meta.properties` on the classpath, so a library's file could replace the application's. Run the goal in the application module, and add the library's source directories to its `sourceRoots`. +In a multi-module build, a module that another module of the build depends on is a library, and it skips the upload. The SDK reads the first `posthog-meta.properties` on the classpath, so a library's file could replace the application's. Run the goal in the application module, and add the library's source directories to its `additionalSourceRoots`: + +```xml + + + ${project.basedir}/../billing/src/main/java + + +``` When the upload can't run, the plugin warns and the build continues. That happens when `posthog-cli` is missing or too old to have `jvm upload`, the credentials are missing, or the upload fails, for example because PostHog can't be reached. That build ships no id, so its exceptions show no source code. Every build also deletes the `posthog-meta.properties` an earlier build left behind, so the app never reports an id that belongs to other code. ### Requiring the upload -In the build that deploys your application, set `true` or pass `-Dposthog.requireUpload=true`. That build uploads wherever it runs, also outside CI, for example in a Dockerfile, and each of the problems above fails it instead of shipping a build without source code. +In the build that deploys your application, set `true` or pass `-Dposthog.requireUpload=true`. That build uploads wherever it runs, also outside CI, for example in a Dockerfile, and each of the problems above fails it instead of shipping a build without source code. A configured source root that doesn't exist fails it too. + +Set it in the application module, not in a parent POM that library modules share: it also makes a library module upload. ## Parameters @@ -71,11 +81,14 @@ In the build that deploys your application, set `true` of `kotlin-maven-plugin` | The directories to upload. Setting it replaces the default. | +| `additionalSourceRoots` | none | none | More directories to upload with `sourceRoots`, such as those of other modules. | + +The plugin uploads only `.java` and `.kt` files from these directories. ## What it doesn't cover yet diff --git a/posthog-maven-plugin/build.gradle.kts b/posthog-maven-plugin/build.gradle.kts index 10b26b073..4e7449f95 100644 --- a/posthog-maven-plugin/build.gradle.kts +++ b/posthog-maven-plugin/build.gradle.kts @@ -59,6 +59,19 @@ publishing { signing.postHogConfig("maven", this) } +// The plugin runs in the JVM of the Maven build, which can be Java 8. --release also rejects a call +// to an API newer than Java 8, which sourceCompatibility alone lets through. +tasks.named("compileJava") { + options.release.set(8) +} + +// The descriptor test reads META-INF/maven/plugin.xml from the jar, as Maven does. +tasks.named("test") { + val pluginJar = tasks.named("jar").flatMap { it.archiveFile } + inputs.file(pluginJar) + jvmArgumentProviders.add(CommandLineArgumentProvider { listOf("-Dposthog.pluginJar=${pluginJar.get().asFile}") }) +} + tasks.javadoc { if (JavaVersion.current().isJava9Compatible) { (options as StandardJavadocDocletOptions).addBooleanOption("html5", true) diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java index e63fc7ec5..dfcaadc5e 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java @@ -17,10 +17,11 @@ private PostHogCli() {} /** * Returns the posthog-cli to run, or null when none is installed. A configured path is used - * verbatim. On Windows, an npm shim counts only when the native binary it starts is found. Otherwise this checks {@code ~/.posthog/posthog-cli} first, the override location - * PostHog's Xcode build script also checks first, then PATH, then the common install - * locations (Homebrew, the installer script's {@code ~/.cargo/bin}) that a build launched from - * an IDE may not have on PATH. + * verbatim. On Windows, an npm shim counts only when the native binary it starts is found. + * Otherwise this checks {@code ~/.posthog/posthog-cli} first, the override location PostHog's + * Xcode build script also checks first, then PATH, then the common install locations + * (Homebrew, the installer script's {@code ~/.cargo/bin}, nvm) that a build launched from an + * IDE may not have on PATH. */ static String resolve( String configured, Map environment, File home, boolean isWindows) { @@ -57,11 +58,13 @@ static String resolve( } List knownLocations = - Arrays.asList( - new File("/opt/homebrew/bin/" + DEFAULT_EXECUTABLE), - new File("/usr/local/bin/" + DEFAULT_EXECUTABLE), - new File(home, ".cargo/bin/" + DEFAULT_EXECUTABLE), - new File(home, ".local/bin/" + DEFAULT_EXECUTABLE)); + new ArrayList<>( + Arrays.asList( + new File("/opt/homebrew/bin/" + DEFAULT_EXECUTABLE), + new File("/usr/local/bin/" + DEFAULT_EXECUTABLE), + new File(home, ".cargo/bin/" + DEFAULT_EXECUTABLE), + new File(home, ".local/bin/" + DEFAULT_EXECUTABLE))); + knownLocations.addAll(nvmBinaries(home, DEFAULT_EXECUTABLE)); for (File candidate : knownLocations) { if (isRunnable(candidate)) { return candidate.getAbsolutePath(); @@ -90,6 +93,23 @@ static boolean runsThroughCmd(String executable, boolean isWindows) { return isWindows && !executable.toLowerCase().endsWith(".exe"); } + /** + * Whether cmd would cut a path with spaces short. Java quotes the path, and any argument that + * is empty or holds a space. When the line then holds more than two quotes, {@code cmd /c} + * removes the first and the last one, which leaves the path unquoted. + */ + static boolean cmdSplitsPath(String executable, List args) { + if (!executable.contains(" ")) { + return false; + } + for (String arg : args) { + if (arg.isEmpty() || arg.contains(" ") || arg.contains("\t")) { + return true; + } + } + return false; + } + /** * The first of {@code values} that cmd would not pass through unchanged, or null when all are * safe. Java quotes an argument with spaces, but cmd still reads operators such as {@code &} @@ -155,13 +175,7 @@ static File resolveNode( } List candidates = knownLocations; if (candidates == null) { - candidates = new ArrayList<>(nvmNodes(new File(home, ".nvm/versions/node"))); - File[] cellars = new File("/opt/homebrew/Cellar/nvm").listFiles(); - if (cellars != null) { - for (File cellar : cellars) { - candidates.addAll(nvmNodes(new File(cellar, "versions/node"))); - } - } + candidates = new ArrayList<>(nvmBinaries(home, "node")); candidates.add(new File("/opt/homebrew/bin/node")); candidates.add(new File("/usr/local/bin/node")); candidates.add(new File(home, ".local/bin/node")); @@ -220,6 +234,10 @@ private static File findOnPath(String name, Map environment, boo return null; } for (String dir : path.split(File.pathSeparator)) { + // Windows allows a quoted PATH entry, such as "C:\Program Files\nodejs". + if (isWindows && dir.length() >= 2 && dir.startsWith("\"") && dir.endsWith("\"")) { + dir = dir.substring(1, dir.length() - 1); + } if (dir.isEmpty()) { continue; } @@ -235,19 +253,34 @@ private static boolean isRunnable(File file) { return file.isFile() && file.canExecute(); } - /** {@code /vX.Y.Z/bin/node}, newest version first. */ - private static List nvmNodes(File root) { - List nodes = new ArrayList<>(); - File[] versions = root.listFiles(); - if (versions == null) { - return nodes; + /** + * {@code bin/} of each node version that nvm installed, in {@code ~/.nvm} and in + * Homebrew's nvm, newest version first. npm installs global packages such as posthog-cli + * there too. + */ + static List nvmBinaries(File home, String name) { + List roots = new ArrayList<>(); + roots.add(new File(home, ".nvm/versions/node")); + File[] cellars = new File("/opt/homebrew/Cellar/nvm").listFiles(); + if (cellars != null) { + for (File cellar : cellars) { + roots.add(new File(cellar, "versions/node")); + } } - List sorted = new ArrayList<>(Arrays.asList(versions)); - sorted.sort((a, b) -> compareVersions(versionParts(b.getName()), versionParts(a.getName()))); - for (File version : sorted) { - nodes.add(new File(version, "bin/node")); + List binaries = new ArrayList<>(); + for (File root : roots) { + File[] versions = root.listFiles(); + if (versions == null) { + continue; + } + List sorted = new ArrayList<>(Arrays.asList(versions)); + sorted.sort( + (a, b) -> compareVersions(versionParts(b.getName()), versionParts(a.getName()))); + for (File version : sorted) { + binaries.add(new File(version, "bin/" + name)); + } } - return nodes; + return binaries; } private static List versionParts(String name) { diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index cd8cc2cbc..8bba03bee 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -106,11 +106,19 @@ public class UploadSourcesMojo extends AbstractMojo { /** * The source directories to upload. Defaults to the project's compile source roots and the - * {@code } that kotlin-maven-plugin compiles. + * source directories that kotlin-maven-plugin compiles. Setting it replaces those defaults. */ @Parameter List sourceRoots; + /** + * More source directories to upload with {@code sourceRoots}, for example those of the other + * modules of a multi-module build. The SDK sends one id per application, so code from another + * module shows source code only when its sources are part of this upload. + */ + @Parameter + List additionalSourceRoots; + @Override public void execute() throws MojoExecutionException { // A file left by an earlier build would point this build's exceptions at that build's @@ -144,9 +152,14 @@ public void execute() throws MojoExecutionException { } boolean isWindows = PostHogCli.isWindows(); + String configured = configuredExecutable(); + if (configured != null && isPath(configured) && !isInstalledAt(configured, isWindows)) { + skipOrFail("posthog-cli was not found at " + configured + INSTALL_HINT, null); + return; + } String executable = PostHogCli.resolve( - cliExecutable, + configured, System.getenv(), new File(System.getProperty("user.home")), isWindows); @@ -161,6 +174,16 @@ public void execute() throws MojoExecutionException { List values = new ArrayList<>(args); values.add(0, executable); String unsafe = PostHogCli.firstUnsafeForCmd(values); + if (unsafe == null && PostHogCli.cmdSplitsPath(executable, args)) { + skipOrFail( + "posthog-cli (" + + executable + + ") runs through cmd, which cannot start a path with spaces" + + " together with an argument with spaces. Set" + + " posthog.cliExecutable to posthog-cli.exe, which runs directly.", + null); + return; + } if (unsafe != null) { skipOrFail( "posthog-cli (" @@ -178,13 +201,9 @@ public void execute() throws MojoExecutionException { try { // A posthog-cli from before `jvm upload` exits with an error on the unknown // subcommand, which would fail the build even when the upload is optional. - if (!supportsJvmUpload(executable, isWindows)) { - skipOrFail( - "posthog-cli (" - + executable - + ") is too old: it has no jvm upload command" - + UPDATE_HINT, - null); + String problem = jvmUploadProblem(executable, isWindows); + if (problem != null) { + skipOrFail(problem, null); return; } process = start(executable, args, isWindows); @@ -226,27 +245,71 @@ private String reasonToSkipOptionalUpload() { if (!CiEnvironment.isCi(environment)) { return "this is not a CI build"; } - if (session == null) { - return null; - } - if (session.isOffline()) { + if (isOffline()) { return "Maven runs offline"; } // The SDK reads the first posthog-meta.properties on the classpath, so a library's file // can replace the application's. - ProjectDependencyGraph graph = session.getProjectDependencyGraph(); - List dependents = - graph == null - ? Collections.emptyList() - : graph.getDownstreamProjects(project, false); + List dependents = dependentModules(); if (!dependents.isEmpty()) { return dependents.get(0).getArtifactId() + " depends on this module, so it is a library. Upload its sources from the" - + " application module with sourceRoots"; + + " application module with additionalSourceRoots"; } return null; } + boolean isOffline() { + return session != null && session.isOffline(); + } + + /** The modules of this build that depend on this one. */ + List dependentModules() { + ProjectDependencyGraph graph = session == null ? null : session.getProjectDependencyGraph(); + return graph == null + ? Collections.emptyList() + : graph.getDownstreamProjects(project, false); + } + + /** + * {@code cliExecutable} with a relative path resolved against the project directory, so that + * a reactor build started from the parent finds it. A bare name stays as it is, for a PATH + * lookup. + */ + private String configuredExecutable() { + if (!isNotBlank(cliExecutable)) { + return null; + } + String trimmed = cliExecutable.trim(); + if (!isPath(trimmed)) { + return trimmed; + } + File file = new File(trimmed); + if (!file.isAbsolute() && project.getBasedir() != null) { + file = new File(project.getBasedir(), trimmed); + } + return file.toPath().normalize().toString(); + } + + private static boolean isPath(String executable) { + return executable.contains("/") || executable.contains("\\"); + } + + // cmd also runs a path without its extension, as it runs a name from PATH. + private static boolean isInstalledAt(String path, boolean isWindows) { + if (new File(path).isFile()) { + return true; + } + if (isWindows) { + for (String extension : Arrays.asList(".exe", ".cmd", ".bat")) { + if (new File(path + extension).isFile()) { + return true; + } + } + } + return false; + } + List cliArguments(List roots) { List args = new ArrayList<>(); // A global option, so it goes before the subcommand. @@ -278,26 +341,53 @@ List cliArguments(List roots) { return args; } - private List existingSourceRoots() { + private List existingSourceRoots() throws MojoExecutionException { + Set defaults = new LinkedHashSet<>(); Set configured = new LinkedHashSet<>(); if (sourceRoots != null && !sourceRoots.isEmpty()) { - configured.addAll(sourceRoots); + for (File root : sourceRoots) { + configured.add(normalized(root)); + } } else { for (String root : project.getCompileSourceRoots()) { - configured.add(new File(root).getAbsoluteFile()); + defaults.add(normalized(new File(root))); + } + for (File root : kotlinSourceDirs()) { + defaults.add(normalized(root)); + } + } + if (additionalSourceRoots != null) { + for (File root : additionalSourceRoots) { + configured.add(normalized(root)); } - configured.addAll(kotlinSourceDirs()); } - List existing = new ArrayList<>(); - for (File root : configured) { + Set existing = new LinkedHashSet<>(); + for (File root : defaults) { if (root.isDirectory()) { existing.add(root); } else { getLog().debug("Skipping missing source root " + root); } } - return existing; + for (File root : configured) { + if (root.isDirectory()) { + existing.add(root); + continue; + } + // A configured directory that does not exist is usually a typo, which would leave + // its sources out of the upload unnoticed. + if (requireUpload) { + throw new MojoExecutionException("The source root " + root + " does not exist"); + } + getLog().warn("Skipping the source root " + root + ": it does not exist"); + } + return new ArrayList<>(existing); + } + + // Normalized, so that ${project.basedir}/. and the project directory count as one root. + private static File normalized(File file) { + return file.getAbsoluteFile().toPath().normalize().toFile(); } /** @@ -325,8 +415,8 @@ private List kotlinSourceDirs() { * otherwise the roots themselves. */ private List utf8Roots(List roots) throws MojoExecutionException { - Charset encoding = sourceEncoding(); - if (encoding == null || Utf8Sources.isUtf8(encoding)) { + Charset encoding = sourceEncoding(Charset.defaultCharset()); + if (Utf8Sources.isUtf8(encoding)) { return roots; } File buildDirectory = new File(project.getBuild().getDirectory()); @@ -340,10 +430,10 @@ private List utf8Roots(List roots) throws MojoExecutionException { /** * The encoding maven-compiler-plugin reads the sources in: its {@code encoding} parameter, - * else {@code project.build.sourceEncoding}. Null when neither is set, so the platform default - * applies, which is UTF-8 from Java 18 on. + * else {@code project.build.sourceEncoding}, else the platform default. The default is UTF-8 + * from Java 18 on, and often windows-1252 on Windows before that. */ - private Charset sourceEncoding() { + Charset sourceEncoding(Charset platformDefault) { String encoding = null; Plugin compiler = project.getPlugin(COMPILER_PLUGIN); if (compiler != null) { @@ -360,13 +450,13 @@ private Charset sourceEncoding() { encoding = project.getProperties().getProperty("project.build.sourceEncoding"); } if (!isNotBlank(encoding)) { - return null; + return platformDefault; } try { return Charset.forName(encoding.trim()); } catch (IllegalArgumentException e) { getLog().warn("Unknown source encoding " + encoding + ", uploading the sources as is"); - return null; + return StandardCharsets.UTF_8; } } @@ -418,10 +508,11 @@ private void skipOrFail(String message, Exception cause) throws MojoExecutionExc } /** - * Whether this posthog-cli has {@code jvm upload} with every option the plugin passes. It asks - * for the command's help, which needs no credentials and sends nothing to PostHog. + * Why this posthog-cli cannot run {@code jvm upload} with every option the plugin passes, or + * null when it can. It asks for the command's help, which needs no credentials and sends + * nothing to PostHog. */ - private boolean supportsJvmUpload(String executable, boolean isWindows) + private String jvmUploadProblem(String executable, boolean isWindows) throws IOException, MojoExecutionException { Process process = start(executable, Arrays.asList("jvm", "upload", "--help"), isWindows); StringBuilder help = new StringBuilder(); @@ -432,7 +523,26 @@ private boolean supportsJvmUpload(String executable, boolean isWindows) while ((line = reader.readLine()) != null) { help.append(line).append('\n'); } - return process.waitFor() == 0 && help.toString().contains("--skip-without-credentials"); + int exitCode = process.waitFor(); + String output = help.toString(); + getLog().debug("posthog-cli jvm upload --help exited with " + exitCode + ":\n" + output); + if (exitCode == 0 && output.contains("--skip-without-credentials")) { + return null; + } + // How clap rejects a subcommand or an option it does not know. + if (exitCode == 0 + || output.contains("unrecognized subcommand") + || output.contains("unexpected argument")) { + return "posthog-cli (" + executable + ") is too old: it has no jvm upload command" + + UPDATE_HINT; + } + String firstLine = output.trim().split("\n", 2)[0]; + return "Could not run posthog-cli (" + + executable + + "): it exited with code " + + exitCode + + (firstLine.isEmpty() ? "" : ": " + firstLine) + + INSTALL_HINT; } catch (InterruptedException e) { process.destroy(); Thread.currentThread().interrupt(); @@ -447,7 +557,8 @@ private Process start(String executable, List args, boolean isWindows) ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); if (project.getBasedir() != null) { - // posthog-cli reads the release's git details from its working directory. + // posthog-cli reads the release's git details from the repository of the first source + // root, which a standard build keeps inside the same repository as this directory. builder.directory(project.getBasedir()); } Map environment = builder.environment(); diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java index 6a7fb4da8..99e8f0224 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java @@ -38,11 +38,13 @@ static List copy( List roots, Charset encoding, File outputDirectory, File buildDirectory) throws IOException { deleteRecursively(outputDirectory.toPath()); - Path output = outputDirectory.toPath().toAbsolutePath(); - Path build = buildDirectory.toPath().toAbsolutePath(); + // Normalized, because a root such as ${project.basedir}/. would otherwise never equal the + // build directory inside it, and the walk would copy these copies into themselves. + Path output = outputDirectory.toPath().toAbsolutePath().normalize(); + Path build = buildDirectory.toPath().toAbsolutePath().normalize(); List copies = new ArrayList<>(); for (int index = 0; index < roots.size(); index++) { - Path root = roots.get(index).toPath().toAbsolutePath(); + Path root = roots.get(index).toPath().toAbsolutePath().normalize(); Path copyRoot = output.resolve(String.valueOf(index)); Files.createDirectories(copyRoot); Files.walkFileTree( diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index 04efcbbc0..05b77c6f1 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -3,22 +3,24 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.maven.execution.DefaultMavenExecutionRequest; -import org.apache.maven.execution.DefaultMavenExecutionResult; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.execution.ProjectDependencyGraph; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import javax.xml.parsers.DocumentBuilderFactory; import org.apache.maven.model.Build; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; @@ -30,6 +32,9 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; public class UploadSourcesMojoTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -37,7 +42,7 @@ public class UploadSourcesMojoTest { private File basedir; private File argsFile; private File classes; - private UploadSourcesMojo mojo; + private TestMojo mojo; @Before public void setUp() throws IOException { @@ -51,7 +56,7 @@ public void setUp() throws IOException { build.setOutputDirectory(new File(basedir, "target/classes").getAbsolutePath()); project.getModel().setBuild(build); - mojo = new UploadSourcesMojo(); + mojo = new TestMojo(); mojo.project = project; mojo.environment = Collections.singletonMap("CI", "true"); mojo.releaseName = "demo-app"; @@ -272,7 +277,7 @@ public void skipsWhenMavenRunsOffline() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); - mojo.session = session(true, Collections.emptyList()); + mojo.offline = true; mojo.execute(); @@ -287,7 +292,7 @@ public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); MavenProject app = new MavenProject(); app.setArtifactId("demo-app"); - mojo.session = session(false, Collections.singletonList(app)); + mojo.dependents = Collections.singletonList(app); mojo.execute(); @@ -305,7 +310,6 @@ public void uploadsAnApplicationThatNoModuleOfTheBuildDependsOn() throws Excepti assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); - mojo.session = session(false, Collections.emptyList()); mojo.execute(); @@ -625,37 +629,252 @@ private File oldCli() throws IOException { return cli; } - @SuppressWarnings("deprecation") - private static MavenSession session(boolean offline, final List dependents) { - DefaultMavenExecutionRequest request = new DefaultMavenExecutionRequest(); - request.setOffline(offline); - MavenSession session = - new MavenSession(null, null, request, new DefaultMavenExecutionResult()); - session.setProjectDependencyGraph( - new ProjectDependencyGraph() { - @Override - public List getAllProjects() { - return Collections.emptyList(); - } - - @Override - public List getSortedProjects() { - return Collections.emptyList(); - } - - @Override - public List getDownstreamProjects( - MavenProject project, boolean transitive) { - return dependents; - } - - @Override - public List getUpstreamProjects( - MavenProject project, boolean transitive) { - return Collections.emptyList(); - } - }); - return session; + @Test + public void utf8CopiesSkipTheBuildDirectoryOfAnUnnormalizedRoot() throws Exception { + File javaDir = sourceRoot("src/main/java/com/acme"); + Files.write( + new File(javaDir, "App.java").toPath(), + "package com.acme;\n// caf\u00e9\nclass App {}\n".getBytes(StandardCharsets.ISO_8859_1)); + File generated = sourceRoot("target/generated-sources/annotations/com/acme"); + Files.write( + new File(generated, "Gen.java").toPath(), + "package com.acme;\nclass Gen {}\n".getBytes(StandardCharsets.ISO_8859_1)); + File buildDir = new File(basedir, "target"); + File outDir = new File(buildDir, "posthog/utf8-sources"); + + for (File root : Arrays.asList(new File(basedir, "."), new File(basedir, "src/.."))) { + List copies = + Utf8Sources.copy( + Collections.singletonList(root), StandardCharsets.ISO_8859_1, outDir, buildDir); + + assertFalse(root.toString(), new File(copies.get(0), "target").exists()); + assertEquals( + "package com.acme;\n// caf\u00e9\nclass App {}\n", + new String( + Files.readAllBytes( + new File(copies.get(0), "src/main/java/com/acme/App.java").toPath()), + StandardCharsets.UTF_8)); + } + } + + @Test + public void additionalSourceRootsAddToTheDefaultRoots() throws Exception { + assumeUnix(); + File java = sourceRoot("src/main/java"); + File shared = sourceRoot("../shared/src/main/java"); + mojo.project.addCompileSourceRoot(java.getAbsolutePath()); + mojo.additionalSourceRoots = Collections.singletonList(new File(basedir, "../shared/src/main/java")); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + + mojo.execute(); + + List args = recordedArgs(); + assertTrue(args.toString(), args.contains(java.getAbsolutePath())); + assertTrue(args.toString(), args.contains(shared.toPath().normalize().toString())); + } + + @Test + public void aConfiguredSourceRootThatDoesNotExistFailsOnlyARequiredUpload() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + File typo = new File(basedir, "src/main/jav"); + mojo.additionalSourceRoots = Collections.singletonList(typo); + mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + + mojo.execute(); + + assertTrue(metaProperties().isFile()); + assertFalse(recordedArgs().contains(typo.getAbsolutePath())); + + mojo.requireUpload = true; + try { + mojo.execute(); + fail("expected a MojoExecutionException"); + } catch (MojoExecutionException e) { + assertTrue(e.getMessage(), e.getMessage().contains(typo + " does not exist")); + } + } + + @Test + public void anUnsetEncodingFallsBackToThePlatformDefault() { + Charset windows1252 = Charset.forName("windows-1252"); + + assertEquals(windows1252, mojo.sourceEncoding(windows1252)); + assertEquals(StandardCharsets.UTF_8, mojo.sourceEncoding(StandardCharsets.UTF_8)); + + mojo.project.getProperties().setProperty("project.build.sourceEncoding", "UTF-8"); + assertEquals(StandardCharsets.UTF_8, mojo.sourceEncoding(windows1252)); + } + + @Test + public void aCliThatCannotStartIsNotReportedAsTooOld() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + File cli = new File(temp.getRoot(), "broken-posthog-cli"); + Files.write( + cli.toPath(), + "#!/bin/sh\necho 'env: node: No such file or directory' >&2\nexit 127\n" + .getBytes(StandardCharsets.UTF_8)); + assertTrue(cli.setExecutable(true)); + mojo.cliExecutable = cli.getAbsolutePath(); + mojo.requireUpload = true; + + try { + mojo.execute(); + fail("expected a MojoExecutionException"); + } catch (MojoExecutionException e) { + assertTrue( + e.getMessage(), + e.getMessage().contains("exited with code 127: env: node: No such file or directory")); + assertFalse(e.getMessage(), e.getMessage().contains("too old")); + } + } + + @Test + public void aRelativeCliExecutableResolvesAgainstTheProject() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + File cli = new File(basedir, "tools/posthog-cli"); + assertTrue(cli.getParentFile().mkdirs()); + Files.copy(fakeCli(0, true).toPath(), cli.toPath()); + assertTrue(cli.setExecutable(true)); + mojo.cliExecutable = "tools/posthog-cli"; + + mojo.execute(); + + assertTrue(metaProperties().isFile()); + } + + @Test + public void cmdSplitsAPathWithSpacesOnlyNextToAnotherQuotedArgument() { + String spaced = "C:\\Users\\Jane Doe\\npm\\posthog-cli.cmd"; + + assertTrue( + PostHogCli.cmdSplitsPath( + spaced, Arrays.asList("--source", "C:\\Users\\Jane Doe\\src"))); + assertTrue(PostHogCli.cmdSplitsPath(spaced, Arrays.asList("--release-version", ""))); + assertFalse(PostHogCli.cmdSplitsPath(spaced, Arrays.asList("jvm", "upload", "--help"))); + assertFalse( + PostHogCli.cmdSplitsPath( + "C:\\npm\\posthog-cli.cmd", + Arrays.asList("--source", "C:\\Users\\Jane Doe\\src"))); + } + + @Test + public void resolveFindsACliThatNvmInstalledNewestFirst() throws Exception { + assumeUnix(); + File home = temp.newFolder("home"); + executable(new File(home, ".nvm/versions/node/v18.20.0/bin/posthog-cli")); + File newest = executable(new File(home, ".nvm/versions/node/v20.11.1/bin/posthog-cli")); + + assertEquals(newest, PostHogCli.nvmBinaries(home, "posthog-cli").get(0)); + Assume.assumeTrue( + "this machine has posthog-cli in a machine-wide location", + !new File("/opt/homebrew/bin/posthog-cli").exists() + && !new File("/usr/local/bin/posthog-cli").exists()); + assertEquals(newest.getAbsolutePath(), PostHogCli.resolve(null, env(""), home, false)); + } + + @Test + public void resolveOnWindowsAcceptsAQuotedPathEntry() throws Exception { + assumeUnix(); + File home = temp.newFolder("home"); + File dir = temp.newFolder("Program Files", "posthog"); + File exe = executable(new File(dir, "posthog-cli.exe")); + + assertEquals( + exe.getAbsolutePath(), + PostHogCli.resolve(null, env("\"" + dir.getAbsolutePath() + "\""), home, true)); + } + + @Test + public void thePluginDescriptorDeclaresTheGoalAsMavenReadsIt() throws Exception { + String jarPath = System.getProperty("posthog.pluginJar"); + Assume.assumeNotNull(jarPath); + Document descriptor; + try (JarFile jar = new JarFile(jarPath)) { + JarEntry entry = jar.getJarEntry("META-INF/maven/plugin.xml"); + assertNotNull("the jar has no META-INF/maven/plugin.xml", entry); + descriptor = + DocumentBuilderFactory.newInstance() + .newDocumentBuilder() + .parse(jar.getInputStream(entry)); + } + Element plugin = descriptor.getDocumentElement(); + assertEquals("com.posthog", childText(plugin, "groupId")); + assertEquals("posthog-maven-plugin", childText(plugin, "artifactId")); + assertEquals("posthog", childText(plugin, "goalPrefix")); + // Maven loads the plugin with nothing but its own jar. + NodeList dependencies = plugin.getElementsByTagName("dependency"); + assertEquals(0, dependencies.getLength()); + + Element mojo = (Element) plugin.getElementsByTagName("mojo").item(0); + assertEquals("upload-sources", childText(mojo, "goal")); + assertEquals("process-classes", childText(mojo, "phase")); + assertEquals("true", childText(mojo, "threadSafe")); + + Element configuration = (Element) mojo.getElementsByTagName("configuration").item(0); + Map expressions = new HashMap<>(); + Map defaults = new HashMap<>(); + NodeList values = configuration.getChildNodes(); + for (int i = 0; i < values.getLength(); i++) { + if (values.item(i) instanceof Element) { + Element value = (Element) values.item(i); + expressions.put(value.getNodeName(), value.getTextContent()); + defaults.put(value.getNodeName(), value.getAttribute("default-value")); + } + } + assertEquals("${posthog.skip}", expressions.get("skip")); + assertEquals("${posthog.requireUpload}", expressions.get("requireUpload")); + assertEquals("${posthog.cliExecutable}", expressions.get("cliExecutable")); + assertEquals("${posthog.dotenvFile}", expressions.get("dotenvFile")); + assertEquals("${posthog.releaseName}", expressions.get("releaseName")); + assertEquals("${posthog.releaseVersion}", expressions.get("releaseVersion")); + assertEquals("${project.artifactId}", defaults.get("releaseName")); + assertEquals("${project}", defaults.get("project")); + assertEquals("${session}", defaults.get("session")); + + List parameters = new ArrayList<>(); + NodeList names = + ((Element) mojo.getElementsByTagName("parameters").item(0)) + .getElementsByTagName("name"); + for (int i = 0; i < names.getLength(); i++) { + parameters.add(names.item(i).getTextContent()); + } + assertTrue( + parameters.toString(), + parameters.containsAll(Arrays.asList("sourceRoots", "additionalSourceRoots"))); + // The descriptor generator drops anything that looks like an HTML tag, such as + // {@code }, and keeps the empty Javadoc tag. + assertFalse( + "a parameter description lost a tag", + descriptor.getDocumentElement().getTextContent().contains("{@code }")); + } + + private static String childText(Element parent, String name) { + NodeList children = parent.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + if (children.item(i) instanceof Element && children.item(i).getNodeName().equals(name)) { + return children.item(i).getTextContent().trim(); + } + } + return null; + } + + /** The mojo with its session checks replaced, because every MavenSession constructor is deprecated. */ + private static final class TestMojo extends UploadSourcesMojo { + boolean offline; + List dependents = Collections.emptyList(); + + @Override + boolean isOffline() { + return offline; + } + + @Override + List dependentModules() { + return dependents; + } } private List recordedArgs() throws IOException { From 7c30ced74b30119cf35e23f97bddd8f7fa75ea89 Mon Sep 17 00:00:00 2001 From: Rafa Audibert Date: Wed, 2 Dec 2026 13:12:53 -0300 Subject: [PATCH 08/14] feat(maven-plugin): upload jvm sources with hog The upload-sources goal now runs `hog error-tracking process --kind jvm` instead of `posthog-cli jvm upload`, since only hog has the command. - Find hog the way the Android Gradle plugin does: PATH, then ~/.local/bin, nvm, /usr/local/bin and /opt/homebrew/bin, then the project's node_modules/.bin when node is installed. On Windows, search PATH with PATHEXT as cmd does, then ~/.local/bin/hog.exe, and run the hog.exe of the npm platform package instead of the hog.cmd shim. - Pass the dotenv file as HOG_DOTENV_FILE. - A missing hog skips with the install commands. Exit 3 skips as missing credentials, and exit 2, which an older hog returns for --kind jvm and --meta-out, skips with a `hog upgrade` hint. Every failure fails the build only when requireUpload is set. - Drop the plugin's deletes of posthog-meta.properties after a failed run, which hog guarantees. Keep the delete for builds that never start hog, and keep the UTF-8 copies, because hog skips non-UTF-8 files. Co-Authored-By: Claude Opus 5.5 --- .changeset/maven-plugin-upload-sources.md | 2 +- AGENTS.md | 2 +- posthog-maven-plugin/README.md | 26 +- .../java/com/posthog/maven/PostHogCli.java | 285 +++++++++----- .../com/posthog/maven/UploadSourcesMojo.java | 175 ++++----- .../java/com/posthog/maven/Utf8Sources.java | 6 +- .../posthog/maven/UploadSourcesMojoTest.java | 354 ++++++++++-------- 7 files changed, 471 insertions(+), 379 deletions(-) diff --git a/.changeset/maven-plugin-upload-sources.md b/.changeset/maven-plugin-upload-sources.md index 95502fc12..48882825b 100644 --- a/.changeset/maven-plugin-upload-sources.md +++ b/.changeset/maven-plugin-upload-sources.md @@ -2,4 +2,4 @@ "posthog-maven-plugin": minor --- -Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `posthog-cli jvm upload` to upload the project's sources and writes the id they were uploaded under and the id of the build's release into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures, and reports the build's release. By default only a CI build of an application module uploads, and a missing `posthog-cli`, missing credentials or a failed upload only logs a warning. Set `requireUpload` to upload from every build and fail it when the upload can't run. +Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `hog error-tracking process --kind jvm` to upload the project's sources and writes the id they were uploaded under and the id of the build's release into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures, and reports the build's release. By default only a CI build of an application module uploads, and a missing or outdated `hog`, missing credentials or a failed upload only logs a warning. Set `requireUpload` to upload from every build and fail it when the upload can't run. diff --git a/AGENTS.md b/AGENTS.md index 7cfea6f72..f38636a45 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ PostHog Android SDK monorepo. Kotlin-first, targets JVM and Android. - `posthog-android/` — Android-specific SDK (depends on `posthog/`) - `posthog-android-surveys-compose/` — Compose survey UI (depends on `posthog-android/`, transitively on `posthog/`) - `posthog-server/` — Server-side SDK (depends on `posthog/`) -- `posthog-maven-plugin/` — Maven plugin that uploads JVM sources for error tracking source context (pure Java, runs `posthog-cli`) +- `posthog-maven-plugin/` — Maven plugin that uploads JVM sources for error tracking source context (pure Java, runs `hog`) - `posthog-server-openfeature/` — OpenFeature provider for the server-side SDK (depends on `posthog-server/`, Java 11+) - `posthog-android-gradle-plugin/` — Gradle plugin for Android integrations - `posthog-samples/` — Sample apps diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index e88b7e1be..419678ae7 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -2,13 +2,13 @@ Uploads your application's Java and Kotlin sources to PostHog, so error tracking shows the source code around each frame of the exceptions your app captures. -On each CI build, the `upload-sources` goal runs [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) `jvm upload`. The CLI bundles the sources, uploads them under an id derived from their content, and writes that id and the id of the build's release into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads the file. It sends the first id on every exception frame, and PostHog looks up the uploaded sources by it. It sends the release id with every exception, and PostHog reports that release. +On each CI build, the `upload-sources` goal runs [`hog`](https://github.com/PostHog/posthog/tree/master/hog), PostHog's command line, as `hog error-tracking process --kind jvm`. hog bundles the sources, uploads them under an id derived from their content, and writes that id and the id of the build's release into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads the file. It sends the first id on every exception frame, and PostHog looks up the uploaded sources by it. It sends the release id with every exception, and PostHog reports that release. A build of unchanged code reuses the existing upload and sends no source files, also in a new release. Changed code gets a new id and a new upload. The goal rewrites or deletes the file on every build, so it always matches the code that was compiled and the release it belongs to. ## Requirements -- [`posthog-cli`](https://github.com/PostHog/posthog/tree/master/cli) with the `jvm upload` command, installed with `npm install -g @posthog/cli`, `brew install posthog/tap/posthog-cli`, or the install script. +- [`hog`](https://github.com/PostHog/posthog/tree/master/hog) in a release that uploads JVM sources. Install it with `curl -fsSL https://releases.posthog.com/hog/install.sh | sh`, `brew install posthog/tap/hog` or `npm install -g hog`, or on Windows with `irm https://releases.posthog.com/hog/install.ps1 | iex`. Update an older hog with `hog upgrade`. - `posthog-server` with `posthog-meta.properties` support, and no `releaseIdentifier` set in code (an explicit value wins over the file). - A personal API key with error tracking write access, for the upload. @@ -35,23 +35,23 @@ A build of unchanged code reuses the existing upload and sends no source files, The goal binds to the `process-classes` phase. It runs after compilation, so the upload includes the sources that annotation processors such as MapStruct generate, and `mvn package` uploads before it packages. A command that stops before that phase uploads nothing: run `mvn package jib:build` or `mvn process-classes jib:build`, not `mvn compile jib:build`. -`posthog-cli` reads sources as UTF-8. When `project.build.sourceEncoding` or the compiler's `encoding` names another encoding, the plugin uploads UTF-8 copies of the Java sources from `target/posthog/utf8-sources`. +hog reads sources as UTF-8, and skips a file that isn't UTF-8 with a warning. When `project.build.sourceEncoding` or the compiler's `encoding` names another encoding, the plugin uploads UTF-8 copies of the Java sources from `target/posthog/utf8-sources`. ### Releases -Each build belongs to a release, and its exceptions are attributed to it. The release name defaults to the artifact id, and the version defaults to the current git commit: `posthog-cli` reads it from the repository, or from the CI environment on GitHub Actions. So every deployed commit is its own release, even when the project version stays at `0.0.1-SNAPSHOT`. A build with no git commit, such as a Docker build that copies only the sources, has no release unless you set `releaseVersion`. Its exceptions still show source code. +Each build belongs to a release, and its exceptions are attributed to it. The release name defaults to the artifact id, and the version defaults to the current git commit: hog reads it from the repository, or from the CI environment on GitHub Actions. So every deployed commit is its own release, even when the project version stays at `0.0.1-SNAPSHOT`. A build with no git commit, such as a Docker build that copies only the sources, has no release unless you set `releaseVersion`. Its exceptions still show source code. Every build that uploads creates its release, also a build of a pull request. To keep your releases to what you deploy, pass `-Dposthog.skip=true` in CI jobs that don't deploy. ### Credentials -`posthog-cli` reads them from the environment, from a dotenv file, or from `posthog-cli login`: +hog reads them from the environment, from a dotenv file, from the CI job's OIDC token, or from `hog auth login`. See [hog's credentials](https://github.com/PostHog/posthog/tree/master/hog#credentials) for the OIDC setup, which needs no stored key. -- `POSTHOG_CLI_HOST`: your PostHog app host, for example `https://us.posthog.com` -- `POSTHOG_CLI_PROJECT_ID`: your project id -- `POSTHOG_CLI_API_KEY`: a personal API key with error tracking write access +- `HOG_HOST`: your PostHog app host, for example `https://us.posthog.com` +- `HOG_PROJECT_ID`: your project id +- `HOG_PERSONAL_API_KEY`: a personal API key with error tracking write access -To use a dotenv file, set `.env` or pass `-Dposthog.dotenvFile=.env`. +To use a dotenv file, set `.env` or pass `-Dposthog.dotenvFile=.env`. The plugin passes it to hog as `HOG_DOTENV_FILE`. ### When it uploads @@ -67,7 +67,7 @@ In a multi-module build, a module that another module of the build depends on is ``` -When the upload can't run, the plugin warns and the build continues. That happens when `posthog-cli` is missing or too old to have `jvm upload`, the credentials are missing, or the upload fails, for example because PostHog can't be reached. That build ships no id, so its exceptions show no source code. Every build also deletes the `posthog-meta.properties` an earlier build left behind, so the app never reports an id that belongs to other code. +When the upload can't run, the plugin warns and the build continues. That happens when hog is missing or too old to upload JVM sources, the credentials are missing, or the upload fails, for example because PostHog can't be reached. That build ships no id, so its exceptions show no source code. Every build also deletes the `posthog-meta.properties` an earlier build left behind, and hog writes a new one only after a successful upload, so the app never reports an id that belongs to other code. ### Requiring the upload @@ -81,14 +81,14 @@ Set it in the application module, not in a parent POM that library modules share |---|---|---|---| | `skip` | `posthog.skip` | `false` | Skip the upload. | | `requireUpload` | `posthog.requireUpload` | `false` | Upload from every build, also outside CI and in library modules, and fail the build when the upload can't run. | -| `cliExecutable` | `posthog.cliExecutable` | found automatically | Path to `posthog-cli`, relative to the project directory. Without it, the plugin checks `~/.posthog/posthog-cli`, then `PATH`, then Homebrew, `~/.cargo/bin`, `~/.local/bin` and nvm. On Windows, it runs `posthog-cli.exe` from `PATH`, or the binary of the npm package behind `posthog-cli.cmd`. | -| `dotenvFile` | `posthog.dotenvFile` | none | A dotenv file `posthog-cli` reads credentials from. | +| `cliExecutable` | `posthog.cliExecutable` | found automatically | Path to `hog`, relative to the project directory. Without it, the plugin checks `PATH`, then `~/.local/bin`, nvm, `/usr/local/bin` and `/opt/homebrew/bin`, then `node_modules/.bin` in the project directory and its parent, as the PostHog Android Gradle plugin does. On Windows, it checks `PATH` as cmd does, then `~/.local/bin/hog.exe`, and runs the binary of the npm package behind `hog.cmd`. | +| `dotenvFile` | `posthog.dotenvFile` | none | A dotenv file hog reads credentials from. | | `releaseName` | `posthog.releaseName` | `${project.artifactId}` | The release the build belongs to. | | `releaseVersion` | `posthog.releaseVersion` | the git commit | The version of that release. Set it to `${project.version}` if you bump the project version on every release. | | `sourceRoots` | none | the project's compile source roots, plus the `` of `kotlin-maven-plugin` | The directories to upload. Setting it replaces the default. | | `additionalSourceRoots` | none | none | More directories to upload with `sourceRoots`, such as those of other modules. | -The plugin uploads only `.java` and `.kt` files from these directories. +hog uploads only `.java` and `.kt` files from these directories. It keys each file by the package it declares, and skips hidden folders, `node_modules`, test source sets such as `src/test`, `build`, `target` and `out` folders next to a build file or `src` folder, and files over 1 MiB. ## What it doesn't cover yet diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java index dfcaadc5e..852f567fd 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java @@ -3,80 +3,183 @@ import java.io.File; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; +import java.util.Locale; import java.util.Map; -/** Finds posthog-cli and builds the command line that runs it. */ +/** + * Finds hog, PostHog's command line, and builds the command line that runs it. It looks for hog in + * the same places and order as the PostHog Android Gradle plugin. + */ final class PostHogCli { - static final String DEFAULT_EXECUTABLE = "posthog-cli"; + static final String EXECUTABLE = "hog"; + + static final String DOTENV_FILE_VARIABLE = "HOG_DOTENV_FILE"; + + /** hog's exit code when a person has to act first, such as logging in. */ + static final int EXIT_NEEDS_PERSON = 3; private static final String CMD_UNSAFE_CHARACTERS = "&|<>^%!\"\r\n"; + private static final String WINDOWS_DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD"; + private static final List NPM_PLATFORM_PACKAGES = + Arrays.asList("@posthog/hog-windows-x64", "@posthog/hog-windows-arm64"); private PostHogCli() {} /** - * Returns the posthog-cli to run, or null when none is installed. A configured path is used - * verbatim. On Windows, an npm shim counts only when the native binary it starts is found. - * Otherwise this checks {@code ~/.posthog/posthog-cli} first, the override location PostHog's - * Xcode build script also checks first, then PATH, then the common install locations - * (Homebrew, the installer script's {@code ~/.cargo/bin}, nvm) that a build launched from an - * IDE may not have on PATH. + * Returns the hog to run, or null when none is installed. A configured value other than a bare + * {@code hog} is used verbatim. + * + *

Outside Windows, this checks PATH, then where the install script, npm under nvm and + * Homebrew put hog, which a build launched from an IDE may not have on PATH, and last the npm + * launcher in {@code node_modules/.bin} of {@code workingDirectory} or its parent, when node is + * installed to run it. On Windows, it checks PATH as cmd does, then where the install script + * puts {@code hog.exe}. + * + *

{@code installLocations} and {@code nodeLocations} replace the default locations when they + * are not null. */ static String resolve( - String configured, Map environment, File home, boolean isWindows) { + String configured, + Map environment, + File home, + File workingDirectory, + boolean isWindows, + List installLocations, + List nodeLocations) { if (configured != null && !configured.trim().isEmpty()) { - return configured.trim(); + String trimmed = configured.trim(); + if (!trimmed.equals(EXECUTABLE)) { + return trimmed; + } } if (isWindows) { - File exe = findOnPath(DEFAULT_EXECUTABLE + ".exe", environment, true); - if (exe != null) { - return exe.getAbsolutePath(); + String onPath = findOnWindowsPath(environment); + if (onPath != null) { + return onPath; } - File shim = findOnPath(DEFAULT_EXECUTABLE + ".cmd", environment, true); - if (shim == null) { - return null; - } - // The npm shim only starts the native binary that the package installed. Running that - // binary directly keeps the arguments away from cmd, which would run a `&` in a path - // or a release version as a second command. Without the binary there is nothing to - // run: cmd would look up a bare name in the project directory before PATH, and could - // run a posthog-cli there instead of the installed one. - File npmExe = npmInstalledExe(shim); - return npmExe != null ? npmExe.getAbsolutePath() : null; + List locations = + installLocations != null ? installLocations : windowsInstallLocations(home); + File installed = firstRunnable(locations, true); + return installed != null ? installed.getAbsolutePath() : null; + } + + File onPath = findOnPath(EXECUTABLE, environment, false); + if (onPath != null) { + return onPath.getAbsolutePath(); } - File installed = new File(home, ".posthog/" + DEFAULT_EXECUTABLE); - if (isRunnable(installed)) { + List locations = + installLocations != null ? installLocations : unixInstallLocations(home); + File installed = firstRunnable(locations, false); + if (installed != null) { return installed.getAbsolutePath(); } - File onPath = findOnPath(DEFAULT_EXECUTABLE, environment, false); - if (onPath != null) { - return onPath.getAbsolutePath(); + List projectDirectories = new ArrayList<>(); + if (workingDirectory != null) { + projectDirectories.add(workingDirectory); + if (workingDirectory.getParentFile() != null) { + projectDirectories.add(workingDirectory.getParentFile()); + } + } + for (File directory : projectDirectories) { + File launcher = new File(directory, "node_modules/.bin/" + EXECUTABLE); + if (isRunnable(launcher, false) + && resolveNode(environment, home, false, nodeLocations) != null) { + return launcher.getAbsolutePath(); + } } + return null; + } - List knownLocations = - new ArrayList<>( - Arrays.asList( - new File("/opt/homebrew/bin/" + DEFAULT_EXECUTABLE), - new File("/usr/local/bin/" + DEFAULT_EXECUTABLE), - new File(home, ".cargo/bin/" + DEFAULT_EXECUTABLE), - new File(home, ".local/bin/" + DEFAULT_EXECUTABLE))); - knownLocations.addAll(nvmBinaries(home, DEFAULT_EXECUTABLE)); - for (File candidate : knownLocations) { - if (isRunnable(candidate)) { - return candidate.getAbsolutePath(); + /** + * Finds hog the way cmd does, trying each PATHEXT extension in each PATH folder. A native + * {@code hog.exe} runs directly. Any other hit, such as the npm {@code hog.cmd} shim, gives way + * to the {@code hog.exe} of the npm platform package next to it, so the arguments never pass + * through cmd. Without one, the shim runs through cmd. + */ + private static String findOnWindowsPath(Map environment) { + String path = variable(environment, "PATH", true); + if (path == null) { + return null; + } + String pathExt = variable(environment, "PATHEXT", true); + List extensions = new ArrayList<>(); + for (String extension : (pathExt != null ? pathExt : WINDOWS_DEFAULT_PATHEXT).split(";")) { + if (!extension.trim().isEmpty()) { + extensions.add(extension.trim().toLowerCase(Locale.ROOT)); + } + } + + for (String directory : pathEntries(path, true)) { + for (String extension : extensions) { + File launcher = new File(directory, EXECUTABLE + extension); + if (!isRunnable(launcher, true)) { + continue; + } + if (extension.equals(".exe")) { + return launcher.getAbsolutePath(); + } + File npmExe = npmInstalledExe(launcher); + return npmExe != null ? npmExe.getAbsolutePath() : launcher.getAbsolutePath(); } } + return null; + } + + /** + * The {@code hog.exe} of the npm platform package that the {@code hog.cmd} shim starts, which + * has {@code hog-worker.exe} next to it. A global install puts the shim in the npm prefix, next + * to {@code node_modules}. A project install puts it in {@code node_modules/.bin}. The platform + * package sits next to the {@code hog} package, or inside it. + */ + static File npmInstalledExe(File shim) { + File shimDirectory = shim.getAbsoluteFile().getParentFile(); + List nodeModules = new ArrayList<>(); + nodeModules.add(new File(shimDirectory, "node_modules")); + if (shimDirectory.getParentFile() != null) { + nodeModules.add(shimDirectory.getParentFile()); + } + for (File modules : nodeModules) { + for (String platformPackage : NPM_PLATFORM_PACKAGES) { + String binary = platformPackage + "/bin/" + EXECUTABLE + ".exe"; + for (File candidate : + Arrays.asList( + new File(modules, binary), + new File(modules, EXECUTABLE + "/node_modules/" + binary))) { + if (candidate.isFile()) { + return candidate; + } + } + } + } return null; } + // install.ps1 puts hog.exe here and adds the folder to the user PATH, which a build started + // before the install does not see. + private static List windowsInstallLocations(File home) { + return Collections.singletonList(new File(home, ".local/bin/" + EXECUTABLE + ".exe")); + } + + private static List unixInstallLocations(File home) { + List locations = new ArrayList<>(); + locations.add(new File(home, ".local/bin/" + EXECUTABLE)); + locations.addAll(nvmBinaries(home, EXECUTABLE)); + locations.add(new File("/usr/local/bin/" + EXECUTABLE)); + locations.add(new File("/opt/homebrew/bin/" + EXECUTABLE)); + return locations; + } + /** - * On Windows a bare name may be the npm posthog-cli.cmd shim, which only cmd can find and run. - * An .exe runs directly, which also keeps cmd from mangling a quoted path with spaces. + * On Windows a path that is not an .exe is a launcher such as the npm {@code hog.cmd} shim, + * which only cmd can run. An .exe runs directly, which also keeps cmd from mangling a quoted + * path with spaces. */ static List commandLine(String executable, List args, boolean isWindows) { List command = new ArrayList<>(); @@ -90,7 +193,7 @@ static List commandLine(String executable, List args, boolean is } static boolean runsThroughCmd(String executable, boolean isWindows) { - return isWindows && !executable.toLowerCase().endsWith(".exe"); + return isWindows && !executable.toLowerCase(Locale.ROOT).endsWith(".exe"); } /** @@ -129,10 +232,10 @@ static String firstUnsafeForCmd(List values) { } /** - * The PATH for the CLI process, with the CLI's directory and node's directory first when PATH - * lacks them. An npm install of posthog-cli is a {@code #!/usr/bin/env node} launcher, and a - * build started from an IDE may have neither the launcher's directory nor node on its PATH. - * Returns null when the PATH needs no change. + * The PATH for the hog process, with hog's directory and node's directory first when PATH lacks + * them. An npm install of hog is a {@code #!/usr/bin/env node} launcher, and a build started + * from an IDE may have neither the launcher's directory nor node on its PATH. Returns null when + * the PATH needs no change. */ static String launcherPath( String executable, @@ -140,7 +243,7 @@ static String launcherPath( File home, boolean isWindows, List knownNodeLocations) { - String path = pathValue(environment, isWindows); + String path = variable(environment, "PATH", isWindows); List onPath = path == null ? new ArrayList<>() : Arrays.asList(path.split(File.pathSeparator)); List missing = new ArrayList<>(); @@ -156,6 +259,7 @@ static String launcherPath( if (missing.isEmpty()) { return null; } + List entries = new ArrayList<>(new LinkedHashSet<>(missing)); if (path != null && !path.isEmpty()) { entries.add(path); @@ -173,45 +277,20 @@ static File resolveNode( if (onPath != null || isWindows) { return onPath; } + List candidates = knownLocations; if (candidates == null) { candidates = new ArrayList<>(nvmBinaries(home, "node")); - candidates.add(new File("/opt/homebrew/bin/node")); candidates.add(new File("/usr/local/bin/node")); + candidates.add(new File("/opt/homebrew/bin/node")); candidates.add(new File(home, ".local/bin/node")); } - for (File candidate : candidates) { - if (isRunnable(candidate)) { - return candidate.getAbsoluteFile(); - } - } - return null; - } - - /** - * The native binary of the npm package, which npm installs into - * {@code node_modules/@posthog/cli/node_modules/.bin_real}. A global install puts the shim in - * the npm prefix, next to {@code node_modules}. A project install puts it in {@code - * node_modules/.bin}. - */ - static File npmInstalledExe(File shim) { - File shimDirectory = shim.getAbsoluteFile().getParentFile(); - String binary = "@posthog/cli/node_modules/.bin_real/" + DEFAULT_EXECUTABLE + ".exe"; - List candidates = new ArrayList<>(); - candidates.add(new File(shimDirectory, "node_modules/" + binary)); - if (shimDirectory.getParentFile() != null) { - candidates.add(new File(shimDirectory.getParentFile(), binary)); - } - for (File candidate : candidates) { - if (candidate.isFile()) { - return candidate; - } - } - return null; + File node = firstRunnable(candidates, false); + return node != null ? node.getAbsoluteFile() : null; } static boolean isWindows() { - return System.getProperty("os.name", "").toLowerCase().contains("win"); + return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win"); } /** The PATH key of {@code environment}. Windows spells it Path, and is case-insensitive. */ @@ -224,39 +303,60 @@ static String pathKey(Map environment, boolean isWindows) { return "PATH"; } - private static String pathValue(Map environment, boolean isWindows) { - return environment.get(pathKey(environment, isWindows)); + // Windows variable names are case-insensitive, and Java keeps whichever case the system used. + private static String variable(Map environment, String name, boolean isWindows) { + for (Map.Entry entry : environment.entrySet()) { + if (isWindows ? entry.getKey().equalsIgnoreCase(name) : entry.getKey().equals(name)) { + return entry.getValue(); + } + } + return null; } - private static File findOnPath(String name, Map environment, boolean isWindows) { - String path = pathValue(environment, isWindows); - if (path == null) { - return null; - } + private static List pathEntries(String path, boolean isWindows) { + List entries = new ArrayList<>(); for (String dir : path.split(File.pathSeparator)) { // Windows allows a quoted PATH entry, such as "C:\Program Files\nodejs". if (isWindows && dir.length() >= 2 && dir.startsWith("\"") && dir.endsWith("\"")) { dir = dir.substring(1, dir.length() - 1); } - if (dir.isEmpty()) { - continue; + if (!dir.isEmpty()) { + entries.add(dir); } + } + return entries; + } + + private static File findOnPath(String name, Map environment, boolean isWindows) { + String path = variable(environment, "PATH", isWindows); + if (path == null) { + return null; + } + for (String dir : pathEntries(path, isWindows)) { File candidate = new File(dir, name); - if (isRunnable(candidate)) { + if (isRunnable(candidate, isWindows)) { return candidate; } } return null; } - private static boolean isRunnable(File file) { - return file.isFile() && file.canExecute(); + private static File firstRunnable(List candidates, boolean isWindows) { + for (File candidate : candidates) { + if (isRunnable(candidate, isWindows)) { + return candidate; + } + } + return null; + } + + private static boolean isRunnable(File file, boolean isWindows) { + return file.isFile() && (isWindows || file.canExecute()); } /** * {@code bin/} of each node version that nvm installed, in {@code ~/.nvm} and in - * Homebrew's nvm, newest version first. npm installs global packages such as posthog-cli - * there too. + * Homebrew's nvm, newest version first. npm installs global packages such as hog there too. */ static List nvmBinaries(File home, String name) { List roots = new ArrayList<>(); @@ -267,6 +367,7 @@ static List nvmBinaries(File home, String name) { roots.add(new File(cellar, "versions/node")); } } + List binaries = new ArrayList<>(); for (File root : roots) { File[] versions = root.listFiles(); diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index 8bba03bee..fd0aa2f33 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -32,9 +32,9 @@ * startup, sends the first id on every exception frame, and sends the release id with every * exception. * - *

Runs {@code posthog-cli jvm upload} after compilation, so the upload includes the sources that - * annotation processors generate. The file goes into the classes directory, never into {@code - * src}, so every build carries the id of the sources it compiled. + *

Runs {@code hog error-tracking process --kind jvm} after compilation, so the upload includes the + * sources that annotation processors generate. The file goes into the classes directory, never into + * {@code src}, so every build carries the id of the sources it compiled. * *

Unless {@code requireUpload} is set, only a CI build of an application module uploads, and a * problem with the upload never fails the build. @@ -43,14 +43,21 @@ public class UploadSourcesMojo extends AbstractMojo { static final String META_PROPERTIES_FILE = "posthog-meta.properties"; + private static final int EXIT_USAGE = 2; + private static final String KOTLIN_MAVEN_PLUGIN = "org.jetbrains.kotlin:kotlin-maven-plugin"; private static final String COMPILER_PLUGIN = "org.apache.maven.plugins:maven-compiler-plugin"; - private static final String INSTALL_HINT = - ". Install it (npm install -g @posthog/cli) or set posthog.cliExecutable."; - private static final String UPDATE_HINT = - ". Update it (npm install -g @posthog/cli@latest or brew upgrade posthog-cli) or set" - + " posthog.cliExecutable."; + private static final String UNIX_INSTALL_HINT = + " Install hog (curl -fsSL https://releases.posthog.com/hog/install.sh | sh, brew install" + + " posthog/tap/hog, or npm install -g hog) or set posthog.cliExecutable."; + private static final String WINDOWS_INSTALL_HINT = + " Install hog (irm https://releases.posthog.com/hog/install.ps1 | iex, or npm install -g" + + " hog) or set posthog.cliExecutable."; + private static final String UPDATE_HINT = " Update hog with `hog upgrade`."; + private static final String CREDENTIALS_HINT = + " Set HOG_PERSONAL_API_KEY and HOG_PROJECT_ID, set posthog.dotenvFile, or run hog auth" + + " login."; @Parameter(defaultValue = "${project}", readonly = true, required = true) MavenProject project; @@ -67,7 +74,7 @@ public class UploadSourcesMojo extends AbstractMojo { /** * Makes the upload required. By default only a CI build of an application module uploads, so - * local builds do not upload work in progress or need the network. When posthog-cli or PostHog + * local builds do not upload work in progress or need the network. When hog or PostHog * credentials are missing, or the upload fails, the plugin warns and the build goes on without * an id. With this set, every build uploads, also outside CI, and each of those problems fails * the build. Set it in the build that deploys the application, for example in a Dockerfile, @@ -77,16 +84,17 @@ public class UploadSourcesMojo extends AbstractMojo { boolean requireUpload; /** - * Path to posthog-cli. When unset, the plugin looks in {@code ~/.posthog/posthog-cli}, then on - * PATH, then in common install locations. + * Path to hog. When unset, or set to {@code hog}, the plugin looks on PATH, then in common + * install locations, then in the project's {@code node_modules/.bin}. */ @Parameter(property = "posthog.cliExecutable") String cliExecutable; /** - * A dotenv file posthog-cli reads its credentials from ({@code POSTHOG_CLI_HOST}, {@code - * POSTHOG_CLI_PROJECT_ID}, {@code POSTHOG_CLI_API_KEY}). Without one, posthog-cli reads the - * environment and the credentials saved by {@code posthog-cli login}. + * A dotenv file hog reads its credentials from ({@code HOG_PERSONAL_API_KEY}, {@code + * HOG_PROJECT_ID}, {@code HOG_HOST}), passed to hog as {@code HOG_DOTENV_FILE}. Without one, + * hog reads the environment, the CI job's OIDC token, and the login saved by {@code hog auth + * login}. */ @Parameter(property = "posthog.dotenvFile") File dotenvFile; @@ -96,7 +104,7 @@ public class UploadSourcesMojo extends AbstractMojo { String releaseName; /** - * The version of that release. When unset, posthog-cli uses the current git commit, from the + * The version of that release. When unset, hog uses the current git commit, from the * repository or from the CI environment, so every deployed commit is its own release. A * project version such as {@code 0.0.1-SNAPSHOT} often stays the same across deploys. A build * with no git commit and no version has no release, so its exceptions report none. @@ -122,7 +130,8 @@ public class UploadSourcesMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { // A file left by an earlier build would point this build's exceptions at that build's - // sources, so it goes first, and a skipped or failed run leaves no id behind. + // sources. hog removes it whenever it runs, and this covers the builds that never start + // hog. deleteStaleMetaProperties(); if (skip) { @@ -152,9 +161,10 @@ public void execute() throws MojoExecutionException { } boolean isWindows = PostHogCli.isWindows(); + String installHint = isWindows ? WINDOWS_INSTALL_HINT : UNIX_INSTALL_HINT; String configured = configuredExecutable(); if (configured != null && isPath(configured) && !isInstalledAt(configured, isWindows)) { - skipOrFail("posthog-cli was not found at " + configured + INSTALL_HINT, null); + skipOrFail("hog was not found at " + configured + "." + installHint, null); return; } String executable = @@ -162,36 +172,38 @@ public void execute() throws MojoExecutionException { configured, System.getenv(), new File(System.getProperty("user.home")), - isWindows); + project.getBasedir(), + isWindows, + null, + null); if (executable == null) { - skipOrFail("posthog-cli was not found" + INSTALL_HINT, null); + skipOrFail("hog was not found." + installHint, null); return; } roots = utf8Roots(roots); - List args = cliArguments(roots); + List args = hogArguments(roots); if (PostHogCli.runsThroughCmd(executable, isWindows)) { List values = new ArrayList<>(args); values.add(0, executable); String unsafe = PostHogCli.firstUnsafeForCmd(values); if (unsafe == null && PostHogCli.cmdSplitsPath(executable, args)) { skipOrFail( - "posthog-cli (" + "hog (" + executable + ") runs through cmd, which cannot start a path with spaces" + " together with an argument with spaces. Set" - + " posthog.cliExecutable to posthog-cli.exe, which runs directly.", + + " posthog.cliExecutable to hog.exe, which runs directly.", null); return; } if (unsafe != null) { skipOrFail( - "posthog-cli (" + "hog (" + executable + ") runs through cmd, which would not pass this value unchanged: " + unsafe - + ". Set posthog.cliExecutable to posthog-cli.exe, which runs" - + " directly.", + + ". Set posthog.cliExecutable to hog.exe, which runs directly.", null); return; } @@ -199,44 +211,40 @@ public void execute() throws MojoExecutionException { Process process; try { - // A posthog-cli from before `jvm upload` exits with an error on the unknown - // subcommand, which would fail the build even when the upload is optional. - String problem = jvmUploadProblem(executable, isWindows); - if (problem != null) { - skipOrFail(problem, null); - return; - } process = start(executable, args, isWindows); } catch (IOException e) { - skipOrFail("Could not run posthog-cli (" + executable + ")" + INSTALL_HINT, e); + skipOrFail("Could not run hog (" + executable + ")." + installHint, e); return; } int exitCode; try { exitCode = waitFor(process); } catch (IOException e) { - deleteStaleMetaProperties(); - skipOrFail("Could not read the posthog-cli output.", e); + skipOrFail("Could not read the hog output.", e); + return; + } + if (exitCode == PostHogCli.EXIT_NEEDS_PERSON) { + skipOrFail( + "hog found no PostHog credentials, or needs a person to act first, as its" + + " output above says." + + CREDENTIALS_HINT, + null); + return; + } + if (exitCode == EXIT_USAGE) { + // A hog from before JVM source uploads rejects --kind jvm and --meta-out as a usage + // error. + skipOrFail("hog exited with code " + exitCode + "." + UPDATE_HINT, null); return; } if (exitCode != 0) { - // posthog-cli writes the file only after a successful upload, but an id from a failed - // run must never ship. - deleteStaleMetaProperties(); - skipOrFail("posthog-cli exited with code " + exitCode + ".", null); + skipOrFail("hog exited with code " + exitCode + ".", null); return; } File written = new File(classesDirectory(), META_PROPERTIES_FILE); if (!written.isFile()) { - if (requireUpload) { - throw new MojoExecutionException( - "posthog-cli exited successfully but did not write " + written); - } - // posthog-cli skips the upload when it finds no credentials, and logs why. - getLog().warn( - "The PostHog source upload was skipped, so exceptions from this build show no" - + " source code. Set posthog.requireUpload to fail the build instead."); + skipOrFail("hog exited successfully but did not write " + written + ".", null); } } @@ -310,26 +318,19 @@ private static boolean isInstalledAt(String path, boolean isWindows) { return false; } - List cliArguments(List roots) { + List hogArguments(List roots) { List args = new ArrayList<>(); - // A global option, so it goes before the subcommand. - if (dotenvFile != null) { - args.add("--dotenv-file"); - args.add(dotenvFile.getAbsolutePath()); - } - args.add("jvm"); - args.add("upload"); + args.add("error-tracking"); + args.add("process"); for (File root : roots) { - args.add("--source"); args.add(root.getAbsolutePath()); } + args.add("--kind"); + args.add("jvm"); // process-resources has already copied the resources, so the file goes straight into the // classes directory that the jar, war and Spring Boot archive are built from. args.add("--meta-out"); args.add(classesDirectory().getAbsolutePath()); - if (!requireUpload) { - args.add("--skip-without-credentials"); - } if (isNotBlank(releaseName)) { args.add("--release-name"); args.add(releaseName); @@ -338,6 +339,9 @@ List cliArguments(List roots) { args.add("--release-version"); args.add(releaseVersion); } + // hog prints JSON when its output is a pipe. Text keeps the build log readable. + args.add("-o"); + args.add("text"); return args; } @@ -507,49 +511,6 @@ private void skipOrFail(String message, Exception cause) throws MojoExecutionExc + " no source code. Set posthog.requireUpload to fail the build instead."); } - /** - * Why this posthog-cli cannot run {@code jvm upload} with every option the plugin passes, or - * null when it can. It asks for the command's help, which needs no credentials and sends - * nothing to PostHog. - */ - private String jvmUploadProblem(String executable, boolean isWindows) - throws IOException, MojoExecutionException { - Process process = start(executable, Arrays.asList("jvm", "upload", "--help"), isWindows); - StringBuilder help = new StringBuilder(); - try (BufferedReader reader = - new BufferedReader( - new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { - String line; - while ((line = reader.readLine()) != null) { - help.append(line).append('\n'); - } - int exitCode = process.waitFor(); - String output = help.toString(); - getLog().debug("posthog-cli jvm upload --help exited with " + exitCode + ":\n" + output); - if (exitCode == 0 && output.contains("--skip-without-credentials")) { - return null; - } - // How clap rejects a subcommand or an option it does not know. - if (exitCode == 0 - || output.contains("unrecognized subcommand") - || output.contains("unexpected argument")) { - return "posthog-cli (" + executable + ") is too old: it has no jvm upload command" - + UPDATE_HINT; - } - String firstLine = output.trim().split("\n", 2)[0]; - return "Could not run posthog-cli (" - + executable - + "): it exited with code " - + exitCode - + (firstLine.isEmpty() ? "" : ": " + firstLine) - + INSTALL_HINT; - } catch (InterruptedException e) { - process.destroy(); - Thread.currentThread().interrupt(); - throw new MojoExecutionException("Interrupted while waiting for posthog-cli", e); - } - } - private Process start(String executable, List args, boolean isWindows) throws IOException { List command = PostHogCli.commandLine(executable, args, isWindows); @@ -557,11 +518,13 @@ private Process start(String executable, List args, boolean isWindows) ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); if (project.getBasedir() != null) { - // posthog-cli reads the release's git details from the repository of the first source - // root, which a standard build keeps inside the same repository as this directory. + // hog reads the release's git details and posthog.json from this directory. builder.directory(project.getBasedir()); } Map environment = builder.environment(); + if (dotenvFile != null) { + environment.put(PostHogCli.DOTENV_FILE_VARIABLE, dotenvFile.getAbsolutePath()); + } String path = PostHogCli.launcherPath( executable, @@ -581,7 +544,7 @@ private int waitFor(Process process) throws IOException, MojoExecutionException new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { - getLog().info("[posthog-cli] " + line); + getLog().info("[hog] " + line); } return process.waitFor(); } catch (IOException e) { @@ -590,7 +553,7 @@ private int waitFor(Process process) throws IOException, MojoExecutionException } catch (InterruptedException e) { process.destroy(); Thread.currentThread().interrupt(); - throw new MojoExecutionException("Interrupted while waiting for posthog-cli", e); + throw new MojoExecutionException("Interrupted while waiting for hog", e); } } diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java index 99e8f0224..b5e0242ed 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java @@ -17,9 +17,9 @@ import java.util.stream.Stream; /** - * Copies source roots with UTF-8 text. posthog-cli reads every source file as UTF-8 and skips a - * file it cannot decode, so a project whose Java sources use another encoding would upload - * without them. + * Copies source roots with UTF-8 text. hog reads every source file as UTF-8 and skips, with a + * warning, a file it cannot decode, so a project whose Java sources use another encoding would + * upload without them. */ final class Utf8Sources { private Utf8Sources() {} diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index 05b77c6f1..10168c870 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -41,13 +41,15 @@ public class UploadSourcesMojoTest { private File basedir; private File argsFile; + private File envFile; private File classes; private TestMojo mojo; @Before public void setUp() throws IOException { basedir = temp.newFolder("project"); - argsFile = new File(temp.getRoot(), "cli-args.txt"); + argsFile = new File(temp.getRoot(), "hog-args.txt"); + envFile = new File(temp.getRoot(), "hog-dotenv-file.txt"); MavenProject project = new MavenProject(); project.setFile(new File(basedir, "pom.xml")); @@ -73,28 +75,30 @@ public void uploadsExistingSourceRootsAndWritesTheIdIntoTheClasses() throws Exce mojo.project.addCompileSourceRoot(new File(basedir, "src/main/missing").getAbsolutePath()); mojo.project.addCompileSourceRoot(kotlin.getAbsolutePath()); mojo.dotenvFile = new File(basedir, ".env"); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); assertEquals( Arrays.asList( - "--dotenv-file", - mojo.dotenvFile.getAbsolutePath(), - "jvm", - "upload", - "--source", + "error-tracking", + "process", java.getAbsolutePath(), - "--source", kotlin.getAbsolutePath(), + "--kind", + "jvm", "--meta-out", classes.getAbsolutePath(), - "--skip-without-credentials", "--release-name", "demo-app", "--release-version", - "1.2.3"), + "1.2.3", + "-o", + "text"), recordedArgs()); + assertEquals( + Collections.singletonList(mojo.dotenvFile.getAbsolutePath()), + Files.readAllLines(envFile.toPath(), StandardCharsets.UTF_8)); assertTrue(metaProperties().isFile()); } @@ -121,15 +125,14 @@ public void kotlinSourceDirsAreUploadedWithTheCompileSourceRoots() throws Except plugin.setArtifactId("kotlin-maven-plugin"); plugin.addExecution(compile); mojo.project.getBuild().addPlugin(plugin); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); assertEquals( - Arrays.asList( - "--source", java.getAbsolutePath(), "--source", kotlin.getAbsolutePath()), - recordedArgs().subList(2, 6)); - assertEquals("--meta-out", recordedArgs().get(6)); + Arrays.asList(java.getAbsolutePath(), kotlin.getAbsolutePath()), + recordedArgs().subList(2, 4)); + assertEquals("--kind", recordedArgs().get(4)); } @Test @@ -140,19 +143,21 @@ public void configuredSourceRootsReplaceTheCompileSourceRoots() throws Exception mojo.sourceRoots = Collections.singletonList(custom); mojo.releaseName = " "; mojo.releaseVersion = null; - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); assertEquals( Arrays.asList( - "jvm", - "upload", - "--source", + "error-tracking", + "process", custom.getAbsolutePath(), + "--kind", + "jvm", "--meta-out", classes.getAbsolutePath(), - "--skip-without-credentials"), + "-o", + "text"), recordedArgs()); } @@ -180,12 +185,12 @@ public void javaSourcesInAnotherEncodingAreUploadedAsUtf8() throws Exception { compiler.setArtifactId("maven-compiler-plugin"); compiler.setConfiguration(configuration); mojo.project.getBuild().addPlugin(compiler); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); File copy = new File(basedir, "target/posthog/utf8-sources/0"); - assertEquals(Arrays.asList("--source", copy.getAbsolutePath()), recordedArgs().subList(2, 4)); + assertEquals(copy.getAbsolutePath(), recordedArgs().get(2)); assertEquals( "package com.acme;\n// 5 \u20ac\nclass Price {}\n", new String( @@ -199,14 +204,14 @@ public void javaSourcesInAnotherEncodingAreUploadedAsUtf8() throws Exception { public void anNpmLauncherRunsWhenNeitherItNorNodeIsOnPath() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - // npm links posthog-cli to a `#!/usr/bin/env node` script next to node, in a directory - // such as /opt/homebrew/bin that a build started from an IDE may not have on PATH. + // npm links hog to a `#!/usr/bin/env node` script next to node, in a directory such as + // /opt/homebrew/bin that a build started from an IDE may not have on PATH. File npmBin = temp.newFolder("npm-bin"); File node = new File(npmBin, "node"); Files.write(node.toPath(), "#!/bin/sh\nexec /bin/sh \"$@\"\n".getBytes(StandardCharsets.UTF_8)); assertTrue(node.setExecutable(true)); - File launcher = new File(npmBin, "posthog-cli"); - String script = new String(Files.readAllBytes(fakeCli(0, true).toPath()), StandardCharsets.UTF_8); + File launcher = new File(npmBin, "hog"); + String script = new String(Files.readAllBytes(fakeHog(0, true).toPath()), StandardCharsets.UTF_8); Files.write( launcher.toPath(), script.replace("#!/bin/sh", "#!/usr/bin/env node").getBytes(StandardCharsets.UTF_8)); @@ -219,37 +224,49 @@ public void anNpmLauncherRunsWhenNeitherItNorNodeIsOnPath() throws Exception { } @Test - public void aFailedUploadThatIsNotRequiredWarnsAndShipsNoId() throws Exception { + public void aFailedUploadFailsOnlyARequiredUpload() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(3, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(1, false).getAbsolutePath(); mojo.execute(); assertFalse(metaProperties().exists()); + + mojo.requireUpload = true; + try { + mojo.execute(); + fail("expected a MojoExecutionException"); + } catch (MojoExecutionException e) { + assertTrue(e.getMessage(), e.getMessage().contains("exited with code 1")); + } } @Test - public void aRequiredUploadFailsTheBuildWhenTheCliFails() throws Exception { + public void missingCredentialsFailOnlyARequiredUpload() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(3, false).getAbsolutePath(); - mojo.requireUpload = true; + mojo.cliExecutable = fakeHog(PostHogCli.EXIT_NEEDS_PERSON, false).getAbsolutePath(); + + mojo.execute(); + assertFalse(metaProperties().exists()); + + mojo.requireUpload = true; try { mojo.execute(); fail("expected a MojoExecutionException"); } catch (MojoExecutionException e) { - assertTrue(e.getMessage(), e.getMessage().contains("exited with code 3")); + assertTrue(e.getMessage(), e.getMessage().contains("found no PostHog credentials")); + assertTrue(e.getMessage(), e.getMessage().contains("HOG_PERSONAL_API_KEY")); } - assertFalse(metaProperties().exists()); } @Test public void skipsOutsideCiAndDeletesTheStaleFile() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.environment = Collections.singletonMap("CI", "false"); File stale = staleMetaProperties(classes); @@ -263,7 +280,7 @@ public void skipsOutsideCiAndDeletesTheStaleFile() throws Exception { public void aRequiredUploadRunsOutsideCi() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.environment = Collections.emptyMap(); mojo.requireUpload = true; @@ -276,7 +293,7 @@ public void aRequiredUploadRunsOutsideCi() throws Exception { public void skipsWhenMavenRunsOffline() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.offline = true; mojo.execute(); @@ -289,7 +306,7 @@ public void skipsWhenMavenRunsOffline() throws Exception { public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); MavenProject app = new MavenProject(); app.setArtifactId("demo-app"); mojo.dependents = Collections.singletonList(app); @@ -309,7 +326,7 @@ public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception public void uploadsAnApplicationThatNoModuleOfTheBuildDependsOn() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -321,7 +338,7 @@ public void skipsAProjectWithPomPackaging() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.project.setPackaging("pom"); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -343,7 +360,7 @@ public void ciIsDetectedFromTheVariablesCiServicesSet() { public void skipsWhenTheCliUploadsNothing() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, false).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, false).getAbsolutePath(); mojo.execute(); @@ -354,7 +371,7 @@ public void skipsWhenTheCliUploadsNothing() throws Exception { public void aRequiredUploadFailsTheBuildWhenTheCliWritesNoFile() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, false).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, false).getAbsolutePath(); mojo.requireUpload = true; try { @@ -363,14 +380,13 @@ public void aRequiredUploadFailsTheBuildWhenTheCliWritesNoFile() throws Exceptio } catch (MojoExecutionException e) { assertTrue(e.getMessage(), e.getMessage().contains("did not write")); } - assertFalse(recordedArgs().contains("--skip-without-credentials")); assertFalse(metaProperties().exists()); } @Test - public void skipsWhenTheCliIsMissing() throws Exception { + public void skipsWhenHogIsMissing() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = new File(temp.getRoot(), "no-such-posthog-cli").getAbsolutePath(); + mojo.cliExecutable = new File(temp.getRoot(), "no-such-hog").getAbsolutePath(); File stale = staleMetaProperties(classes); mojo.execute(); @@ -380,10 +396,10 @@ public void skipsWhenTheCliIsMissing() throws Exception { } @Test - public void anOldCliSkipsTheUploadUnlessItIsRequired() throws Exception { + public void aUsageErrorPointsAtHogUpgrade() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = oldCli().getAbsolutePath(); + mojo.cliExecutable = fakeHog(2, false).getAbsolutePath(); mojo.execute(); @@ -394,20 +410,22 @@ public void anOldCliSkipsTheUploadUnlessItIsRequired() throws Exception { mojo.execute(); fail("expected a MojoExecutionException"); } catch (MojoExecutionException e) { - assertTrue(e.getMessage(), e.getMessage().contains("too old")); + assertTrue(e.getMessage(), e.getMessage().contains("exited with code 2")); + assertTrue(e.getMessage(), e.getMessage().contains("hog upgrade")); } } @Test - public void aRequiredUploadFailsWithAnInstallHintWhenTheCliIsMissing() throws Exception { + public void aRequiredUploadFailsWithAnInstallHintWhenHogIsMissing() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = new File(temp.getRoot(), "no-such-posthog-cli").getAbsolutePath(); + mojo.cliExecutable = new File(temp.getRoot(), "no-such-hog").getAbsolutePath(); mojo.requireUpload = true; try { mojo.execute(); fail("expected a MojoExecutionException"); } catch (MojoExecutionException e) { + assertTrue(e.getMessage(), e.getMessage().contains("Install hog")); assertTrue(e.getMessage(), e.getMessage().contains("posthog.cliExecutable")); } } @@ -415,7 +433,7 @@ public void aRequiredUploadFailsWithAnInstallHintWhenTheCliIsMissing() throws Ex @Test public void skipRunsNothingAndRemovesAStaleId() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); File stale = staleMetaProperties(classes); mojo.skip = true; @@ -428,7 +446,7 @@ public void skipRunsNothingAndRemovesAStaleId() throws Exception { @Test public void skipsWhenNoSourceRootExists() throws Exception { mojo.project.addCompileSourceRoot(new File(basedir, "src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -437,70 +455,100 @@ public void skipsWhenNoSourceRootExists() throws Exception { } @Test - public void resolveUsesTheConfiguredExecutableVerbatim() { + public void resolveUsesAConfiguredPathVerbatimAndSearchesForABareHog() throws Exception { + assumeUnix(); + File pathDir = temp.newFolder("bin"); + File onPath = executable(new File(pathDir, "hog")); + + assertEquals("/custom/hog", resolve(" /custom/hog ", env(""), null, false, none())); assertEquals( - "/custom/posthog-cli", - PostHogCli.resolve(" /custom/posthog-cli ", env(""), temp.getRoot(), false)); + onPath.getAbsolutePath(), + resolve("hog", env(pathDir.getAbsolutePath()), null, false, none())); } @Test - public void resolvePrefersTheDotPosthogInstallOverPath() throws Exception { + public void resolvePrefersPathThenInstallLocationsThenTheProjectLauncher() throws Exception { assumeUnix(); - File home = temp.newFolder("home"); - File installed = executable(new File(home, ".posthog/posthog-cli")); File pathDir = temp.newFolder("bin"); - executable(new File(pathDir, "posthog-cli")); + File onPath = executable(new File(pathDir, "hog")); + File installed = executable(new File(temp.newFolder("installed"), "hog")); + List installLocations = Collections.singletonList(installed); + // A React Native project keeps node_modules next to the directory the build runs in. + File project = temp.newFolder("app", "android"); + File projectLauncher = executable(new File(project.getParentFile(), "node_modules/.bin/hog")); assertEquals( - installed.getAbsolutePath(), - PostHogCli.resolve(null, env(pathDir.getAbsolutePath()), home, false)); + onPath.getAbsolutePath(), + resolve(null, env(pathDir.getAbsolutePath()), project, false, installLocations)); + assertEquals(installed.getAbsolutePath(), resolve(null, env(""), project, false, installLocations)); + File node = executable(new File(temp.newFolder("node-bin"), "node")); + assertEquals( + projectLauncher.getAbsolutePath(), + PostHogCli.resolve( + null, + env(""), + temp.getRoot(), + project, + false, + none(), + Collections.singletonList(node))); } @Test - public void resolveFallsBackToPathThenNothing() throws Exception { + public void resolveSkipsAProjectLauncherWithoutNode() throws Exception { assumeUnix(); - File home = temp.newFolder("home"); - File pathDir = temp.newFolder("bin"); - File onPath = executable(new File(pathDir, "posthog-cli")); + File project = temp.newFolder("app"); + executable(new File(project, "node_modules/.bin/hog")); - assertEquals( - onPath.getAbsolutePath(), - PostHogCli.resolve("", env(pathDir.getAbsolutePath()), home, false)); - // A temp home and an empty PATH only leave the machine-wide install locations, so no - // CLI is expected unless this machine has one installed in one of them. - String resolved = PostHogCli.resolve(null, env(""), home, false); - assertTrue(resolved, resolved == null || resolved.startsWith("/")); + String resolved = + PostHogCli.resolve( + null, + env(""), + temp.getRoot(), + project, + false, + none(), + Collections.emptyList()); + + assertEquals(null, resolved); } @Test - public void resolveOnWindowsPrefersTheExeThenTheNpmShim() throws Exception { - File home = temp.newFolder("home"); + public void resolveOnWindowsFindsHogAsCmdDoes() throws Exception { File exeDir = temp.newFolder("exe"); - File exe = executable(new File(exeDir, "posthog-cli.exe")); + File exe = executable(new File(exeDir, "hog.exe")); File shimDir = temp.newFolder("shim"); - executable(new File(shimDir, "posthog-cli.cmd")); - String both = exeDir.getAbsolutePath() + File.pathSeparator + shimDir.getAbsolutePath(); + File shim = executable(new File(shimDir, "hog.cmd")); + File installed = executable(new File(temp.newFolder("installed"), "hog.exe")); + List installLocations = Collections.singletonList(installed); - assertEquals(exe.getAbsolutePath(), PostHogCli.resolve(null, env(both), home, true)); - assertEquals(null, PostHogCli.resolve(null, env(shimDir.getAbsolutePath()), home, true)); - assertEquals(null, PostHogCli.resolve(null, env(""), home, true)); + assertEquals( + exe.getAbsolutePath(), + resolve(null, env(exeDir + File.pathSeparator + shimDir), null, true, none())); + // The first PATH folder with any PATHEXT match wins, as in cmd. + assertEquals( + shim.getAbsolutePath(), + resolve(null, env(shimDir + File.pathSeparator + exeDir), null, true, none())); + assertEquals(installed.getAbsolutePath(), resolve(null, env(""), null, true, installLocations)); + assertEquals(null, resolve(null, env(""), null, true, none())); + } - // The shim starts the binary the npm package installed, so that binary runs instead, - // without cmd: from a global install, and from a project's node_modules/.bin. - String binary = "@posthog/cli/node_modules/.bin_real/posthog-cli.exe"; + @Test + public void resolveOnWindowsRunsTheNpmPlatformBinaryInsteadOfTheShim() throws Exception { + String binary = "@posthog/hog-windows-x64/bin/hog.exe"; File globalPrefix = temp.newFolder("npm-global"); - executable(new File(globalPrefix, "posthog-cli.cmd")); - File globalExe = executable(new File(globalPrefix, "node_modules/" + binary)); + executable(new File(globalPrefix, "hog.cmd")); + File globalExe = executable(new File(globalPrefix, "node_modules/hog/node_modules/" + binary)); File projectBin = temp.newFolder("project-npm", "node_modules", ".bin"); - executable(new File(projectBin, "posthog-cli.cmd")); + executable(new File(projectBin, "hog.cmd")); File projectExe = executable(new File(projectBin.getParentFile(), binary)); assertEquals( globalExe.getAbsolutePath(), - PostHogCli.resolve(null, env(globalPrefix.getAbsolutePath()), home, true)); + resolve(null, env(globalPrefix.getAbsolutePath()), null, true, none())); assertEquals( projectExe.getAbsolutePath(), - PostHogCli.resolve(null, env(projectBin.getAbsolutePath()), home, true)); + resolve(null, env(projectBin.getAbsolutePath()), null, true, none())); } @Test @@ -522,7 +570,7 @@ public void cmdUnsafeValuesAreFound() { null, PostHogCli.firstUnsafeForCmd( Arrays.asList( - "posthog-cli", + "hog", "--source", "C:\\My Projects\\app-1\\src\\main\\java", "--release-version", @@ -537,7 +585,7 @@ public void launcherPathPrependsOnlyTheDirectoriesPathLacks() throws Exception { File nodeDir = temp.newFolder("node-bin"); File node = executable(new File(nodeDir, "node")); List nodeLocations = Collections.singletonList(node); - String cli = new File(cliDir, "posthog-cli").getAbsolutePath(); + String cli = new File(cliDir, "hog").getAbsolutePath(); String otherDir = temp.newFolder("other-bin").getAbsolutePath(); assertEquals( @@ -554,17 +602,17 @@ public void launcherPathPrependsOnlyTheDirectoriesPathLacks() throws Exception { @Test public void commandLineWrapsABareNameInCmdOnWindows() { - List args = Arrays.asList("jvm", "upload"); + List args = Arrays.asList("error-tracking", "process"); assertEquals( - Arrays.asList("cmd", "/c", "posthog-cli", "jvm", "upload"), - PostHogCli.commandLine("posthog-cli", args, true)); + Arrays.asList("cmd", "/c", "C:\\npm\\hog.cmd", "error-tracking", "process"), + PostHogCli.commandLine("C:\\npm\\hog.cmd", args, true)); assertEquals( - Arrays.asList("C:\\bin\\posthog-cli.exe", "jvm", "upload"), - PostHogCli.commandLine("C:\\bin\\posthog-cli.exe", args, true)); + Arrays.asList("C:\\bin\\hog.exe", "error-tracking", "process"), + PostHogCli.commandLine("C:\\bin\\hog.exe", args, true)); assertEquals( - Arrays.asList("/bin/posthog-cli", "jvm", "upload"), - PostHogCli.commandLine("/bin/posthog-cli", args, false)); + Arrays.asList("/bin/hog", "error-tracking", "process"), + PostHogCli.commandLine("/bin/hog", args, false)); } private File sourceRoot(String relative) { @@ -585,18 +633,19 @@ private File staleMetaProperties(File dir) throws IOException { } /** - * A shell script standing in for posthog-cli. It answers the plugin's help probe like a CLI - * with jvm upload. Otherwise it records its arguments one per line, writes - * posthog-meta.properties into the --meta-out directory when asked to, and exits with the - * given code. + * A shell script standing in for hog. It records its arguments one per line and + * HOG_DOTENV_FILE, writes posthog-meta.properties into the --meta-out directory when asked to, + * and exits with the given code. */ - private File fakeCli(int exitCode, boolean writeMetaProperties) throws IOException { + private File fakeHog(int exitCode, boolean writeMetaProperties) throws IOException { String script = "#!/bin/sh\n" - + "case \" $* \" in *' --help '*) echo ' --skip-without-credentials'; exit 0;; esac\n" + "printf '%s\\n' \"$@\" > '" + argsFile.getAbsolutePath() + "'\n" + + "printf '%s\\n' \"$HOG_DOTENV_FILE\" > '" + + envFile.getAbsolutePath() + + "'\n" + "meta=''\n" + "prev=''\n" + "for arg in \"$@\"; do\n" @@ -611,22 +660,10 @@ private File fakeCli(int exitCode, boolean writeMetaProperties) throws IOExcepti + "exit " + exitCode + "\n"; - File cli = new File(temp.getRoot(), "fake-posthog-cli-" + exitCode + "-" + writeMetaProperties); - Files.write(cli.toPath(), script.getBytes(StandardCharsets.UTF_8)); - assertTrue(cli.setExecutable(true)); - return cli; - } - - /** A posthog-cli from before jvm upload, which rejects the subcommand like clap does. */ - private File oldCli() throws IOException { - String script = - "#!/bin/sh\n" - + "echo \"error: unrecognized subcommand 'jvm'\" >&2\n" - + "exit 2\n"; - File cli = new File(temp.getRoot(), "old-posthog-cli"); - Files.write(cli.toPath(), script.getBytes(StandardCharsets.UTF_8)); - assertTrue(cli.setExecutable(true)); - return cli; + File hog = new File(temp.getRoot(), "fake-hog-" + exitCode + "-" + writeMetaProperties); + Files.write(hog.toPath(), script.getBytes(StandardCharsets.UTF_8)); + assertTrue(hog.setExecutable(true)); + return hog; } @Test @@ -664,7 +701,7 @@ public void additionalSourceRootsAddToTheDefaultRoots() throws Exception { File shared = sourceRoot("../shared/src/main/java"); mojo.project.addCompileSourceRoot(java.getAbsolutePath()); mojo.additionalSourceRoots = Collections.singletonList(new File(basedir, "../shared/src/main/java")); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -679,7 +716,7 @@ public void aConfiguredSourceRootThatDoesNotExistFailsOnlyARequiredUpload() thro mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); File typo = new File(basedir, "src/main/jav"); mojo.additionalSourceRoots = Collections.singletonList(typo); - mojo.cliExecutable = fakeCli(0, true).getAbsolutePath(); + mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -706,39 +743,15 @@ public void anUnsetEncodingFallsBackToThePlatformDefault() { assertEquals(StandardCharsets.UTF_8, mojo.sourceEncoding(windows1252)); } - @Test - public void aCliThatCannotStartIsNotReportedAsTooOld() throws Exception { - assumeUnix(); - mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - File cli = new File(temp.getRoot(), "broken-posthog-cli"); - Files.write( - cli.toPath(), - "#!/bin/sh\necho 'env: node: No such file or directory' >&2\nexit 127\n" - .getBytes(StandardCharsets.UTF_8)); - assertTrue(cli.setExecutable(true)); - mojo.cliExecutable = cli.getAbsolutePath(); - mojo.requireUpload = true; - - try { - mojo.execute(); - fail("expected a MojoExecutionException"); - } catch (MojoExecutionException e) { - assertTrue( - e.getMessage(), - e.getMessage().contains("exited with code 127: env: node: No such file or directory")); - assertFalse(e.getMessage(), e.getMessage().contains("too old")); - } - } - @Test public void aRelativeCliExecutableResolvesAgainstTheProject() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - File cli = new File(basedir, "tools/posthog-cli"); + File cli = new File(basedir, "tools/hog"); assertTrue(cli.getParentFile().mkdirs()); - Files.copy(fakeCli(0, true).toPath(), cli.toPath()); + Files.copy(fakeHog(0, true).toPath(), cli.toPath()); assertTrue(cli.setExecutable(true)); - mojo.cliExecutable = "tools/posthog-cli"; + mojo.cliExecutable = "tools/hog"; mojo.execute(); @@ -747,44 +760,39 @@ public void aRelativeCliExecutableResolvesAgainstTheProject() throws Exception { @Test public void cmdSplitsAPathWithSpacesOnlyNextToAnotherQuotedArgument() { - String spaced = "C:\\Users\\Jane Doe\\npm\\posthog-cli.cmd"; + String spaced = "C:\\Users\\Jane Doe\\npm\\hog.cmd"; assertTrue( PostHogCli.cmdSplitsPath( spaced, Arrays.asList("--source", "C:\\Users\\Jane Doe\\src"))); assertTrue(PostHogCli.cmdSplitsPath(spaced, Arrays.asList("--release-version", ""))); - assertFalse(PostHogCli.cmdSplitsPath(spaced, Arrays.asList("jvm", "upload", "--help"))); assertFalse( PostHogCli.cmdSplitsPath( - "C:\\npm\\posthog-cli.cmd", + spaced, Arrays.asList("error-tracking", "process", "--help"))); + assertFalse( + PostHogCli.cmdSplitsPath( + "C:\\npm\\hog.cmd", Arrays.asList("--source", "C:\\Users\\Jane Doe\\src"))); } @Test - public void resolveFindsACliThatNvmInstalledNewestFirst() throws Exception { - assumeUnix(); + public void nvmBinariesListTheNewestNodeVersionFirst() throws Exception { File home = temp.newFolder("home"); - executable(new File(home, ".nvm/versions/node/v18.20.0/bin/posthog-cli")); - File newest = executable(new File(home, ".nvm/versions/node/v20.11.1/bin/posthog-cli")); + executable(new File(home, ".nvm/versions/node/v18.20.0/bin/hog")); + File newest = executable(new File(home, ".nvm/versions/node/v20.11.1/bin/hog")); - assertEquals(newest, PostHogCli.nvmBinaries(home, "posthog-cli").get(0)); - Assume.assumeTrue( - "this machine has posthog-cli in a machine-wide location", - !new File("/opt/homebrew/bin/posthog-cli").exists() - && !new File("/usr/local/bin/posthog-cli").exists()); - assertEquals(newest.getAbsolutePath(), PostHogCli.resolve(null, env(""), home, false)); + assertEquals(newest, PostHogCli.nvmBinaries(home, "hog").get(0)); } @Test public void resolveOnWindowsAcceptsAQuotedPathEntry() throws Exception { assumeUnix(); - File home = temp.newFolder("home"); File dir = temp.newFolder("Program Files", "posthog"); - File exe = executable(new File(dir, "posthog-cli.exe")); + File exe = executable(new File(dir, "hog.exe")); assertEquals( exe.getAbsolutePath(), - PostHogCli.resolve(null, env("\"" + dir.getAbsolutePath() + "\""), home, true)); + resolve(null, env("\"" + dir.getAbsolutePath() + "\""), null, true, none())); } @Test @@ -888,6 +896,26 @@ private static File executable(File file) throws IOException { return file; } + private String resolve( + String configured, + Map environment, + File workingDirectory, + boolean isWindows, + List installLocations) { + return PostHogCli.resolve( + configured, + environment, + temp.getRoot(), + workingDirectory, + isWindows, + installLocations, + null); + } + + private static List none() { + return Collections.emptyList(); + } + private static Map env(String path) { Map env = new HashMap<>(); env.put("PATH", path); From fcfe6aba721465123af25a77a5c35cec58aa5df6 Mon Sep 17 00:00:00 2001 From: Rafa Audibert Date: Wed, 2 Dec 2026 13:17:39 -0300 Subject: [PATCH 09/14] refactor(maven-plugin): name the hog runner after hog Rename PostHogCli to Hog, the cliExecutable parameter to hogExecutable (property posthog.hogExecutable), and the tests and helpers that named the CLI. Co-Authored-By: Claude Opus 5.5 --- posthog-maven-plugin/README.md | 2 +- .../maven/{PostHogCli.java => Hog.java} | 4 +- .../com/posthog/maven/UploadSourcesMojo.java | 38 +++---- .../posthog/maven/UploadSourcesMojoTest.java | 104 +++++++++--------- 4 files changed, 74 insertions(+), 74 deletions(-) rename posthog-maven-plugin/src/main/java/com/posthog/maven/{PostHogCli.java => Hog.java} (99%) diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index 419678ae7..973206317 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -81,7 +81,7 @@ Set it in the application module, not in a parent POM that library modules share |---|---|---|---| | `skip` | `posthog.skip` | `false` | Skip the upload. | | `requireUpload` | `posthog.requireUpload` | `false` | Upload from every build, also outside CI and in library modules, and fail the build when the upload can't run. | -| `cliExecutable` | `posthog.cliExecutable` | found automatically | Path to `hog`, relative to the project directory. Without it, the plugin checks `PATH`, then `~/.local/bin`, nvm, `/usr/local/bin` and `/opt/homebrew/bin`, then `node_modules/.bin` in the project directory and its parent, as the PostHog Android Gradle plugin does. On Windows, it checks `PATH` as cmd does, then `~/.local/bin/hog.exe`, and runs the binary of the npm package behind `hog.cmd`. | +| `hogExecutable` | `posthog.hogExecutable` | found automatically | Path to `hog`, relative to the project directory. Without it, the plugin checks `PATH`, then `~/.local/bin`, nvm, `/usr/local/bin` and `/opt/homebrew/bin`, then `node_modules/.bin` in the project directory and its parent, as the PostHog Android Gradle plugin does. On Windows, it checks `PATH` as cmd does, then `~/.local/bin/hog.exe`, and runs the binary of the npm package behind `hog.cmd`. | | `dotenvFile` | `posthog.dotenvFile` | none | A dotenv file hog reads credentials from. | | `releaseName` | `posthog.releaseName` | `${project.artifactId}` | The release the build belongs to. | | `releaseVersion` | `posthog.releaseVersion` | the git commit | The version of that release. Set it to `${project.version}` if you bump the project version on every release. | diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java similarity index 99% rename from posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java rename to posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java index 852f567fd..a9f55a68c 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/PostHogCli.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java @@ -13,7 +13,7 @@ * Finds hog, PostHog's command line, and builds the command line that runs it. It looks for hog in * the same places and order as the PostHog Android Gradle plugin. */ -final class PostHogCli { +final class Hog { static final String EXECUTABLE = "hog"; static final String DOTENV_FILE_VARIABLE = "HOG_DOTENV_FILE"; @@ -26,7 +26,7 @@ final class PostHogCli { private static final List NPM_PLATFORM_PACKAGES = Arrays.asList("@posthog/hog-windows-x64", "@posthog/hog-windows-arm64"); - private PostHogCli() {} + private Hog() {} /** * Returns the hog to run, or null when none is installed. A configured value other than a bare diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index fd0aa2f33..26223a94f 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -50,10 +50,10 @@ public class UploadSourcesMojo extends AbstractMojo { private static final String UNIX_INSTALL_HINT = " Install hog (curl -fsSL https://releases.posthog.com/hog/install.sh | sh, brew install" - + " posthog/tap/hog, or npm install -g hog) or set posthog.cliExecutable."; + + " posthog/tap/hog, or npm install -g hog) or set posthog.hogExecutable."; private static final String WINDOWS_INSTALL_HINT = " Install hog (irm https://releases.posthog.com/hog/install.ps1 | iex, or npm install -g" - + " hog) or set posthog.cliExecutable."; + + " hog) or set posthog.hogExecutable."; private static final String UPDATE_HINT = " Update hog with `hog upgrade`."; private static final String CREDENTIALS_HINT = " Set HOG_PERSONAL_API_KEY and HOG_PROJECT_ID, set posthog.dotenvFile, or run hog auth" @@ -87,8 +87,8 @@ public class UploadSourcesMojo extends AbstractMojo { * Path to hog. When unset, or set to {@code hog}, the plugin looks on PATH, then in common * install locations, then in the project's {@code node_modules/.bin}. */ - @Parameter(property = "posthog.cliExecutable") - String cliExecutable; + @Parameter(property = "posthog.hogExecutable") + String hogExecutable; /** * A dotenv file hog reads its credentials from ({@code HOG_PERSONAL_API_KEY}, {@code @@ -160,7 +160,7 @@ public void execute() throws MojoExecutionException { return; } - boolean isWindows = PostHogCli.isWindows(); + boolean isWindows = Hog.isWindows(); String installHint = isWindows ? WINDOWS_INSTALL_HINT : UNIX_INSTALL_HINT; String configured = configuredExecutable(); if (configured != null && isPath(configured) && !isInstalledAt(configured, isWindows)) { @@ -168,7 +168,7 @@ public void execute() throws MojoExecutionException { return; } String executable = - PostHogCli.resolve( + Hog.resolve( configured, System.getenv(), new File(System.getProperty("user.home")), @@ -183,17 +183,17 @@ public void execute() throws MojoExecutionException { roots = utf8Roots(roots); List args = hogArguments(roots); - if (PostHogCli.runsThroughCmd(executable, isWindows)) { + if (Hog.runsThroughCmd(executable, isWindows)) { List values = new ArrayList<>(args); values.add(0, executable); - String unsafe = PostHogCli.firstUnsafeForCmd(values); - if (unsafe == null && PostHogCli.cmdSplitsPath(executable, args)) { + String unsafe = Hog.firstUnsafeForCmd(values); + if (unsafe == null && Hog.cmdSplitsPath(executable, args)) { skipOrFail( "hog (" + executable + ") runs through cmd, which cannot start a path with spaces" + " together with an argument with spaces. Set" - + " posthog.cliExecutable to hog.exe, which runs directly.", + + " posthog.hogExecutable to hog.exe, which runs directly.", null); return; } @@ -203,7 +203,7 @@ public void execute() throws MojoExecutionException { + executable + ") runs through cmd, which would not pass this value unchanged: " + unsafe - + ". Set posthog.cliExecutable to hog.exe, which runs directly.", + + ". Set posthog.hogExecutable to hog.exe, which runs directly.", null); return; } @@ -223,7 +223,7 @@ public void execute() throws MojoExecutionException { skipOrFail("Could not read the hog output.", e); return; } - if (exitCode == PostHogCli.EXIT_NEEDS_PERSON) { + if (exitCode == Hog.EXIT_NEEDS_PERSON) { skipOrFail( "hog found no PostHog credentials, or needs a person to act first, as its" + " output above says." @@ -280,15 +280,15 @@ List dependentModules() { } /** - * {@code cliExecutable} with a relative path resolved against the project directory, so that + * {@code hogExecutable} with a relative path resolved against the project directory, so that * a reactor build started from the parent finds it. A bare name stays as it is, for a PATH * lookup. */ private String configuredExecutable() { - if (!isNotBlank(cliExecutable)) { + if (!isNotBlank(hogExecutable)) { return null; } - String trimmed = cliExecutable.trim(); + String trimmed = hogExecutable.trim(); if (!isPath(trimmed)) { return trimmed; } @@ -513,7 +513,7 @@ private void skipOrFail(String message, Exception cause) throws MojoExecutionExc private Process start(String executable, List args, boolean isWindows) throws IOException { - List command = PostHogCli.commandLine(executable, args, isWindows); + List command = Hog.commandLine(executable, args, isWindows); getLog().debug("Running " + String.join(" ", command)); ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); @@ -523,17 +523,17 @@ private Process start(String executable, List args, boolean isWindows) } Map environment = builder.environment(); if (dotenvFile != null) { - environment.put(PostHogCli.DOTENV_FILE_VARIABLE, dotenvFile.getAbsolutePath()); + environment.put(Hog.DOTENV_FILE_VARIABLE, dotenvFile.getAbsolutePath()); } String path = - PostHogCli.launcherPath( + Hog.launcherPath( executable, environment, new File(System.getProperty("user.home")), isWindows, null); if (path != null) { - environment.put(PostHogCli.pathKey(environment, isWindows), path); + environment.put(Hog.pathKey(environment, isWindows), path); } return builder.start(); } diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index 10168c870..ac45a5b24 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -75,7 +75,7 @@ public void uploadsExistingSourceRootsAndWritesTheIdIntoTheClasses() throws Exce mojo.project.addCompileSourceRoot(new File(basedir, "src/main/missing").getAbsolutePath()); mojo.project.addCompileSourceRoot(kotlin.getAbsolutePath()); mojo.dotenvFile = new File(basedir, ".env"); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -125,7 +125,7 @@ public void kotlinSourceDirsAreUploadedWithTheCompileSourceRoots() throws Except plugin.setArtifactId("kotlin-maven-plugin"); plugin.addExecution(compile); mojo.project.getBuild().addPlugin(plugin); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -143,7 +143,7 @@ public void configuredSourceRootsReplaceTheCompileSourceRoots() throws Exception mojo.sourceRoots = Collections.singletonList(custom); mojo.releaseName = " "; mojo.releaseVersion = null; - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -185,7 +185,7 @@ public void javaSourcesInAnotherEncodingAreUploadedAsUtf8() throws Exception { compiler.setArtifactId("maven-compiler-plugin"); compiler.setConfiguration(configuration); mojo.project.getBuild().addPlugin(compiler); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -216,7 +216,7 @@ public void anNpmLauncherRunsWhenNeitherItNorNodeIsOnPath() throws Exception { launcher.toPath(), script.replace("#!/bin/sh", "#!/usr/bin/env node").getBytes(StandardCharsets.UTF_8)); assertTrue(launcher.setExecutable(true)); - mojo.cliExecutable = launcher.getAbsolutePath(); + mojo.hogExecutable = launcher.getAbsolutePath(); mojo.execute(); @@ -227,7 +227,7 @@ public void anNpmLauncherRunsWhenNeitherItNorNodeIsOnPath() throws Exception { public void aFailedUploadFailsOnlyARequiredUpload() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(1, false).getAbsolutePath(); + mojo.hogExecutable = fakeHog(1, false).getAbsolutePath(); mojo.execute(); @@ -246,7 +246,7 @@ public void aFailedUploadFailsOnlyARequiredUpload() throws Exception { public void missingCredentialsFailOnlyARequiredUpload() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(PostHogCli.EXIT_NEEDS_PERSON, false).getAbsolutePath(); + mojo.hogExecutable = fakeHog(Hog.EXIT_NEEDS_PERSON, false).getAbsolutePath(); mojo.execute(); @@ -266,7 +266,7 @@ public void missingCredentialsFailOnlyARequiredUpload() throws Exception { public void skipsOutsideCiAndDeletesTheStaleFile() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.environment = Collections.singletonMap("CI", "false"); File stale = staleMetaProperties(classes); @@ -280,7 +280,7 @@ public void skipsOutsideCiAndDeletesTheStaleFile() throws Exception { public void aRequiredUploadRunsOutsideCi() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.environment = Collections.emptyMap(); mojo.requireUpload = true; @@ -293,7 +293,7 @@ public void aRequiredUploadRunsOutsideCi() throws Exception { public void skipsWhenMavenRunsOffline() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.offline = true; mojo.execute(); @@ -306,7 +306,7 @@ public void skipsWhenMavenRunsOffline() throws Exception { public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); MavenProject app = new MavenProject(); app.setArtifactId("demo-app"); mojo.dependents = Collections.singletonList(app); @@ -326,7 +326,7 @@ public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception public void uploadsAnApplicationThatNoModuleOfTheBuildDependsOn() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -338,7 +338,7 @@ public void skipsAProjectWithPomPackaging() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.project.setPackaging("pom"); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -357,10 +357,10 @@ public void ciIsDetectedFromTheVariablesCiServicesSet() { } @Test - public void skipsWhenTheCliUploadsNothing() throws Exception { + public void skipsWhenHogUploadsNothing() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, false).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, false).getAbsolutePath(); mojo.execute(); @@ -368,10 +368,10 @@ public void skipsWhenTheCliUploadsNothing() throws Exception { } @Test - public void aRequiredUploadFailsTheBuildWhenTheCliWritesNoFile() throws Exception { + public void aRequiredUploadFailsTheBuildWhenHogWritesNoFile() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, false).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, false).getAbsolutePath(); mojo.requireUpload = true; try { @@ -386,7 +386,7 @@ public void aRequiredUploadFailsTheBuildWhenTheCliWritesNoFile() throws Exceptio @Test public void skipsWhenHogIsMissing() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = new File(temp.getRoot(), "no-such-hog").getAbsolutePath(); + mojo.hogExecutable = new File(temp.getRoot(), "no-such-hog").getAbsolutePath(); File stale = staleMetaProperties(classes); mojo.execute(); @@ -399,7 +399,7 @@ public void skipsWhenHogIsMissing() throws Exception { public void aUsageErrorPointsAtHogUpgrade() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(2, false).getAbsolutePath(); + mojo.hogExecutable = fakeHog(2, false).getAbsolutePath(); mojo.execute(); @@ -418,7 +418,7 @@ public void aUsageErrorPointsAtHogUpgrade() throws Exception { @Test public void aRequiredUploadFailsWithAnInstallHintWhenHogIsMissing() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = new File(temp.getRoot(), "no-such-hog").getAbsolutePath(); + mojo.hogExecutable = new File(temp.getRoot(), "no-such-hog").getAbsolutePath(); mojo.requireUpload = true; try { @@ -426,14 +426,14 @@ public void aRequiredUploadFailsWithAnInstallHintWhenHogIsMissing() throws Excep fail("expected a MojoExecutionException"); } catch (MojoExecutionException e) { assertTrue(e.getMessage(), e.getMessage().contains("Install hog")); - assertTrue(e.getMessage(), e.getMessage().contains("posthog.cliExecutable")); + assertTrue(e.getMessage(), e.getMessage().contains("posthog.hogExecutable")); } } @Test public void skipRunsNothingAndRemovesAStaleId() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); File stale = staleMetaProperties(classes); mojo.skip = true; @@ -446,7 +446,7 @@ public void skipRunsNothingAndRemovesAStaleId() throws Exception { @Test public void skipsWhenNoSourceRootExists() throws Exception { mojo.project.addCompileSourceRoot(new File(basedir, "src/main/java").getAbsolutePath()); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -484,7 +484,7 @@ public void resolvePrefersPathThenInstallLocationsThenTheProjectLauncher() throw File node = executable(new File(temp.newFolder("node-bin"), "node")); assertEquals( projectLauncher.getAbsolutePath(), - PostHogCli.resolve( + Hog.resolve( null, env(""), temp.getRoot(), @@ -501,7 +501,7 @@ public void resolveSkipsAProjectLauncherWithoutNode() throws Exception { executable(new File(project, "node_modules/.bin/hog")); String resolved = - PostHogCli.resolve( + Hog.resolve( null, env(""), temp.getRoot(), @@ -564,11 +564,11 @@ public void cmdUnsafeValuesAreFound() { "say \"hi\"", "a^b", "a\nb")) { - assertEquals(unsafe, PostHogCli.firstUnsafeForCmd(Arrays.asList("--source", unsafe))); + assertEquals(unsafe, Hog.firstUnsafeForCmd(Arrays.asList("--source", unsafe))); } assertEquals( null, - PostHogCli.firstUnsafeForCmd( + Hog.firstUnsafeForCmd( Arrays.asList( "hog", "--source", @@ -581,23 +581,23 @@ public void cmdUnsafeValuesAreFound() { @Test public void launcherPathPrependsOnlyTheDirectoriesPathLacks() throws Exception { assumeUnix(); - File cliDir = temp.newFolder("cli-bin"); + File hogDir = temp.newFolder("hog-bin"); File nodeDir = temp.newFolder("node-bin"); File node = executable(new File(nodeDir, "node")); List nodeLocations = Collections.singletonList(node); - String cli = new File(cliDir, "hog").getAbsolutePath(); + String hog = new File(hogDir, "hog").getAbsolutePath(); String otherDir = temp.newFolder("other-bin").getAbsolutePath(); assertEquals( - cliDir.getAbsolutePath() + hogDir.getAbsolutePath() + File.pathSeparator + nodeDir.getAbsolutePath() + File.pathSeparator + otherDir, - PostHogCli.launcherPath(cli, env(otherDir), temp.getRoot(), false, nodeLocations)); - String both = cliDir.getAbsolutePath() + File.pathSeparator + nodeDir.getAbsolutePath(); + Hog.launcherPath(hog, env(otherDir), temp.getRoot(), false, nodeLocations)); + String both = hogDir.getAbsolutePath() + File.pathSeparator + nodeDir.getAbsolutePath(); assertEquals( - null, PostHogCli.launcherPath(cli, env(both), temp.getRoot(), false, nodeLocations)); + null, Hog.launcherPath(hog, env(both), temp.getRoot(), false, nodeLocations)); } @Test @@ -606,13 +606,13 @@ public void commandLineWrapsABareNameInCmdOnWindows() { assertEquals( Arrays.asList("cmd", "/c", "C:\\npm\\hog.cmd", "error-tracking", "process"), - PostHogCli.commandLine("C:\\npm\\hog.cmd", args, true)); + Hog.commandLine("C:\\npm\\hog.cmd", args, true)); assertEquals( Arrays.asList("C:\\bin\\hog.exe", "error-tracking", "process"), - PostHogCli.commandLine("C:\\bin\\hog.exe", args, true)); + Hog.commandLine("C:\\bin\\hog.exe", args, true)); assertEquals( Arrays.asList("/bin/hog", "error-tracking", "process"), - PostHogCli.commandLine("/bin/hog", args, false)); + Hog.commandLine("/bin/hog", args, false)); } private File sourceRoot(String relative) { @@ -701,7 +701,7 @@ public void additionalSourceRootsAddToTheDefaultRoots() throws Exception { File shared = sourceRoot("../shared/src/main/java"); mojo.project.addCompileSourceRoot(java.getAbsolutePath()); mojo.additionalSourceRoots = Collections.singletonList(new File(basedir, "../shared/src/main/java")); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -716,7 +716,7 @@ public void aConfiguredSourceRootThatDoesNotExistFailsOnlyARequiredUpload() thro mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); File typo = new File(basedir, "src/main/jav"); mojo.additionalSourceRoots = Collections.singletonList(typo); - mojo.cliExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.execute(); @@ -744,14 +744,14 @@ public void anUnsetEncodingFallsBackToThePlatformDefault() { } @Test - public void aRelativeCliExecutableResolvesAgainstTheProject() throws Exception { + public void aRelativeHogExecutableResolvesAgainstTheProject() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - File cli = new File(basedir, "tools/hog"); - assertTrue(cli.getParentFile().mkdirs()); - Files.copy(fakeHog(0, true).toPath(), cli.toPath()); - assertTrue(cli.setExecutable(true)); - mojo.cliExecutable = "tools/hog"; + File hog = new File(basedir, "tools/hog"); + assertTrue(hog.getParentFile().mkdirs()); + Files.copy(fakeHog(0, true).toPath(), hog.toPath()); + assertTrue(hog.setExecutable(true)); + mojo.hogExecutable = "tools/hog"; mojo.execute(); @@ -763,14 +763,14 @@ public void cmdSplitsAPathWithSpacesOnlyNextToAnotherQuotedArgument() { String spaced = "C:\\Users\\Jane Doe\\npm\\hog.cmd"; assertTrue( - PostHogCli.cmdSplitsPath( + Hog.cmdSplitsPath( spaced, Arrays.asList("--source", "C:\\Users\\Jane Doe\\src"))); - assertTrue(PostHogCli.cmdSplitsPath(spaced, Arrays.asList("--release-version", ""))); + assertTrue(Hog.cmdSplitsPath(spaced, Arrays.asList("--release-version", ""))); assertFalse( - PostHogCli.cmdSplitsPath( + Hog.cmdSplitsPath( spaced, Arrays.asList("error-tracking", "process", "--help"))); assertFalse( - PostHogCli.cmdSplitsPath( + Hog.cmdSplitsPath( "C:\\npm\\hog.cmd", Arrays.asList("--source", "C:\\Users\\Jane Doe\\src"))); } @@ -781,7 +781,7 @@ public void nvmBinariesListTheNewestNodeVersionFirst() throws Exception { executable(new File(home, ".nvm/versions/node/v18.20.0/bin/hog")); File newest = executable(new File(home, ".nvm/versions/node/v20.11.1/bin/hog")); - assertEquals(newest, PostHogCli.nvmBinaries(home, "hog").get(0)); + assertEquals(newest, Hog.nvmBinaries(home, "hog").get(0)); } @Test @@ -834,7 +834,7 @@ public void thePluginDescriptorDeclaresTheGoalAsMavenReadsIt() throws Exception } assertEquals("${posthog.skip}", expressions.get("skip")); assertEquals("${posthog.requireUpload}", expressions.get("requireUpload")); - assertEquals("${posthog.cliExecutable}", expressions.get("cliExecutable")); + assertEquals("${posthog.hogExecutable}", expressions.get("hogExecutable")); assertEquals("${posthog.dotenvFile}", expressions.get("dotenvFile")); assertEquals("${posthog.releaseName}", expressions.get("releaseName")); assertEquals("${posthog.releaseVersion}", expressions.get("releaseVersion")); @@ -902,7 +902,7 @@ private String resolve( File workingDirectory, boolean isWindows, List installLocations) { - return PostHogCli.resolve( + return Hog.resolve( configured, environment, temp.getRoot(), @@ -923,6 +923,6 @@ private static Map env(String path) { } private static void assumeUnix() { - Assume.assumeFalse(PostHogCli.isWindows()); + Assume.assumeFalse(Hog.isWindows()); } } From 29cd104ee2e0e620a4dab1004b958b568e112400 Mon Sep 17 00:00:00 2001 From: Rafa Audibert Date: Wed, 2 Dec 2026 13:17:59 -0300 Subject: [PATCH 10/14] docs(maven-plugin): name hog the same way everywhere Call the tool hog without code formatting, keep code formatting for the `hog error-tracking process` command and `posthog.hogExecutable`, and list credentials as a requirement instead of only a personal API key, since hog also logs in with a CI job's OIDC token or `hog auth login`. Co-Authored-By: Claude Opus 5.5 --- .changeset/maven-plugin-upload-sources.md | 2 +- AGENTS.md | 2 +- posthog-maven-plugin/README.md | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.changeset/maven-plugin-upload-sources.md b/.changeset/maven-plugin-upload-sources.md index 48882825b..4d5da9979 100644 --- a/.changeset/maven-plugin-upload-sources.md +++ b/.changeset/maven-plugin-upload-sources.md @@ -2,4 +2,4 @@ "posthog-maven-plugin": minor --- -Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `hog error-tracking process --kind jvm` to upload the project's sources and writes the id they were uploaded under and the id of the build's release into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures, and reports the build's release. By default only a CI build of an application module uploads, and a missing or outdated `hog`, missing credentials or a failed upload only logs a warning. Set `requireUpload` to upload from every build and fail it when the upload can't run. +Add `posthog-maven-plugin` with an `upload-sources` goal. It runs `hog error-tracking process --kind jvm` to upload the project's sources and writes the id they were uploaded under and the id of the build's release into `posthog-meta.properties`, so error tracking shows source code on the frames of exceptions `posthog-server` captures, and reports the build's release. By default only a CI build of an application module uploads, and a missing or outdated hog, missing credentials or a failed upload only logs a warning. Set `requireUpload` to upload from every build and fail it when the upload can't run. diff --git a/AGENTS.md b/AGENTS.md index f38636a45..83df44e78 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ PostHog Android SDK monorepo. Kotlin-first, targets JVM and Android. - `posthog-android/` — Android-specific SDK (depends on `posthog/`) - `posthog-android-surveys-compose/` — Compose survey UI (depends on `posthog-android/`, transitively on `posthog/`) - `posthog-server/` — Server-side SDK (depends on `posthog/`) -- `posthog-maven-plugin/` — Maven plugin that uploads JVM sources for error tracking source context (pure Java, runs `hog`) +- `posthog-maven-plugin/` — Maven plugin that uploads JVM sources for error tracking source context (pure Java, runs hog) - `posthog-server-openfeature/` — OpenFeature provider for the server-side SDK (depends on `posthog-server/`, Java 11+) - `posthog-android-gradle-plugin/` — Gradle plugin for Android integrations - `posthog-samples/` — Sample apps diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index 973206317..b4563187a 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -2,15 +2,15 @@ Uploads your application's Java and Kotlin sources to PostHog, so error tracking shows the source code around each frame of the exceptions your app captures. -On each CI build, the `upload-sources` goal runs [`hog`](https://github.com/PostHog/posthog/tree/master/hog), PostHog's command line, as `hog error-tracking process --kind jvm`. hog bundles the sources, uploads them under an id derived from their content, and writes that id and the id of the build's release into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads the file. It sends the first id on every exception frame, and PostHog looks up the uploaded sources by it. It sends the release id with every exception, and PostHog reports that release. +On each CI build, the `upload-sources` goal runs [hog](https://github.com/PostHog/posthog/tree/master/hog), PostHog's command line, as `hog error-tracking process --kind jvm`. hog bundles the sources, uploads them under an id derived from their content, and writes that id and the id of the build's release into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads the file. It sends the first id on every exception frame, and PostHog looks up the uploaded sources by it. It sends the release id with every exception, and PostHog reports that release. A build of unchanged code reuses the existing upload and sends no source files, also in a new release. Changed code gets a new id and a new upload. The goal rewrites or deletes the file on every build, so it always matches the code that was compiled and the release it belongs to. ## Requirements -- [`hog`](https://github.com/PostHog/posthog/tree/master/hog) in a release that uploads JVM sources. Install it with `curl -fsSL https://releases.posthog.com/hog/install.sh | sh`, `brew install posthog/tap/hog` or `npm install -g hog`, or on Windows with `irm https://releases.posthog.com/hog/install.ps1 | iex`. Update an older hog with `hog upgrade`. +- [hog](https://github.com/PostHog/posthog/tree/master/hog) in a release that uploads JVM sources. Install it with `curl -fsSL https://releases.posthog.com/hog/install.sh | sh`, `brew install posthog/tap/hog` or `npm install -g hog`, or on Windows with `irm https://releases.posthog.com/hog/install.ps1 | iex`. Update an older hog with `hog upgrade`. - `posthog-server` with `posthog-meta.properties` support, and no `releaseIdentifier` set in code (an explicit value wins over the file). -- A personal API key with error tracking write access, for the upload. +- PostHog credentials with error tracking write access, for the upload. See [Credentials](#credentials). ## Usage @@ -81,7 +81,7 @@ Set it in the application module, not in a parent POM that library modules share |---|---|---|---| | `skip` | `posthog.skip` | `false` | Skip the upload. | | `requireUpload` | `posthog.requireUpload` | `false` | Upload from every build, also outside CI and in library modules, and fail the build when the upload can't run. | -| `hogExecutable` | `posthog.hogExecutable` | found automatically | Path to `hog`, relative to the project directory. Without it, the plugin checks `PATH`, then `~/.local/bin`, nvm, `/usr/local/bin` and `/opt/homebrew/bin`, then `node_modules/.bin` in the project directory and its parent, as the PostHog Android Gradle plugin does. On Windows, it checks `PATH` as cmd does, then `~/.local/bin/hog.exe`, and runs the binary of the npm package behind `hog.cmd`. | +| `hogExecutable` | `posthog.hogExecutable` | found automatically | Path to hog, relative to the project directory. Without it, the plugin checks `PATH`, then `~/.local/bin`, nvm, `/usr/local/bin` and `/opt/homebrew/bin`, then `node_modules/.bin` in the project directory and its parent, as the PostHog Android Gradle plugin does. On Windows, it checks `PATH` as cmd does, then `~/.local/bin/hog.exe`, and runs the binary of the npm package behind `hog.cmd`. | | `dotenvFile` | `posthog.dotenvFile` | none | A dotenv file hog reads credentials from. | | `releaseName` | `posthog.releaseName` | `${project.artifactId}` | The release the build belongs to. | | `releaseVersion` | `posthog.releaseVersion` | the git commit | The version of that release. Set it to `${project.version}` if you bump the project version on every release. | From 91aac0e976e9276a113da1640001a48884043f4f Mon Sep 17 00:00:00 2001 From: Rafa Audibert Date: Wed, 2 Dec 2026 13:21:52 -0300 Subject: [PATCH 11/14] refactor(maven-plugin): simplify the hog runner and its tests - One blank-string helper, Hog.isBlank, instead of four copies. - One environment key lookup behind pathKey and variable. - One cmd rejection message, and firstUnsafeForCmd takes the executable and its arguments. - Both hog exit codes in Hog, one branch for every non-zero exit with the `hog upgrade` hint only for exit 2, and a shorter credentials message. - skipOrFail(String), metaPropertiesFile() and home() helpers, and hog resolved from the mojo's environment field. - Look node up once for a project launcher. - Decode with new String, which already replaces unmappable bytes, and create the target folder once per copied file. - Tests: an assertThrows helper for required uploads, one helper that writes executable scripts, the meta file name from the constant, and no duplicate success test. Co-Authored-By: Claude Opus 5.5 --- .../java/com/posthog/maven/CiEnvironment.java | 8 +- .../src/main/java/com/posthog/maven/Hog.java | 41 +++-- .../com/posthog/maven/UploadSourcesMojo.java | 115 +++++------- .../java/com/posthog/maven/Utf8Sources.java | 28 ++- .../posthog/maven/UploadSourcesMojoTest.java | 166 +++++++----------- 5 files changed, 145 insertions(+), 213 deletions(-) diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java index 196e70e17..2394b6ff7 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java @@ -13,18 +13,14 @@ private CiEnvironment() {} static boolean isCi(Map environment) { String ci = environment.get("CI"); - if (isSet(ci) && !ci.trim().equalsIgnoreCase("false") && !ci.trim().equals("0")) { + if (!Hog.isBlank(ci) && !ci.trim().equalsIgnoreCase("false") && !ci.trim().equals("0")) { return true; } for (String name : CI_SERVICE_VARIABLES) { - if (isSet(environment.get(name))) { + if (!Hog.isBlank(environment.get(name))) { return true; } } return false; } - - private static boolean isSet(String value) { - return value != null && !value.trim().isEmpty(); - } } diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java index a9f55a68c..3e274d9d2 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java @@ -18,6 +18,7 @@ final class Hog { static final String DOTENV_FILE_VARIABLE = "HOG_DOTENV_FILE"; + static final int EXIT_USAGE = 2; /** hog's exit code when a person has to act first, such as logging in. */ static final int EXIT_NEEDS_PERSON = 3; @@ -49,7 +50,7 @@ static String resolve( boolean isWindows, List installLocations, List nodeLocations) { - if (configured != null && !configured.trim().isEmpty()) { + if (!isBlank(configured)) { String trimmed = configured.trim(); if (!trimmed.equals(EXECUTABLE)) { return trimmed; @@ -88,9 +89,10 @@ static String resolve( } for (File directory : projectDirectories) { File launcher = new File(directory, "node_modules/.bin/" + EXECUTABLE); - if (isRunnable(launcher, false) - && resolveNode(environment, home, false, nodeLocations) != null) { - return launcher.getAbsolutePath(); + if (isRunnable(launcher, false)) { + return resolveNode(environment, home, false, nodeLocations) != null + ? launcher.getAbsolutePath() + : null; } } return null; @@ -110,7 +112,7 @@ private static String findOnWindowsPath(Map environment) { String pathExt = variable(environment, "PATHEXT", true); List extensions = new ArrayList<>(); for (String extension : (pathExt != null ? pathExt : WINDOWS_DEFAULT_PATHEXT).split(";")) { - if (!extension.trim().isEmpty()) { + if (!isBlank(extension)) { extensions.add(extension.trim().toLowerCase(Locale.ROOT)); } } @@ -214,13 +216,15 @@ static boolean cmdSplitsPath(String executable, List args) { } /** - * The first of {@code values} that cmd would not pass through unchanged, or null when all are - * safe. Java quotes an argument with spaces, but cmd still reads operators such as {@code &} + * The first of {@code executable} and {@code args} that cmd would not pass through unchanged, + * or null when all are safe. Java quotes an argument with spaces, but cmd still reads operators such as {@code &} * and {@code |}, expands {@code %VAR%}, and ends the command at a line break. Parentheses are * allowed, because they start no command, and versions such as {@code 1.0(5)} hold them. The * Gradle plugin uses the same characters. */ - static String firstUnsafeForCmd(List values) { + static String firstUnsafeForCmd(String executable, List args) { + List values = new ArrayList<>(args); + values.add(0, executable); for (String value : values) { for (int i = 0; i < value.length(); i++) { if (CMD_UNSAFE_CHARACTERS.indexOf(value.charAt(i)) >= 0) { @@ -293,24 +297,27 @@ static boolean isWindows() { return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win"); } + static boolean isBlank(String value) { + return value == null || value.trim().isEmpty(); + } + /** The PATH key of {@code environment}. Windows spells it Path, and is case-insensitive. */ static String pathKey(Map environment, boolean isWindows) { + return key(environment, "PATH", isWindows); + } + + // Windows variable names are case-insensitive, and Java keeps whichever case the system used. + private static String key(Map environment, String name, boolean isWindows) { for (String key : environment.keySet()) { - if (isWindows ? key.equalsIgnoreCase("PATH") : key.equals("PATH")) { + if (isWindows ? key.equalsIgnoreCase(name) : key.equals(name)) { return key; } } - return "PATH"; + return name; } - // Windows variable names are case-insensitive, and Java keeps whichever case the system used. private static String variable(Map environment, String name, boolean isWindows) { - for (Map.Entry entry : environment.entrySet()) { - if (isWindows ? entry.getKey().equalsIgnoreCase(name) : entry.getKey().equals(name)) { - return entry.getValue(); - } - } - return null; + return environment.get(key(environment, name, isWindows)); } private static List pathEntries(String path, boolean isWindows) { diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index 26223a94f..6a53e2c77 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -43,8 +43,6 @@ public class UploadSourcesMojo extends AbstractMojo { static final String META_PROPERTIES_FILE = "posthog-meta.properties"; - private static final int EXIT_USAGE = 2; - private static final String KOTLIN_MAVEN_PLUGIN = "org.jetbrains.kotlin:kotlin-maven-plugin"; private static final String COMPILER_PLUGIN = "org.apache.maven.plugins:maven-compiler-plugin"; @@ -54,10 +52,6 @@ public class UploadSourcesMojo extends AbstractMojo { private static final String WINDOWS_INSTALL_HINT = " Install hog (irm https://releases.posthog.com/hog/install.ps1 | iex, or npm install -g" + " hog) or set posthog.hogExecutable."; - private static final String UPDATE_HINT = " Update hog with `hog upgrade`."; - private static final String CREDENTIALS_HINT = - " Set HOG_PERSONAL_API_KEY and HOG_PROJECT_ID, set posthog.dotenvFile, or run hog auth" - + " login."; @Parameter(defaultValue = "${project}", readonly = true, required = true) MavenProject project; @@ -164,47 +158,34 @@ public void execute() throws MojoExecutionException { String installHint = isWindows ? WINDOWS_INSTALL_HINT : UNIX_INSTALL_HINT; String configured = configuredExecutable(); if (configured != null && isPath(configured) && !isInstalledAt(configured, isWindows)) { - skipOrFail("hog was not found at " + configured + "." + installHint, null); + skipOrFail("hog was not found at " + configured + "." + installHint); return; } String executable = Hog.resolve( - configured, - System.getenv(), - new File(System.getProperty("user.home")), - project.getBasedir(), - isWindows, - null, - null); + configured, environment, home(), project.getBasedir(), isWindows, null, null); if (executable == null) { - skipOrFail("hog was not found." + installHint, null); + skipOrFail("hog was not found." + installHint); return; } roots = utf8Roots(roots); List args = hogArguments(roots); if (Hog.runsThroughCmd(executable, isWindows)) { - List values = new ArrayList<>(args); - values.add(0, executable); - String unsafe = Hog.firstUnsafeForCmd(values); - if (unsafe == null && Hog.cmdSplitsPath(executable, args)) { + String unsafe = Hog.firstUnsafeForCmd(executable, args); + String problem = + unsafe != null + ? "would not pass this value unchanged: " + unsafe + : Hog.cmdSplitsPath(executable, args) + ? "cannot start a path with spaces with an argument with spaces" + : null; + if (problem != null) { skipOrFail( "hog (" + executable - + ") runs through cmd, which cannot start a path with spaces" - + " together with an argument with spaces. Set" - + " posthog.hogExecutable to hog.exe, which runs directly.", - null); - return; - } - if (unsafe != null) { - skipOrFail( - "hog (" - + executable - + ") runs through cmd, which would not pass this value unchanged: " - + unsafe - + ". Set posthog.hogExecutable to hog.exe, which runs directly.", - null); + + ") runs through cmd, which " + + problem + + ". Set posthog.hogExecutable to hog.exe, which runs directly."); return; } } @@ -225,26 +206,20 @@ public void execute() throws MojoExecutionException { } if (exitCode == Hog.EXIT_NEEDS_PERSON) { skipOrFail( - "hog found no PostHog credentials, or needs a person to act first, as its" - + " output above says." - + CREDENTIALS_HINT, - null); + "hog found no PostHog credentials. Set HOG_PERSONAL_API_KEY and HOG_PROJECT_ID," + + " set posthog.dotenvFile, or run hog auth login."); return; } - if (exitCode == EXIT_USAGE) { + if (exitCode != 0) { // A hog from before JVM source uploads rejects --kind jvm and --meta-out as a usage // error. - skipOrFail("hog exited with code " + exitCode + "." + UPDATE_HINT, null); - return; - } - if (exitCode != 0) { - skipOrFail("hog exited with code " + exitCode + ".", null); + String hint = exitCode == Hog.EXIT_USAGE ? " Update hog with `hog upgrade`." : ""; + skipOrFail("hog exited with code " + exitCode + "." + hint); return; } - File written = new File(classesDirectory(), META_PROPERTIES_FILE); - if (!written.isFile()) { - skipOrFail("hog exited successfully but did not write " + written + ".", null); + if (!metaPropertiesFile().isFile()) { + skipOrFail("hog exited successfully but did not write " + metaPropertiesFile() + "."); } } @@ -285,7 +260,7 @@ List dependentModules() { * lookup. */ private String configuredExecutable() { - if (!isNotBlank(hogExecutable)) { + if (Hog.isBlank(hogExecutable)) { return null; } String trimmed = hogExecutable.trim(); @@ -331,11 +306,11 @@ List hogArguments(List roots) { // classes directory that the jar, war and Spring Boot archive are built from. args.add("--meta-out"); args.add(classesDirectory().getAbsolutePath()); - if (isNotBlank(releaseName)) { + if (!Hog.isBlank(releaseName)) { args.add("--release-name"); args.add(releaseName); } - if (isNotBlank(releaseVersion)) { + if (!Hog.isBlank(releaseVersion)) { args.add("--release-version"); args.add(releaseVersion); } @@ -442,8 +417,11 @@ Charset sourceEncoding(Charset platformDefault) { Plugin compiler = project.getPlugin(COMPILER_PLUGIN); if (compiler != null) { for (PluginExecution execution : compiler.getExecutions()) { - if (encoding == null && execution.getGoals().contains("compile")) { + if (execution.getGoals().contains("compile")) { encoding = childValue(execution.getConfiguration(), "encoding"); + if (encoding != null) { + break; + } } } if (encoding == null) { @@ -453,7 +431,7 @@ Charset sourceEncoding(Charset platformDefault) { if (encoding == null) { encoding = project.getProperties().getProperty("project.build.sourceEncoding"); } - if (!isNotBlank(encoding)) { + if (Hog.isBlank(encoding)) { return platformDefault; } try { @@ -469,7 +447,7 @@ private static String childValue(Object configuration, String name) { return null; } Xpp3Dom child = ((Xpp3Dom) configuration).getChild(name); - return child != null && isNotBlank(child.getValue()) ? child.getValue().trim() : null; + return child != null && !Hog.isBlank(child.getValue()) ? child.getValue().trim() : null; } private void addSourceDirs(Object configuration, List dirs) { @@ -481,26 +459,37 @@ private void addSourceDirs(Object configuration, List dirs) { return; } for (Xpp3Dom sourceDir : sourceDirs.getChildren()) { - String value = sourceDir.getValue(); - if (value == null || value.trim().isEmpty()) { + if (Hog.isBlank(sourceDir.getValue())) { continue; } - File dir = new File(value.trim()); - dirs.add(dir.isAbsolute() ? dir : new File(project.getBasedir(), value.trim())); + File dir = new File(sourceDir.getValue().trim()); + dirs.add(dir.isAbsolute() ? dir : new File(project.getBasedir(), dir.getPath())); } } private void deleteStaleMetaProperties() throws MojoExecutionException { - File stale = new File(classesDirectory(), META_PROPERTIES_FILE); + File stale = metaPropertiesFile(); if (stale.exists() && !stale.delete()) { throw new MojoExecutionException("Could not delete the stale " + stale); } } + private File metaPropertiesFile() { + return new File(classesDirectory(), META_PROPERTIES_FILE); + } + private File classesDirectory() { return new File(project.getBuild().getOutputDirectory()); } + private static File home() { + return new File(System.getProperty("user.home")); + } + + private void skipOrFail(String message) throws MojoExecutionException { + skipOrFail(message, null); + } + private void skipOrFail(String message, Exception cause) throws MojoExecutionException { if (requireUpload) { throw new MojoExecutionException(message, cause); @@ -525,13 +514,7 @@ private Process start(String executable, List args, boolean isWindows) if (dotenvFile != null) { environment.put(Hog.DOTENV_FILE_VARIABLE, dotenvFile.getAbsolutePath()); } - String path = - Hog.launcherPath( - executable, - environment, - new File(System.getProperty("user.home")), - isWindows, - null); + String path = Hog.launcherPath(executable, environment, home(), isWindows, null); if (path != null) { environment.put(Hog.pathKey(environment, isWindows), path); } @@ -556,8 +539,4 @@ private int waitFor(Process process) throws IOException, MojoExecutionException throw new MojoExecutionException("Interrupted while waiting for hog", e); } } - - private static boolean isNotBlank(String value) { - return value != null && !value.trim().isEmpty(); - } } diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java index b5e0242ed..f16d2b11b 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java @@ -2,9 +2,7 @@ import java.io.File; import java.io.IOException; -import java.nio.ByteBuffer; import java.nio.charset.Charset; -import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; @@ -69,12 +67,16 @@ public FileVisitResult preVisitDirectory( public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { String name = file.getFileName().toString(); + boolean java = name.endsWith(".java"); + if (!java && !name.endsWith(".kt")) { + return FileVisitResult.CONTINUE; + } + Path target = copyRoot.resolve(root.relativize(file).toString()); - if (name.endsWith(".java")) { - Files.createDirectories(target.getParent()); + Files.createDirectories(target.getParent()); + if (java) { Files.write(target, decode(Files.readAllBytes(file), encoding)); - } else if (name.endsWith(".kt")) { - Files.createDirectories(target.getParent()); + } else { Files.copy(file, target); } return FileVisitResult.CONTINUE; @@ -85,16 +87,10 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) return copies; } - // A byte the encoding cannot map becomes U+FFFD, as javac would report it, instead of dropping - // the file. - private static byte[] decode(byte[] bytes, Charset encoding) throws IOException { - String text = - encoding.newDecoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - return text.getBytes(StandardCharsets.UTF_8); + // new String replaces a byte the encoding cannot map with U+FFFD, as javac would report it, + // instead of dropping the file. + private static byte[] decode(byte[] bytes, Charset encoding) { + return new String(bytes, encoding).getBytes(StandardCharsets.UTF_8); } private static void deleteRecursively(Path path) throws IOException { diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index ac45a5b24..212a931df 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -4,8 +4,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; @@ -207,15 +207,11 @@ public void anNpmLauncherRunsWhenNeitherItNorNodeIsOnPath() throws Exception { // npm links hog to a `#!/usr/bin/env node` script next to node, in a directory such as // /opt/homebrew/bin that a build started from an IDE may not have on PATH. File npmBin = temp.newFolder("npm-bin"); - File node = new File(npmBin, "node"); - Files.write(node.toPath(), "#!/bin/sh\nexec /bin/sh \"$@\"\n".getBytes(StandardCharsets.UTF_8)); - assertTrue(node.setExecutable(true)); - File launcher = new File(npmBin, "hog"); - String script = new String(Files.readAllBytes(fakeHog(0, true).toPath()), StandardCharsets.UTF_8); - Files.write( - launcher.toPath(), - script.replace("#!/bin/sh", "#!/usr/bin/env node").getBytes(StandardCharsets.UTF_8)); - assertTrue(launcher.setExecutable(true)); + executable(new File(npmBin, "node"), "#!/bin/sh\nexec /bin/sh \"$@\"\n"); + File launcher = + executable( + new File(npmBin, "hog"), + fakeHogScript(0, true).replace("#!/bin/sh", "#!/usr/bin/env node")); mojo.hogExecutable = launcher.getAbsolutePath(); mojo.execute(); @@ -233,13 +229,8 @@ public void aFailedUploadFailsOnlyARequiredUpload() throws Exception { assertFalse(metaProperties().exists()); - mojo.requireUpload = true; - try { - mojo.execute(); - fail("expected a MojoExecutionException"); - } catch (MojoExecutionException e) { - assertTrue(e.getMessage(), e.getMessage().contains("exited with code 1")); - } + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("exited with code 1")); } @Test @@ -252,14 +243,9 @@ public void missingCredentialsFailOnlyARequiredUpload() throws Exception { assertFalse(metaProperties().exists()); - mojo.requireUpload = true; - try { - mojo.execute(); - fail("expected a MojoExecutionException"); - } catch (MojoExecutionException e) { - assertTrue(e.getMessage(), e.getMessage().contains("found no PostHog credentials")); - assertTrue(e.getMessage(), e.getMessage().contains("HOG_PERSONAL_API_KEY")); - } + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("found no PostHog credentials")); + assertTrue(message, message.contains("HOG_PERSONAL_API_KEY")); } @Test @@ -268,7 +254,7 @@ public void skipsOutsideCiAndDeletesTheStaleFile() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); mojo.environment = Collections.singletonMap("CI", "false"); - File stale = staleMetaProperties(classes); + File stale = staleMetaProperties(); mojo.execute(); @@ -322,17 +308,6 @@ public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception assertTrue(metaProperties().isFile()); } - @Test - public void uploadsAnApplicationThatNoModuleOfTheBuildDependsOn() throws Exception { - assumeUnix(); - mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); - - mojo.execute(); - - assertTrue(metaProperties().isFile()); - } - @Test public void skipsAProjectWithPomPackaging() throws Exception { assumeUnix(); @@ -372,14 +347,9 @@ public void aRequiredUploadFailsTheBuildWhenHogWritesNoFile() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.hogExecutable = fakeHog(0, false).getAbsolutePath(); - mojo.requireUpload = true; - try { - mojo.execute(); - fail("expected a MojoExecutionException"); - } catch (MojoExecutionException e) { - assertTrue(e.getMessage(), e.getMessage().contains("did not write")); - } + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("did not write")); assertFalse(metaProperties().exists()); } @@ -387,7 +357,7 @@ public void aRequiredUploadFailsTheBuildWhenHogWritesNoFile() throws Exception { public void skipsWhenHogIsMissing() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.hogExecutable = new File(temp.getRoot(), "no-such-hog").getAbsolutePath(); - File stale = staleMetaProperties(classes); + File stale = staleMetaProperties(); mojo.execute(); @@ -405,36 +375,26 @@ public void aUsageErrorPointsAtHogUpgrade() throws Exception { assertFalse(metaProperties().exists()); - mojo.requireUpload = true; - try { - mojo.execute(); - fail("expected a MojoExecutionException"); - } catch (MojoExecutionException e) { - assertTrue(e.getMessage(), e.getMessage().contains("exited with code 2")); - assertTrue(e.getMessage(), e.getMessage().contains("hog upgrade")); - } + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("exited with code 2")); + assertTrue(message, message.contains("hog upgrade")); } @Test public void aRequiredUploadFailsWithAnInstallHintWhenHogIsMissing() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.hogExecutable = new File(temp.getRoot(), "no-such-hog").getAbsolutePath(); - mojo.requireUpload = true; - try { - mojo.execute(); - fail("expected a MojoExecutionException"); - } catch (MojoExecutionException e) { - assertTrue(e.getMessage(), e.getMessage().contains("Install hog")); - assertTrue(e.getMessage(), e.getMessage().contains("posthog.hogExecutable")); - } + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("Install hog")); + assertTrue(message, message.contains("posthog.hogExecutable")); } @Test public void skipRunsNothingAndRemovesAStaleId() throws Exception { mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); - File stale = staleMetaProperties(classes); + File stale = staleMetaProperties(); mojo.skip = true; mojo.execute(); @@ -484,14 +444,7 @@ public void resolvePrefersPathThenInstallLocationsThenTheProjectLauncher() throw File node = executable(new File(temp.newFolder("node-bin"), "node")); assertEquals( projectLauncher.getAbsolutePath(), - Hog.resolve( - null, - env(""), - temp.getRoot(), - project, - false, - none(), - Collections.singletonList(node))); + resolve(null, env(""), project, false, none(), Collections.singletonList(node))); } @Test @@ -500,15 +453,7 @@ public void resolveSkipsAProjectLauncherWithoutNode() throws Exception { File project = temp.newFolder("app"); executable(new File(project, "node_modules/.bin/hog")); - String resolved = - Hog.resolve( - null, - env(""), - temp.getRoot(), - project, - false, - none(), - Collections.emptyList()); + String resolved = resolve(null, env(""), project, false, none(), none()); assertEquals(null, resolved); } @@ -564,13 +509,13 @@ public void cmdUnsafeValuesAreFound() { "say \"hi\"", "a^b", "a\nb")) { - assertEquals(unsafe, Hog.firstUnsafeForCmd(Arrays.asList("--source", unsafe))); + assertEquals(unsafe, Hog.firstUnsafeForCmd("hog", Arrays.asList("--source", unsafe))); } assertEquals( null, Hog.firstUnsafeForCmd( + "hog", Arrays.asList( - "hog", "--source", "C:\\My Projects\\app-1\\src\\main\\java", "--release-version", @@ -622,14 +567,16 @@ private File sourceRoot(String relative) { } private File metaProperties() { - return new File(classes, "posthog-meta.properties"); + return new File(classes, UploadSourcesMojo.META_PROPERTIES_FILE); } - private File staleMetaProperties(File dir) throws IOException { - assertTrue(dir.isDirectory() || dir.mkdirs()); - File file = new File(dir, "posthog-meta.properties"); - Files.write(file.toPath(), "io.posthog.proguard.mapid=stale\n".getBytes(StandardCharsets.UTF_8)); - return file; + private File staleMetaProperties() throws IOException { + return executable(metaProperties(), "io.posthog.proguard.mapid=stale\n"); + } + + private MojoExecutionException requiredUploadFailure() { + mojo.requireUpload = true; + return assertThrows(MojoExecutionException.class, mojo::execute); } /** @@ -638,8 +585,13 @@ private File staleMetaProperties(File dir) throws IOException { * and exits with the given code. */ private File fakeHog(int exitCode, boolean writeMetaProperties) throws IOException { - String script = - "#!/bin/sh\n" + return executable( + new File(temp.getRoot(), "fake-hog-" + exitCode + "-" + writeMetaProperties), + fakeHogScript(exitCode, writeMetaProperties)); + } + + private String fakeHogScript(int exitCode, boolean writeMetaProperties) { + return "#!/bin/sh\n" + "printf '%s\\n' \"$@\" > '" + argsFile.getAbsolutePath() + "'\n" @@ -660,10 +612,6 @@ private File fakeHog(int exitCode, boolean writeMetaProperties) throws IOExcepti + "exit " + exitCode + "\n"; - File hog = new File(temp.getRoot(), "fake-hog-" + exitCode + "-" + writeMetaProperties); - Files.write(hog.toPath(), script.getBytes(StandardCharsets.UTF_8)); - assertTrue(hog.setExecutable(true)); - return hog; } @Test @@ -723,13 +671,8 @@ public void aConfiguredSourceRootThatDoesNotExistFailsOnlyARequiredUpload() thro assertTrue(metaProperties().isFile()); assertFalse(recordedArgs().contains(typo.getAbsolutePath())); - mojo.requireUpload = true; - try { - mojo.execute(); - fail("expected a MojoExecutionException"); - } catch (MojoExecutionException e) { - assertTrue(e.getMessage(), e.getMessage().contains(typo + " does not exist")); - } + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains(typo + " does not exist")); } @Test @@ -747,10 +690,7 @@ public void anUnsetEncodingFallsBackToThePlatformDefault() { public void aRelativeHogExecutableResolvesAgainstTheProject() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); - File hog = new File(basedir, "tools/hog"); - assertTrue(hog.getParentFile().mkdirs()); - Files.copy(fakeHog(0, true).toPath(), hog.toPath()); - assertTrue(hog.setExecutable(true)); + executable(new File(basedir, "tools/hog"), fakeHogScript(0, true)); mojo.hogExecutable = "tools/hog"; mojo.execute(); @@ -890,8 +830,12 @@ private List recordedArgs() throws IOException { } private static File executable(File file) throws IOException { + return executable(file, "#!/bin/sh\n"); + } + + private static File executable(File file, String content) throws IOException { assertTrue(file.getParentFile().isDirectory() || file.getParentFile().mkdirs()); - Files.write(file.toPath(), "#!/bin/sh\n".getBytes(StandardCharsets.UTF_8)); + Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8)); assertTrue(file.setExecutable(true)); return file; } @@ -902,6 +846,16 @@ private String resolve( File workingDirectory, boolean isWindows, List installLocations) { + return resolve(configured, environment, workingDirectory, isWindows, installLocations, null); + } + + private String resolve( + String configured, + Map environment, + File workingDirectory, + boolean isWindows, + List installLocations, + List nodeLocations) { return Hog.resolve( configured, environment, @@ -909,7 +863,7 @@ private String resolve( workingDirectory, isWindows, installLocations, - null); + nodeLocations); } private static List none() { From 23f6cecc1265e109238a4d1d5b8ac2def48f46ac Mon Sep 17 00:00:00 2001 From: Rafa Audibert Date: Wed, 2 Dec 2026 13:23:32 -0300 Subject: [PATCH 12/14] feat(maven-plugin): require a hog new enough for jvm uploads Run `hog --version` before the upload. posthog-cli, or a hog older than MIN_HOG_VERSION (1.1.0, the first release with `hog error-tracking bundle`), skips the upload with a warning that says how to install or update hog, and fails it with requireUpload. The upload never runs with either. Versions compare numerically and ignore a prerelease suffix, and output without a version counts as too old. The exit 2 hint stays as a fallback. Co-Authored-By: Claude Opus 5.5 --- posthog-maven-plugin/README.md | 2 +- .../src/main/java/com/posthog/maven/Hog.java | 32 +++++++++ .../com/posthog/maven/UploadSourcesMojo.java | 55 ++++++++++++++-- .../posthog/maven/UploadSourcesMojoTest.java | 65 ++++++++++++++++++- 4 files changed, 143 insertions(+), 11 deletions(-) diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index b4563187a..4878f2d11 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -8,7 +8,7 @@ A build of unchanged code reuses the existing upload and sends no source files, ## Requirements -- [hog](https://github.com/PostHog/posthog/tree/master/hog) in a release that uploads JVM sources. Install it with `curl -fsSL https://releases.posthog.com/hog/install.sh | sh`, `brew install posthog/tap/hog` or `npm install -g hog`, or on Windows with `irm https://releases.posthog.com/hog/install.ps1 | iex`. Update an older hog with `hog upgrade`. +- [hog](https://github.com/PostHog/posthog/tree/master/hog) 1.1.0 or newer. Before the upload, the plugin runs `hog --version`, and skips the upload with a warning when it finds posthog-cli or an older hog. Install hog with `curl -fsSL https://releases.posthog.com/hog/install.sh | sh`, `brew install posthog/tap/hog` or `npm install -g hog`, or on Windows with `irm https://releases.posthog.com/hog/install.ps1 | iex`. Update an older hog with `hog upgrade`. - `posthog-server` with `posthog-meta.properties` support, and no `releaseIdentifier` set in code (an explicit value wins over the file). - PostHog credentials with error tracking write access, for the upload. See [Credentials](#credentials). diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java index 3e274d9d2..2ab4f6bfa 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java @@ -8,6 +8,8 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Finds hog, PostHog's command line, and builds the command line that runs it. It looks for hog in @@ -18,6 +20,11 @@ final class Hog { static final String DOTENV_FILE_VARIABLE = "HOG_DOTENV_FILE"; + // The first hog release with `hog error-tracking bundle`. + static final String MIN_HOG_VERSION = "1.1.0"; + + private static final Pattern VERSION = Pattern.compile("^(?:hog )?v?(\\d+)\\.(\\d+)\\.(\\d+)"); + static final int EXIT_USAGE = 2; /** hog's exit code when a person has to act first, such as logging in. */ static final int EXIT_NEEDS_PERSON = 3; @@ -297,6 +304,31 @@ static boolean isWindows() { return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win"); } + /** + * Why the hog that printed {@code version} for {@code --version} is too old to upload JVM + * sources, or null when it is {@link #MIN_HOG_VERSION} or newer. A prerelease suffix is + * ignored, and a line that holds no version counts as too old. + */ + static String versionProblem(String version) { + List found = versionNumbers(version); + if (found != null && compareVersions(found, versionNumbers(MIN_HOG_VERSION)) >= 0) { + return null; + } + return "hog " + + (version.isEmpty() ? "with no version" : version) + + " is too old to upload JVM sources. Run `hog upgrade` to get " + + MIN_HOG_VERSION + + " or newer."; + } + + private static List versionNumbers(String version) { + Matcher matcher = VERSION.matcher(version.trim()); + if (!matcher.find()) { + return null; + } + return versionParts(matcher.group(1) + "." + matcher.group(2) + "." + matcher.group(3)); + } + static boolean isBlank(String value) { return value == null || value.trim().isEmpty(); } diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index 6a53e2c77..720e8673f 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Consumer; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.model.Plugin; @@ -47,11 +48,11 @@ public class UploadSourcesMojo extends AbstractMojo { private static final String COMPILER_PLUGIN = "org.apache.maven.plugins:maven-compiler-plugin"; private static final String UNIX_INSTALL_HINT = - " Install hog (curl -fsSL https://releases.posthog.com/hog/install.sh | sh, brew install" - + " posthog/tap/hog, or npm install -g hog) or set posthog.hogExecutable."; + " Install hog: curl -fsSL https://releases.posthog.com/hog/install.sh | sh, brew install" + + " posthog/tap/hog, or npm install -g hog. Or set posthog.hogExecutable."; private static final String WINDOWS_INSTALL_HINT = - " Install hog (irm https://releases.posthog.com/hog/install.ps1 | iex, or npm install -g" - + " hog) or set posthog.hogExecutable."; + " Install hog: irm https://releases.posthog.com/hog/install.ps1 | iex, or npm install -g" + + " hog. Or set posthog.hogExecutable."; @Parameter(defaultValue = "${project}", readonly = true, required = true) MavenProject project; @@ -169,6 +170,18 @@ public void execute() throws MojoExecutionException { return; } + String versionProblem; + try { + versionProblem = versionProblem(executable, isWindows, installHint); + } catch (IOException e) { + skipOrFail("Could not run hog (" + executable + ")." + installHint, e); + return; + } + if (versionProblem != null) { + skipOrFail(versionProblem); + return; + } + roots = utf8Roots(roots); List args = hogArguments(roots); if (Hog.runsThroughCmd(executable, isWindows)) { @@ -199,7 +212,7 @@ public void execute() throws MojoExecutionException { } int exitCode; try { - exitCode = waitFor(process); + exitCode = waitFor(process, line -> getLog().info("[hog] " + line)); } catch (IOException e) { skipOrFail("Could not read the hog output.", e); return; @@ -521,13 +534,41 @@ private Process start(String executable, List args, boolean isWindows) return builder.start(); } - private int waitFor(Process process) throws IOException, MojoExecutionException { + /** + * Why this executable can't upload JVM sources, or null when it is a new enough hog. It runs + * {@code --version}, which needs no credentials and sends nothing to PostHog. + */ + private String versionProblem(String executable, boolean isWindows, String installHint) + throws IOException, MojoExecutionException { + List output = new ArrayList<>(); + int exitCode = + waitFor(start(executable, Collections.singletonList("--version"), isWindows), output::add); + String firstLine = output.isEmpty() ? "" : output.get(0).trim(); + getLog().debug(executable + " --version exited with " + exitCode + ": " + firstLine); + + if (firstLine.startsWith("posthog-cli")) { + return "posthog-cli can't upload JVM sources." + installHint; + } + if (exitCode != 0) { + return "Could not run hog (" + + executable + + "): --version exited with code " + + exitCode + + (firstLine.isEmpty() ? "" : ": " + firstLine) + + "." + + installHint; + } + return Hog.versionProblem(firstLine); + } + + private int waitFor(Process process, Consumer onLine) + throws IOException, MojoExecutionException { try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { - getLog().info("[hog] " + line); + onLine.accept(line); } return process.waitFor(); } catch (IOException e) { diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index 212a931df..f528b1945 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -365,6 +365,58 @@ public void skipsWhenHogIsMissing() throws Exception { assertFalse(metaProperties().exists()); } + @Test + public void posthogCliNeverRunsTheUpload() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + File posthogCli = + executable( + new File(temp.getRoot(), "bin/posthog-cli"), + fakeHogScript(0, true, "posthog-cli 0.18.10")); + mojo.hogExecutable = posthogCli.getAbsolutePath(); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(metaProperties().exists()); + + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("posthog-cli can't upload JVM sources. Install hog")); + assertFalse(argsFile.exists()); + } + + @Test + public void aHogOlderThanTheMinimumNeverRunsTheUpload() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + File oldHog = executable(new File(temp.getRoot(), "old/hog"), fakeHogScript(0, true, "1.0.1")); + mojo.hogExecutable = oldHog.getAbsolutePath(); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(metaProperties().exists()); + + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("hog 1.0.1 is too old to upload JVM sources")); + assertTrue(message, message.contains("hog upgrade")); + assertFalse(argsFile.exists()); + } + + @Test + public void versionsAreComparedNumericallyWithoutTheirPrereleaseSuffix() { + for (String newEnough : + Arrays.asList(Hog.MIN_HOG_VERSION, "1.1.1", "1.10.0", "2.0.0-rc.1", "hog 1.1.0")) { + assertEquals(newEnough, null, Hog.versionProblem(newEnough)); + } + + for (String tooOld : Arrays.asList("1.0.9", "0.99.0", "1.1", "garbage", "")) { + String problem = Hog.versionProblem(tooOld); + assertNotNull(tooOld, problem); + assertTrue(problem, problem.contains("Run `hog upgrade` to get " + Hog.MIN_HOG_VERSION)); + } + } + @Test public void aUsageErrorPointsAtHogUpgrade() throws Exception { assumeUnix(); @@ -580,9 +632,9 @@ private MojoExecutionException requiredUploadFailure() { } /** - * A shell script standing in for hog. It records its arguments one per line and - * HOG_DOTENV_FILE, writes posthog-meta.properties into the --meta-out directory when asked to, - * and exits with the given code. + * A shell script standing in for hog. It answers --version with {@code version}. Otherwise it + * records its arguments one per line and HOG_DOTENV_FILE, writes posthog-meta.properties into + * the --meta-out directory when asked to, and exits with the given code. */ private File fakeHog(int exitCode, boolean writeMetaProperties) throws IOException { return executable( @@ -591,7 +643,14 @@ private File fakeHog(int exitCode, boolean writeMetaProperties) throws IOExcepti } private String fakeHogScript(int exitCode, boolean writeMetaProperties) { + return fakeHogScript(exitCode, writeMetaProperties, Hog.MIN_HOG_VERSION); + } + + private String fakeHogScript(int exitCode, boolean writeMetaProperties, String version) { return "#!/bin/sh\n" + + "if [ \"$1\" = '--version' ]; then echo '" + + version + + "'; exit 0; fi\n" + "printf '%s\\n' \"$@\" > '" + argsFile.getAbsolutePath() + "'\n" From bf46023092caa27f3f960f54e0c6c41b172f1194 Mon Sep 17 00:00:00 2001 From: Rafa Audibert Date: Wed, 2 Dec 2026 13:24:48 -0300 Subject: [PATCH 13/14] fix(maven-plugin): leave out of the utf-8 copies what hog would skip The UTF-8 copies keep only Java and Kotlin files, so hog can't see the build files that mark a build output folder inside a copy. A broad root with a non-UTF-8 encoding could then upload generated sources that the same build without the copy skips. The copy now applies hog's folder skips to the original tree: hidden folders, node_modules, test source sets under src, and build, target and out folders next to a build file or src. A root is always copied. Co-Authored-By: Claude Opus 5.5 --- .../java/com/posthog/maven/Utf8Sources.java | 40 ++++++++++++++++++- .../posthog/maven/UploadSourcesMojoTest.java | 29 ++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java index f16d2b11b..52f625a3b 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java @@ -10,6 +10,7 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Stream; @@ -20,6 +21,23 @@ * upload without them. */ final class Utf8Sources { + // The folders hog skips when it walks a source root, so the copies hold only what hog would + // read from the original tree. A copy keeps no build files, so hog can't apply these rules to + // it. + private static final List BUILD_OUTPUT_FOLDERS = Arrays.asList("build", "target", "out"); + private static final List MODULE_MARKERS = + Arrays.asList( + "src", + "pom.xml", + "build.gradle", + "build.gradle.kts", + "settings.gradle", + "settings.gradle.kts", + "build.sbt", + "build.xml"); + private static final List TEST_SOURCE_SETS = + Arrays.asList("test", "androidTest", "testFixtures", "integrationTest"); + private Utf8Sources() {} static boolean isUtf8(Charset encoding) { @@ -57,8 +75,7 @@ public FileVisitResult preVisitDirectory( // A root such as the project directory holds the build directory, and // with it these copies. boolean buildOutput = dir.equals(build) && !root.startsWith(build); - boolean hidden = dir.getFileName().toString().startsWith("."); - return buildOutput || hidden || dir.equals(output) + return buildOutput || dir.equals(output) || skippedByHog(dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE; } @@ -87,6 +104,25 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) return copies; } + private static boolean skippedByHog(Path dir) { + String name = dir.getFileName().toString(); + Path parent = dir.getParent(); + if (name.startsWith(".") || name.equals("node_modules")) { + return true; + } + if (BUILD_OUTPUT_FOLDERS.contains(name)) { + for (String marker : MODULE_MARKERS) { + if (Files.exists(parent.resolve(marker))) { + return true; + } + } + return false; + } + return parent.getFileName() != null + && parent.getFileName().toString().equals("src") + && TEST_SOURCE_SETS.contains(name); + } + // new String replaces a byte the encoding cannot map with U+FFFD, as javac would report it, // instead of dropping the file. private static byte[] decode(byte[] bytes, Charset encoding) { diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index f528b1945..85a86e380 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -701,6 +701,35 @@ public void utf8CopiesSkipTheBuildDirectoryOfAnUnnormalizedRoot() throws Excepti } } + @Test + public void utf8CopiesLeaveOutWhatHogWouldSkipInTheOriginalTree() throws Exception { + File module = temp.newFolder("billing"); + Files.write(new File(module, "pom.xml").toPath(), "".getBytes(StandardCharsets.UTF_8)); + for (String path : + Arrays.asList( + "src/main/java/com/acme/App.java", + "target/generated-sources/com/acme/X.java", + "src/test/java/com/acme/AppTest.java", + "node_modules/pkg/Y.java")) { + File file = new File(module, path); + assertTrue(file.getParentFile().mkdirs()); + Files.write(file.toPath(), "package com.acme;\n".getBytes(StandardCharsets.ISO_8859_1)); + } + + File copy = + Utf8Sources.copy( + Collections.singletonList(module), + StandardCharsets.ISO_8859_1, + new File(basedir, "target/posthog/utf8-sources"), + new File(basedir, "target")) + .get(0); + + assertTrue(new File(copy, "src/main/java/com/acme/App.java").isFile()); + assertFalse(new File(copy, "target").exists()); + assertFalse(new File(copy, "src/test").exists()); + assertFalse(new File(copy, "node_modules").exists()); + } + @Test public void additionalSourceRootsAddToTheDefaultRoots() throws Exception { assumeUnix(); From 211887eccc9260ae8ff81917dc9324d1c048e9bf Mon Sep 17 00:00:00 2001 From: ablaszkiewicz Date: Thu, 3 Dec 2026 20:24:29 +0100 Subject: [PATCH 14/14] fix(maven-plugin): keep uploading from apps that other modules depend on A module counted as a library whenever another module of the build depended on it, so an application with an integration test, coverage or distribution module skipped the upload in CI with only an info line. Only a dependent module that runs the goal on sources of its own makes a module a library now. - A failed UTF-8 copy warns instead of failing a build whose upload is optional. - The UTF-8 copies keep a Java file that is valid UTF-8 already, so the sources of a module with another encoding stay readable. - The version check finds the version below a launcher warning on stderr. - The README says how a dotenv path resolves in a multi-module build, how a generated timestamp defeats reuse, and that hog now keeps a file that isn't UTF-8. Co-Authored-By: Claude Opus 5.5 --- posthog-maven-plugin/README.md | 8 +- .../src/main/java/com/posthog/maven/Hog.java | 5 + .../com/posthog/maven/UploadSourcesMojo.java | 98 ++++++++++++++----- .../java/com/posthog/maven/Utf8Sources.java | 26 +++-- .../posthog/maven/UploadSourcesMojoTest.java | 89 ++++++++++++++++- 5 files changed, 185 insertions(+), 41 deletions(-) diff --git a/posthog-maven-plugin/README.md b/posthog-maven-plugin/README.md index 4878f2d11..f2e3218d6 100644 --- a/posthog-maven-plugin/README.md +++ b/posthog-maven-plugin/README.md @@ -4,7 +4,7 @@ Uploads your application's Java and Kotlin sources to PostHog, so error tracking On each CI build, the `upload-sources` goal runs [hog](https://github.com/PostHog/posthog/tree/master/hog), PostHog's command line, as `hog error-tracking process --kind jvm`. hog bundles the sources, uploads them under an id derived from their content, and writes that id and the id of the build's release into `posthog-meta.properties` in the classes directory, so it is packaged with your classes. At startup, [`posthog-server`](../posthog-server) reads the file. It sends the first id on every exception frame, and PostHog looks up the uploaded sources by it. It sends the release id with every exception, and PostHog reports that release. -A build of unchanged code reuses the existing upload and sends no source files, also in a new release. Changed code gets a new id and a new upload. The goal rewrites or deletes the file on every build, so it always matches the code that was compiled and the release it belongs to. +A build of unchanged code reuses the existing upload and sends no source files, also in a new release. Changed code gets a new id and a new upload. A generated source that holds the time of the build changes on every build, so turn that time off, as `-Amapstruct.suppressGeneratorTimestamp=true` does for MapStruct mappers. The goal rewrites or deletes the file on every build, so it always matches the code that was compiled and the release it belongs to. ## Requirements @@ -35,7 +35,7 @@ A build of unchanged code reuses the existing upload and sends no source files, The goal binds to the `process-classes` phase. It runs after compilation, so the upload includes the sources that annotation processors such as MapStruct generate, and `mvn package` uploads before it packages. A command that stops before that phase uploads nothing: run `mvn package jib:build` or `mvn process-classes jib:build`, not `mvn compile jib:build`. -hog reads sources as UTF-8, and skips a file that isn't UTF-8 with a warning. When `project.build.sourceEncoding` or the compiler's `encoding` names another encoding, the plugin uploads UTF-8 copies of the Java sources from `target/posthog/utf8-sources`. +hog reads sources as UTF-8, and shows a replacement character for each byte that isn't valid UTF-8. When `project.build.sourceEncoding` or the compiler's `encoding` names another encoding, the plugin uploads UTF-8 copies of the Java sources from `target/posthog/utf8-sources`, so their non-ASCII characters show. A file that is valid UTF-8 already, such as one from another module, is copied as it is. ### Releases @@ -51,13 +51,13 @@ hog reads them from the environment, from a dotenv file, from the CI job's OIDC - `HOG_PROJECT_ID`: your project id - `HOG_PERSONAL_API_KEY`: a personal API key with error tracking write access -To use a dotenv file, set `.env` or pass `-Dposthog.dotenvFile=.env`. The plugin passes it to hog as `HOG_DOTENV_FILE`. +To use a dotenv file, set `.env` or pass `-Dposthog.dotenvFile=.env`. The plugin passes it to hog as `HOG_DOTENV_FILE`. A relative path resolves against the module directory, so in a multi-module build set `${maven.multiModuleProjectDirectory}/.env` for a file in the top directory. ### When it uploads By default, only a CI build uploads. A build counts as CI when the `CI` environment variable is set, as GitHub Actions, GitLab CI, CircleCI, Bitbucket Pipelines and most other services set it, or when it runs on Jenkins, Azure Pipelines, TeamCity or AWS CodeBuild. A local build skips the upload, so it doesn't upload work in progress or need the network. An offline build (`mvn -o`) skips it too. -In a multi-module build, a module that another module of the build depends on is a library, and it skips the upload. The SDK reads the first `posthog-meta.properties` on the classpath, so a library's file could replace the application's. Run the goal in the application module, and add the library's source directories to its `additionalSourceRoots`: +In a multi-module build, a module is a library when another module of the build depends on it and runs the goal too, and the library skips the upload. The SDK reads the first `posthog-meta.properties` on the classpath, so a library's file could replace the application's. A module that depends on the application and doesn't upload, such as one for integration tests or a distribution, leaves the application uploading. A library that runs the goal in a build without its application, such as `mvn -pl billing deploy` or a build of its own repository, puts its file into its jar. So run the goal only in the application module, and add the library's source directories to its `additionalSourceRoots`: ```xml diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java index 2ab4f6bfa..1c4e81217 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java @@ -321,6 +321,11 @@ static String versionProblem(String version) { + " or newer."; } + /** Whether {@code line} is the version that {@code hog --version} prints. */ + static boolean isVersion(String line) { + return VERSION.matcher(line.trim()).find(); + } + private static List versionNumbers(String version) { Matcher matcher = VERSION.matcher(version.trim()); if (!matcher.find()) { diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java index 720e8673f..61ea8a1ce 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -44,6 +44,8 @@ public class UploadSourcesMojo extends AbstractMojo { static final String META_PROPERTIES_FILE = "posthog-meta.properties"; + private static final String PLUGIN_KEY = "com.posthog:posthog-maven-plugin"; + private static final String GOAL = "upload-sources"; private static final String KOTLIN_MAVEN_PLUGIN = "org.jetbrains.kotlin:kotlin-maven-plugin"; private static final String COMPILER_PLUGIN = "org.apache.maven.plugins:maven-compiler-plugin"; @@ -182,7 +184,12 @@ public void execute() throws MojoExecutionException { return; } - roots = utf8Roots(roots); + try { + roots = utf8Roots(roots); + } catch (IOException e) { + skipOrFail("Could not copy the sources as UTF-8.", e); + return; + } List args = hogArguments(roots); if (Hog.runsThroughCmd(executable, isWindows)) { String unsafe = Hog.firstUnsafeForCmd(executable, args); @@ -245,26 +252,62 @@ private String reasonToSkipOptionalUpload() { return "Maven runs offline"; } // The SDK reads the first posthog-meta.properties on the classpath, so a library's file - // can replace the application's. - List dependents = dependentModules(); - if (!dependents.isEmpty()) { - return dependents.get(0).getArtifactId() - + " depends on this module, so it is a library. Upload its sources from the" - + " application module with additionalSourceRoots"; + // can replace the application's. A module that only depends on this one, such as one that + // runs integration tests or assembles a distribution, writes no file of its own, so this + // module stays the application. + for (MavenProject dependent : dependentModules()) { + if (uploadsOwnSources(dependent)) { + return dependent.getArtifactId() + + " depends on this module and uploads its own sources, so this module is a" + + " library. Upload its sources from " + + dependent.getArtifactId() + + " with additionalSourceRoots"; + } } return null; } + /** + * Whether {@code module} runs this goal on sources of its own. A module with pom packaging or + * with no source directory skips the upload, so it writes no file. + */ + private static boolean uploadsOwnSources(MavenProject module) { + if ("pom".equals(module.getPackaging())) { + return false; + } + Plugin plugin = module.getPlugin(PLUGIN_KEY); + if (plugin == null) { + return false; + } + boolean runsGoal = false; + for (PluginExecution execution : plugin.getExecutions()) { + runsGoal |= execution.getGoals().contains(GOAL); + } + if (!runsGoal) { + return false; + } + List roots = kotlinSourceDirs(module); + for (String root : module.getCompileSourceRoots()) { + roots.add(new File(root)); + } + for (File root : roots) { + if (root.isDirectory()) { + return true; + } + } + return false; + } + boolean isOffline() { return session != null && session.isOffline(); } - /** The modules of this build that depend on this one. */ + /** The modules of this build that depend on this one, directly or through other modules. */ List dependentModules() { ProjectDependencyGraph graph = session == null ? null : session.getProjectDependencyGraph(); return graph == null ? Collections.emptyList() - : graph.getDownstreamProjects(project, false); + : graph.getDownstreamProjects(project, true); } /** @@ -344,7 +387,7 @@ private List existingSourceRoots() throws MojoExecutionException { for (String root : project.getCompileSourceRoots()) { defaults.add(normalized(new File(root))); } - for (File root : kotlinSourceDirs()) { + for (File root : kotlinSourceDirs(project)) { defaults.add(normalized(root)); } } @@ -387,16 +430,16 @@ private static File normalized(File file) { * with Java and Kotlin sources usually lists {@code src/main/kotlin} there, as the Kotlin docs * show, and that list never becomes a compile source root of the project. */ - private List kotlinSourceDirs() { + private static List kotlinSourceDirs(MavenProject module) { List dirs = new ArrayList<>(); - Plugin kotlin = project.getPlugin(KOTLIN_MAVEN_PLUGIN); + Plugin kotlin = module.getPlugin(KOTLIN_MAVEN_PLUGIN); if (kotlin == null) { return dirs; } - addSourceDirs(kotlin.getConfiguration(), dirs); + addSourceDirs(kotlin.getConfiguration(), module.getBasedir(), dirs); for (PluginExecution execution : kotlin.getExecutions()) { if (execution.getGoals().contains("compile")) { - addSourceDirs(execution.getConfiguration(), dirs); + addSourceDirs(execution.getConfiguration(), module.getBasedir(), dirs); } } return dirs; @@ -406,18 +449,14 @@ private List kotlinSourceDirs() { * Copies of the roots with UTF-8 text when the compiler reads the sources in another encoding, * otherwise the roots themselves. */ - private List utf8Roots(List roots) throws MojoExecutionException { + private List utf8Roots(List roots) throws IOException { Charset encoding = sourceEncoding(Charset.defaultCharset()); if (Utf8Sources.isUtf8(encoding)) { return roots; } File buildDirectory = new File(project.getBuild().getDirectory()); - try { - return Utf8Sources.copy( - roots, encoding, new File(buildDirectory, "posthog/utf8-sources"), buildDirectory); - } catch (IOException e) { - throw new MojoExecutionException("Could not copy the sources as UTF-8", e); - } + return Utf8Sources.copy( + roots, encoding, new File(buildDirectory, "posthog/utf8-sources"), buildDirectory); } /** @@ -463,7 +502,7 @@ private static String childValue(Object configuration, String name) { return child != null && !Hog.isBlank(child.getValue()) ? child.getValue().trim() : null; } - private void addSourceDirs(Object configuration, List dirs) { + private static void addSourceDirs(Object configuration, File basedir, List dirs) { if (!(configuration instanceof Xpp3Dom)) { return; } @@ -476,7 +515,7 @@ private void addSourceDirs(Object configuration, List dirs) { continue; } File dir = new File(sourceDir.getValue().trim()); - dirs.add(dir.isAbsolute() ? dir : new File(project.getBasedir(), dir.getPath())); + dirs.add(dir.isAbsolute() ? dir : new File(basedir, dir.getPath())); } } @@ -545,8 +584,17 @@ private String versionProblem(String executable, boolean isWindows, String insta waitFor(start(executable, Collections.singletonList("--version"), isWindows), output::add); String firstLine = output.isEmpty() ? "" : output.get(0).trim(); getLog().debug(executable + " --version exited with " + exitCode + ": " + firstLine); + // The output holds stderr too, where a launcher can warn before hog prints its version, + // as Node does when NODE_OPTIONS holds a deprecated flag. + String versionLine = firstLine; + for (String line : output) { + if (line.trim().startsWith("posthog-cli") || Hog.isVersion(line)) { + versionLine = line.trim(); + break; + } + } - if (firstLine.startsWith("posthog-cli")) { + if (versionLine.startsWith("posthog-cli")) { return "posthog-cli can't upload JVM sources." + installHint; } if (exitCode != 0) { @@ -558,7 +606,7 @@ private String versionProblem(String executable, boolean isWindows, String insta + "." + installHint; } - return Hog.versionProblem(firstLine); + return Hog.versionProblem(versionLine); } private int waitFor(Process process, Consumer onLine) diff --git a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java index 52f625a3b..eb798d3c5 100644 --- a/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java @@ -2,6 +2,8 @@ import java.io.File; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; @@ -16,9 +18,9 @@ import java.util.stream.Stream; /** - * Copies source roots with UTF-8 text. hog reads every source file as UTF-8 and skips, with a - * warning, a file it cannot decode, so a project whose Java sources use another encoding would - * upload without them. + * Copies source roots with UTF-8 text. hog reads every source file as UTF-8 and shows a + * replacement character for each byte that is not valid UTF-8, so the non-ASCII characters of a + * project whose Java sources use another encoding would not show. */ final class Utf8Sources { // The folders hog skips when it walks a source root, so the copies hold only what hog would @@ -47,8 +49,9 @@ static boolean isUtf8(Charset encoding) { /** * Copies each root into {@code /}, with the same relative * paths, and returns the copies. Java files are decoded from {@code encoding} and written as - * UTF-8. Kotlin files are copied unchanged, because the Kotlin compiler reads only UTF-8. - * Characters and line breaks stay the same, so every line keeps its number. + * UTF-8, unless they are valid UTF-8 already, as the sources of another module can be. Kotlin + * files are copied unchanged, because the Kotlin compiler reads only UTF-8. Characters and + * line breaks stay the same, so every line keeps its number. */ static List copy( List roots, Charset encoding, File outputDirectory, File buildDirectory) @@ -123,10 +126,17 @@ private static boolean skippedByHog(Path dir) { && TEST_SOURCE_SETS.contains(name); } - // new String replaces a byte the encoding cannot map with U+FFFD, as javac would report it, - // instead of dropping the file. + // Text in a single-byte encoding such as windows-1252 is almost never valid UTF-8 when it holds + // a non-ASCII character, so a file that is valid UTF-8 is kept as it is. new String replaces a + // byte the encoding cannot map with U+FFFD, as javac would report it, instead of dropping the + // file. private static byte[] decode(byte[] bytes, Charset encoding) { - return new String(bytes, encoding).getBytes(StandardCharsets.UTF_8); + try { + StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)); + return bytes; + } catch (CharacterCodingException e) { + return new String(bytes, encoding).getBytes(StandardCharsets.UTF_8); + } } private static void deleteRecursively(Path path) throws IOException { diff --git a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java index 85a86e380..bb1af7d05 100644 --- a/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -173,6 +173,10 @@ public void javaSourcesInAnotherEncodingAreUploadedAsUtf8() throws Exception { File kotlinFile = new File(java, "com/acme/Tax.kt"); byte[] kotlin = "package com.acme\n// 5 \u20ac\n".getBytes(StandardCharsets.UTF_8); Files.write(kotlinFile.toPath(), kotlin); + // A module with UTF-8 sources, added to the upload of a module with another encoding. + File utf8File = new File(java, "com/acme/Shared.java"); + byte[] utf8 = "package com.acme;\n// 5 \u20ac\nclass Shared {}\n".getBytes(StandardCharsets.UTF_8); + Files.write(utf8File.toPath(), utf8); mojo.project.addCompileSourceRoot(java.getAbsolutePath()); // The compiler's own encoding wins over the project property. mojo.project.getProperties().setProperty("project.build.sourceEncoding", "ISO-8859-1"); @@ -197,9 +201,27 @@ public void javaSourcesInAnotherEncodingAreUploadedAsUtf8() throws Exception { Files.readAllBytes(new File(copy, "com/acme/Price.java").toPath()), StandardCharsets.UTF_8)); assertArrayEquals(kotlin, Files.readAllBytes(new File(copy, "com/acme/Tax.kt").toPath())); + assertArrayEquals(utf8, Files.readAllBytes(new File(copy, "com/acme/Shared.java").toPath())); assertArrayEquals(cp1252, Files.readAllBytes(javaFile.toPath())); } + @Test + public void aFailedUtf8CopyFailsOnlyARequiredUpload() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.project.getProperties().setProperty("project.build.sourceEncoding", "ISO-8859-1"); + // The copies go into target/posthog, which can't be a folder while a file holds its name. + assertTrue(new File(basedir, "target").mkdirs()); + assertTrue(new File(basedir, "target/posthog").createNewFile()); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); + + mojo.execute(); + + assertFalse(argsFile.exists()); + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("Could not copy the sources as UTF-8")); + } + @Test public void anNpmLauncherRunsWhenNeitherItNorNodeIsOnPath() throws Exception { assumeUnix(); @@ -289,13 +311,11 @@ public void skipsWhenMavenRunsOffline() throws Exception { } @Test - public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception { + public void skipsALibraryThatAnotherUploadingModuleOfTheBuildDependsOn() throws Exception { assumeUnix(); mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); - MavenProject app = new MavenProject(); - app.setArtifactId("demo-app"); - mojo.dependents = Collections.singletonList(app); + mojo.dependents = Collections.singletonList(dependentModule("demo-app", true)); mojo.execute(); @@ -308,6 +328,20 @@ public void skipsALibraryThatAnotherModuleOfTheBuildDependsOn() throws Exception assertTrue(metaProperties().isFile()); } + @Test + public void uploadsWhenTheModulesThatDependOnItUploadNothing() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); + // An integration test module runs the goal from a shared parent but has only test + // sources, and a distribution module does not run it. + mojo.dependents = Arrays.asList(dependentModule("demo-it", false), distributionModule()); + + mojo.execute(); + + assertTrue(metaProperties().isFile()); + } + @Test public void skipsAProjectWithPomPackaging() throws Exception { assumeUnix(); @@ -403,6 +437,20 @@ public void aHogOlderThanTheMinimumNeverRunsTheUpload() throws Exception { assertFalse(argsFile.exists()); } + @Test + public void aWarningBeforeTheVersionDoesNotHideIt() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + String warned = "(node:42) [DEP0040] DeprecationWarning: a launcher warning\n" + Hog.MIN_HOG_VERSION; + mojo.hogExecutable = + executable(new File(temp.getRoot(), "warned/hog"), fakeHogScript(0, true, warned)) + .getAbsolutePath(); + + mojo.execute(); + + assertTrue(metaProperties().isFile()); + } + @Test public void versionsAreComparedNumericallyWithoutTheirPrereleaseSuffix() { for (String newEnough : @@ -612,6 +660,39 @@ public void commandLineWrapsABareNameInCmdOnWindows() { Hog.commandLine("/bin/hog", args, false)); } + // A module of the same build that runs this goal, with or without a source directory. + private MavenProject dependentModule(String artifactId, boolean hasSources) throws IOException { + File moduleDir = temp.newFolder(artifactId); + MavenProject module = new MavenProject(); + module.setArtifactId(artifactId); + module.setFile(new File(moduleDir, "pom.xml")); + File sources = new File(moduleDir, "src/main/java"); + if (hasSources) { + assertTrue(sources.mkdirs()); + } + module.addCompileSourceRoot(sources.getAbsolutePath()); + PluginExecution upload = new PluginExecution(); + upload.addGoal("upload-sources"); + Plugin plugin = new Plugin(); + plugin.setGroupId("com.posthog"); + plugin.setArtifactId("posthog-maven-plugin"); + plugin.addExecution(upload); + Build build = new Build(); + build.addPlugin(plugin); + module.getModel().setBuild(build); + return module; + } + + private MavenProject distributionModule() throws IOException { + File moduleDir = temp.newFolder("demo-dist"); + assertTrue(new File(moduleDir, "src/main/java").mkdirs()); + MavenProject module = new MavenProject(); + module.setArtifactId("demo-dist"); + module.setFile(new File(moduleDir, "pom.xml")); + module.addCompileSourceRoot(new File(moduleDir, "src/main/java").getAbsolutePath()); + return module; + } + private File sourceRoot(String relative) { File dir = new File(basedir, relative); assertTrue(dir.mkdirs());