diff --git a/.changeset/maven-plugin-upload-sources.md b/.changeset/maven-plugin-upload-sources.md new file mode 100644 index 000000000..4d5da9979 --- /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 `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/.github/workflows/release.yml b/.github/workflows/release.yml index b4d67eaab..987e0e4c4 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..83df44e78 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 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/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 bf10b4d85..5a57979d2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -27,6 +27,7 @@ androidVersion=4.2.3 surveysComposeVersion=1.1.0 serverVersion=2.29.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..f2e3218d6 --- /dev/null +++ b/posthog-maven-plugin/README.md @@ -0,0 +1,96 @@ +# 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 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. 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 + +- [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). + +## Usage + +```xml + + + + com.posthog + posthog-maven-plugin + 0.1.0 + + + + upload-sources + + + + + + +``` + +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 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 + +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 + +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. + +- `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`. 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 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 + + + ${project.basedir}/../billing/src/main/java + + +``` + +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 + +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 + +| Parameter | User property | Default | Description | +|---|---|---|---| +| `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`. | +| `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. | + +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 + +- 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/build.gradle.kts b/posthog-maven-plugin/build.gradle.kts new file mode 100644 index 000000000..4e7449f95 --- /dev/null +++ b/posthog-maven-plugin/build.gradle.kts @@ -0,0 +1,79 @@ +// 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) +} + +// 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/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/CiEnvironment.java b/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java new file mode 100644 index 000000000..2394b6ff7 --- /dev/null +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/CiEnvironment.java @@ -0,0 +1,26 @@ +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 (!Hog.isBlank(ci) && !ci.trim().equalsIgnoreCase("false") && !ci.trim().equals("0")) { + return true; + } + for (String name : CI_SERVICE_VARIABLES) { + if (!Hog.isBlank(environment.get(name))) { + return true; + } + } + return false; + } +} 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 new file mode 100644 index 000000000..1c4e81217 --- /dev/null +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Hog.java @@ -0,0 +1,454 @@ +package com.posthog.maven; + +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; +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 + * the same places and order as the PostHog Android Gradle plugin. + */ +final class Hog { + static final String EXECUTABLE = "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; + + 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 Hog() {} + + /** + * 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, + File workingDirectory, + boolean isWindows, + List installLocations, + List nodeLocations) { + if (!isBlank(configured)) { + String trimmed = configured.trim(); + if (!trimmed.equals(EXECUTABLE)) { + return trimmed; + } + } + + if (isWindows) { + String onPath = findOnWindowsPath(environment); + if (onPath != null) { + return onPath; + } + 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(); + } + + List locations = + installLocations != null ? installLocations : unixInstallLocations(home); + File installed = firstRunnable(locations, false); + if (installed != null) { + return installed.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)) { + return resolveNode(environment, home, false, nodeLocations) != null + ? launcher.getAbsolutePath() + : null; + } + } + return null; + } + + /** + * 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 (!isBlank(extension)) { + 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 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<>(); + if (runsThroughCmd(executable, isWindows)) { + command.add("cmd"); + command.add("/c"); + } + command.add(executable); + command.addAll(args); + return command; + } + + static boolean runsThroughCmd(String executable, boolean isWindows) { + return isWindows && !executable.toLowerCase(Locale.ROOT).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 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(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) { + return value; + } + } + } + return null; + } + + /** + * 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, + Map environment, + File home, + boolean isWindows, + List knownNodeLocations) { + String path = variable(environment, "PATH", 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<>(nvmBinaries(home, "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")); + } + File node = firstRunnable(candidates, false); + return node != null ? node.getAbsoluteFile() : null; + } + + 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."; + } + + /** 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()) { + return null; + } + return versionParts(matcher.group(1) + "." + matcher.group(2) + "." + matcher.group(3)); + } + + 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(name) : key.equals(name)) { + return key; + } + } + return name; + } + + private static String variable(Map environment, String name, boolean isWindows) { + return environment.get(key(environment, name, isWindows)); + } + + 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()) { + 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, isWindows)) { + return candidate; + } + } + return null; + } + + 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 hog 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 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 binaries; + } + + 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 new file mode 100644 index 000000000..61ea8a1ce --- /dev/null +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/UploadSourcesMojo.java @@ -0,0 +1,631 @@ +package com.posthog.maven; + +import java.io.BufferedReader; +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.Collections; +import java.util.LinkedHashSet; +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; +import org.apache.maven.model.PluginExecution; +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. 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 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. + */ +@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 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"; + + 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."; + 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."; + + @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; + + /** + * 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 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, + * so that it never ships a build whose exceptions show no source code. + */ + @Parameter(property = "posthog.requireUpload", defaultValue = "false") + boolean requireUpload; + + /** + * 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.hogExecutable") + String hogExecutable; + + /** + * 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; + + /** The release the build belongs to. Exceptions from the build report it. */ + @Parameter(property = "posthog.releaseName", defaultValue = "${project.artifactId}") + String releaseName; + + /** + * 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. + */ + @Parameter(property = "posthog.releaseVersion") + String releaseVersion; + + /** + * The source directories to upload. Defaults to the project's compile source roots and the + * 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 + // sources. hog removes it whenever it runs, and this covers the builds that never start + // hog. + deleteStaleMetaProperties(); + + if (skip) { + getLog().info("Skipping the PostHog source upload (posthog.skip is true)"); + 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"); + return; + } + + boolean isWindows = Hog.isWindows(); + 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); + return; + } + String executable = + Hog.resolve( + configured, environment, home(), project.getBasedir(), isWindows, null, null); + if (executable == null) { + skipOrFail("hog was not found." + installHint); + 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; + } + + 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); + 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 " + + problem + + ". Set posthog.hogExecutable to hog.exe, which runs directly."); + return; + } + } + + Process process; + try { + process = start(executable, args, isWindows); + } catch (IOException e) { + skipOrFail("Could not run hog (" + executable + ")." + installHint, e); + return; + } + int exitCode; + try { + exitCode = waitFor(process, line -> getLog().info("[hog] " + line)); + } catch (IOException e) { + skipOrFail("Could not read the hog output.", e); + return; + } + if (exitCode == Hog.EXIT_NEEDS_PERSON) { + skipOrFail( + "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 != 0) { + // A hog from before JVM source uploads rejects --kind jvm and --meta-out as a usage + // error. + String hint = exitCode == Hog.EXIT_USAGE ? " Update hog with `hog upgrade`." : ""; + skipOrFail("hog exited with code " + exitCode + "." + hint); + return; + } + + if (!metaPropertiesFile().isFile()) { + skipOrFail("hog exited successfully but did not write " + metaPropertiesFile() + "."); + } + } + + /** 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 (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. 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, directly or through other modules. */ + List dependentModules() { + ProjectDependencyGraph graph = session == null ? null : session.getProjectDependencyGraph(); + return graph == null + ? Collections.emptyList() + : graph.getDownstreamProjects(project, true); + } + + /** + * {@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 (Hog.isBlank(hogExecutable)) { + return null; + } + String trimmed = hogExecutable.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 hogArguments(List roots) { + List args = new ArrayList<>(); + args.add("error-tracking"); + args.add("process"); + for (File root : roots) { + 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 (!Hog.isBlank(releaseName)) { + args.add("--release-name"); + args.add(releaseName); + } + if (!Hog.isBlank(releaseVersion)) { + 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; + } + + private List existingSourceRoots() throws MojoExecutionException { + Set defaults = new LinkedHashSet<>(); + Set configured = new LinkedHashSet<>(); + if (sourceRoots != null && !sourceRoots.isEmpty()) { + for (File root : sourceRoots) { + configured.add(normalized(root)); + } + } else { + for (String root : project.getCompileSourceRoots()) { + defaults.add(normalized(new File(root))); + } + for (File root : kotlinSourceDirs(project)) { + defaults.add(normalized(root)); + } + } + if (additionalSourceRoots != null) { + for (File root : additionalSourceRoots) { + configured.add(normalized(root)); + } + } + + Set existing = new LinkedHashSet<>(); + for (File root : defaults) { + if (root.isDirectory()) { + existing.add(root); + } else { + getLog().debug("Skipping missing source root " + root); + } + } + 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(); + } + + /** + * 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 static List kotlinSourceDirs(MavenProject module) { + List dirs = new ArrayList<>(); + Plugin kotlin = module.getPlugin(KOTLIN_MAVEN_PLUGIN); + if (kotlin == null) { + return dirs; + } + addSourceDirs(kotlin.getConfiguration(), module.getBasedir(), dirs); + for (PluginExecution execution : kotlin.getExecutions()) { + if (execution.getGoals().contains("compile")) { + addSourceDirs(execution.getConfiguration(), module.getBasedir(), dirs); + } + } + 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 IOException { + Charset encoding = sourceEncoding(Charset.defaultCharset()); + if (Utf8Sources.isUtf8(encoding)) { + return roots; + } + File buildDirectory = new File(project.getBuild().getDirectory()); + return Utf8Sources.copy( + roots, encoding, new File(buildDirectory, "posthog/utf8-sources"), buildDirectory); + } + + /** + * The encoding maven-compiler-plugin reads the sources in: its {@code encoding} parameter, + * 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. + */ + Charset sourceEncoding(Charset platformDefault) { + String encoding = null; + Plugin compiler = project.getPlugin(COMPILER_PLUGIN); + if (compiler != null) { + for (PluginExecution execution : compiler.getExecutions()) { + if (execution.getGoals().contains("compile")) { + encoding = childValue(execution.getConfiguration(), "encoding"); + if (encoding != null) { + break; + } + } + } + if (encoding == null) { + encoding = childValue(compiler.getConfiguration(), "encoding"); + } + } + if (encoding == null) { + encoding = project.getProperties().getProperty("project.build.sourceEncoding"); + } + if (Hog.isBlank(encoding)) { + return platformDefault; + } + try { + return Charset.forName(encoding.trim()); + } catch (IllegalArgumentException e) { + getLog().warn("Unknown source encoding " + encoding + ", uploading the sources as is"); + return StandardCharsets.UTF_8; + } + } + + private static String childValue(Object configuration, String name) { + if (!(configuration instanceof Xpp3Dom)) { + return null; + } + Xpp3Dom child = ((Xpp3Dom) configuration).getChild(name); + return child != null && !Hog.isBlank(child.getValue()) ? child.getValue().trim() : null; + } + + private static void addSourceDirs(Object configuration, File basedir, List dirs) { + if (!(configuration instanceof Xpp3Dom)) { + return; + } + Xpp3Dom sourceDirs = ((Xpp3Dom) configuration).getChild("sourceDirs"); + if (sourceDirs == null) { + return; + } + for (Xpp3Dom sourceDir : sourceDirs.getChildren()) { + if (Hog.isBlank(sourceDir.getValue())) { + continue; + } + File dir = new File(sourceDir.getValue().trim()); + dirs.add(dir.isAbsolute() ? dir : new File(basedir, dir.getPath())); + } + } + + private void deleteStaleMetaProperties() throws MojoExecutionException { + 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); + } + 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."); + } + + private Process start(String executable, List args, boolean isWindows) + throws IOException { + List command = Hog.commandLine(executable, args, isWindows); + getLog().debug("Running " + String.join(" ", command)); + + ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); + if (project.getBasedir() != null) { + // 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(Hog.DOTENV_FILE_VARIABLE, dotenvFile.getAbsolutePath()); + } + String path = Hog.launcherPath(executable, environment, home(), isWindows, null); + if (path != null) { + environment.put(Hog.pathKey(environment, isWindows), path); + } + return builder.start(); + } + + /** + * 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); + // 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 (versionLine.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(versionLine); + } + + 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) { + onLine.accept(line); + } + return process.waitFor(); + } catch (IOException e) { + process.destroy(); + throw e; + } catch (InterruptedException e) { + process.destroy(); + Thread.currentThread().interrupt(); + 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 new file mode 100644 index 000000000..eb798d3c5 --- /dev/null +++ b/posthog-maven-plugin/src/main/java/com/posthog/maven/Utf8Sources.java @@ -0,0 +1,152 @@ +package com.posthog.maven; + +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; +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.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Stream; + +/** + * 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 + // 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) { + 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, 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) + throws IOException { + deleteRecursively(outputDirectory.toPath()); + // 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().normalize(); + 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); + return buildOutput || dir.equals(output) || skippedByHog(dir) + ? FileVisitResult.SKIP_SUBTREE + : FileVisitResult.CONTINUE; + } + + @Override + 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()); + Files.createDirectories(target.getParent()); + if (java) { + Files.write(target, decode(Files.readAllBytes(file), encoding)); + } else { + Files.copy(file, target); + } + return FileVisitResult.CONTINUE; + } + }); + copies.add(copyRoot.toFile()); + } + 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); + } + + // 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) { + 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 { + 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 new file mode 100644 index 000000000..bb1af7d05 --- /dev/null +++ b/posthog-maven-plugin/src/test/java/com/posthog/maven/UploadSourcesMojoTest.java @@ -0,0 +1,1051 @@ +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.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +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 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; +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; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +public class UploadSourcesMojoTest { + @Rule public TemporaryFolder temp = new TemporaryFolder(); + + 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(), "hog-args.txt"); + envFile = new File(temp.getRoot(), "hog-dotenv-file.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 TestMojo(); + mojo.project = project; + mojo.environment = Collections.singletonMap("CI", "true"); + mojo.releaseName = "demo-app"; + mojo.releaseVersion = "1.2.3"; + classes = new File(basedir, "target/classes"); + } + + @Test + public void uploadsExistingSourceRootsAndWritesTheIdIntoTheClasses() 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.hogExecutable = fakeHog(0, true).getAbsolutePath(); + + mojo.execute(); + + assertEquals( + Arrays.asList( + "error-tracking", + "process", + java.getAbsolutePath(), + kotlin.getAbsolutePath(), + "--kind", + "jvm", + "--meta-out", + classes.getAbsolutePath(), + "--release-name", + "demo-app", + "--release-version", + "1.2.3", + "-o", + "text"), + recordedArgs()); + assertEquals( + Collections.singletonList(mojo.dotenvFile.getAbsolutePath()), + Files.readAllLines(envFile.toPath(), StandardCharsets.UTF_8)); + assertTrue(metaProperties().isFile()); + } + + @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.hogExecutable = fakeHog(0, true).getAbsolutePath(); + + mojo.execute(); + + assertEquals( + Arrays.asList(java.getAbsolutePath(), kotlin.getAbsolutePath()), + recordedArgs().subList(2, 4)); + assertEquals("--kind", recordedArgs().get(4)); + } + + @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.hogExecutable = fakeHog(0, true).getAbsolutePath(); + + mojo.execute(); + + assertEquals( + Arrays.asList( + "error-tracking", + "process", + custom.getAbsolutePath(), + "--kind", + "jvm", + "--meta-out", + classes.getAbsolutePath(), + "-o", + "text"), + recordedArgs()); + } + + @Test + public void javaSourcesInAnotherEncodingAreUploadedAsUtf8() throws Exception { + assumeUnix(); + 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); + // 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"); + 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.hogExecutable = fakeHog(0, true).getAbsolutePath(); + + mojo.execute(); + + File copy = new File(basedir, "target/posthog/utf8-sources/0"); + assertEquals(copy.getAbsolutePath(), recordedArgs().get(2)); + 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(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(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + // 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"); + 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(); + + assertTrue(metaProperties().isFile()); + } + + @Test + public void aFailedUploadFailsOnlyARequiredUpload() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(1, false).getAbsolutePath(); + + mojo.execute(); + + assertFalse(metaProperties().exists()); + + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("exited with code 1")); + } + + @Test + public void missingCredentialsFailOnlyARequiredUpload() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(Hog.EXIT_NEEDS_PERSON, false).getAbsolutePath(); + + mojo.execute(); + + assertFalse(metaProperties().exists()); + + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("found no PostHog credentials")); + assertTrue(message, message.contains("HOG_PERSONAL_API_KEY")); + } + + @Test + public void skipsOutsideCiAndDeletesTheStaleFile() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.environment = Collections.singletonMap("CI", "false"); + File stale = staleMetaProperties(); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(stale.exists()); + } + + @Test + public void aRequiredUploadRunsOutsideCi() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(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.hogExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.offline = true; + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(metaProperties().exists()); + } + + @Test + public void skipsALibraryThatAnotherUploadingModuleOfTheBuildDependsOn() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); + mojo.dependents = Collections.singletonList(dependentModule("demo-app", true)); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(metaProperties().exists()); + + mojo.requireUpload = true; + mojo.execute(); + + 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(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.project.setPackaging("pom"); + mojo.hogExecutable = fakeHog(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 skipsWhenHogUploadsNothing() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(0, false).getAbsolutePath(); + + mojo.execute(); + + assertFalse(metaProperties().exists()); + } + + @Test + public void aRequiredUploadFailsTheBuildWhenHogWritesNoFile() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(0, false).getAbsolutePath(); + + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.contains("did not write")); + assertFalse(metaProperties().exists()); + } + + @Test + 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(); + + mojo.execute(); + + assertFalse(stale.exists()); + 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 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 : + 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(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(2, false).getAbsolutePath(); + + mojo.execute(); + + assertFalse(metaProperties().exists()); + + 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(); + + 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(); + mojo.skip = true; + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(stale.exists()); + } + + @Test + public void skipsWhenNoSourceRootExists() throws Exception { + mojo.project.addCompileSourceRoot(new File(basedir, "src/main/java").getAbsolutePath()); + mojo.hogExecutable = fakeHog(0, true).getAbsolutePath(); + + mojo.execute(); + + assertFalse(argsFile.exists()); + assertFalse(metaProperties().exists()); + } + + @Test + 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( + onPath.getAbsolutePath(), + resolve("hog", env(pathDir.getAbsolutePath()), null, false, none())); + } + + @Test + public void resolvePrefersPathThenInstallLocationsThenTheProjectLauncher() throws Exception { + assumeUnix(); + File pathDir = temp.newFolder("bin"); + 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( + 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(), + resolve(null, env(""), project, false, none(), Collections.singletonList(node))); + } + + @Test + public void resolveSkipsAProjectLauncherWithoutNode() throws Exception { + assumeUnix(); + File project = temp.newFolder("app"); + executable(new File(project, "node_modules/.bin/hog")); + + String resolved = resolve(null, env(""), project, false, none(), none()); + + assertEquals(null, resolved); + } + + @Test + public void resolveOnWindowsFindsHogAsCmdDoes() throws Exception { + File exeDir = temp.newFolder("exe"); + File exe = executable(new File(exeDir, "hog.exe")); + File shimDir = temp.newFolder("shim"); + 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(), + 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())); + } + + @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, "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, "hog.cmd")); + File projectExe = executable(new File(projectBin.getParentFile(), binary)); + + assertEquals( + globalExe.getAbsolutePath(), + resolve(null, env(globalPrefix.getAbsolutePath()), null, true, none())); + assertEquals( + projectExe.getAbsolutePath(), + resolve(null, env(projectBin.getAbsolutePath()), null, true, none())); + } + + @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\nb")) { + assertEquals(unsafe, Hog.firstUnsafeForCmd("hog", Arrays.asList("--source", unsafe))); + } + assertEquals( + null, + Hog.firstUnsafeForCmd( + "hog", + Arrays.asList( + "--source", + "C:\\My Projects\\app-1\\src\\main\\java", + "--release-version", + "1.2.3+build.4", + "1.0(5)"))); + } + + @Test + public void launcherPathPrependsOnlyTheDirectoriesPathLacks() throws Exception { + assumeUnix(); + 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 hog = new File(hogDir, "hog").getAbsolutePath(); + String otherDir = temp.newFolder("other-bin").getAbsolutePath(); + + assertEquals( + hogDir.getAbsolutePath() + + File.pathSeparator + + nodeDir.getAbsolutePath() + + File.pathSeparator + + otherDir, + Hog.launcherPath(hog, env(otherDir), temp.getRoot(), false, nodeLocations)); + String both = hogDir.getAbsolutePath() + File.pathSeparator + nodeDir.getAbsolutePath(); + assertEquals( + null, Hog.launcherPath(hog, env(both), temp.getRoot(), false, nodeLocations)); + } + + @Test + public void commandLineWrapsABareNameInCmdOnWindows() { + List args = Arrays.asList("error-tracking", "process"); + + assertEquals( + Arrays.asList("cmd", "/c", "C:\\npm\\hog.cmd", "error-tracking", "process"), + Hog.commandLine("C:\\npm\\hog.cmd", args, true)); + assertEquals( + Arrays.asList("C:\\bin\\hog.exe", "error-tracking", "process"), + Hog.commandLine("C:\\bin\\hog.exe", args, true)); + assertEquals( + Arrays.asList("/bin/hog", "error-tracking", "process"), + 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()); + return dir; + } + + private File metaProperties() { + return new File(classes, UploadSourcesMojo.META_PROPERTIES_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); + } + + /** + * 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( + new File(temp.getRoot(), "fake-hog-" + exitCode + "-" + writeMetaProperties), + fakeHogScript(exitCode, writeMetaProperties)); + } + + 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" + + "printf '%s\\n' \"$HOG_DOTENV_FILE\" > '" + + envFile.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"; + } + + @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 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(); + 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.hogExecutable = fakeHog(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.hogExecutable = fakeHog(0, true).getAbsolutePath(); + + mojo.execute(); + + assertTrue(metaProperties().isFile()); + assertFalse(recordedArgs().contains(typo.getAbsolutePath())); + + String message = requiredUploadFailure().getMessage(); + assertTrue(message, message.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 aRelativeHogExecutableResolvesAgainstTheProject() throws Exception { + assumeUnix(); + mojo.project.addCompileSourceRoot(sourceRoot("src/main/java").getAbsolutePath()); + executable(new File(basedir, "tools/hog"), fakeHogScript(0, true)); + mojo.hogExecutable = "tools/hog"; + + mojo.execute(); + + assertTrue(metaProperties().isFile()); + } + + @Test + public void cmdSplitsAPathWithSpacesOnlyNextToAnotherQuotedArgument() { + String spaced = "C:\\Users\\Jane Doe\\npm\\hog.cmd"; + + assertTrue( + Hog.cmdSplitsPath( + spaced, Arrays.asList("--source", "C:\\Users\\Jane Doe\\src"))); + assertTrue(Hog.cmdSplitsPath(spaced, Arrays.asList("--release-version", ""))); + assertFalse( + Hog.cmdSplitsPath( + spaced, Arrays.asList("error-tracking", "process", "--help"))); + assertFalse( + Hog.cmdSplitsPath( + "C:\\npm\\hog.cmd", + Arrays.asList("--source", "C:\\Users\\Jane Doe\\src"))); + } + + @Test + public void nvmBinariesListTheNewestNodeVersionFirst() throws Exception { + File home = temp.newFolder("home"); + 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, Hog.nvmBinaries(home, "hog").get(0)); + } + + @Test + public void resolveOnWindowsAcceptsAQuotedPathEntry() throws Exception { + assumeUnix(); + File dir = temp.newFolder("Program Files", "posthog"); + File exe = executable(new File(dir, "hog.exe")); + + assertEquals( + exe.getAbsolutePath(), + resolve(null, env("\"" + dir.getAbsolutePath() + "\""), null, true, none())); + } + + @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.hogExecutable}", expressions.get("hogExecutable")); + 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 { + return Files.readAllLines(argsFile.toPath(), StandardCharsets.UTF_8); + } + + 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(), content.getBytes(StandardCharsets.UTF_8)); + assertTrue(file.setExecutable(true)); + return file; + } + + private String resolve( + String configured, + Map environment, + 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, + temp.getRoot(), + workingDirectory, + isWindows, + installLocations, + nodeLocations); + } + + private static List none() { + return Collections.emptyList(); + } + + private static Map env(String path) { + Map env = new HashMap<>(); + env.put("PATH", path); + return env; + } + + private static void assumeUnix() { + Assume.assumeFalse(Hog.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")