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")