Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cli): package api cli bundle in releases (#64014)

Chris Volzerace786f67bd4
diff --git a/.github/workflows/release-cli.yml b/.github/workflows/release-cli.yml
index dabae0adaf0e..9a2fb501696b 100644
--- a/.github/workflows/release-cli.yml
+++ b/.github/workflows/release-cli.yml
@@ -423,11 +423,40 @@ jobs:
- name: Install dependencies
run: |
${{ matrix.packages_install }}
+ - name: Setup pnpm
+ uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
+ - name: Setup Node.js
+ uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
+ with:
+ node-version-file: .nvmrc
+ cache: 'pnpm'
+ - name: Install API CLI dependencies
+ run: pnpm --filter '@posthog/mcp...' install --frozen-lockfile
+ - name: Build API CLI release bundle
+ run: pnpm --dir services/mcp run build:cli:release
+ - name: Verify API CLI release bundle
+ run: |
+ node -e "const { existsSync, statSync } = require('node:fs'); const path = 'cli/lib/posthog-api-cli.mjs'; if (!existsSync(path) || statSync(path).size <= 0) { console.error('::error::API CLI bundle is missing or empty: ' + path); process.exit(1); }"
- name: Build artifacts
run: |
# Actually do builds and make zips and whatnot
dist build ${{ needs.plan-release.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json
echo "dist ran successfully"
+ - name: Verify API CLI bundle in local artifacts
+ shell: bash
+ run: |
+ shopt -s nullglob
+ bundles=(target/distrib/posthog-cli-*/lib/posthog-api-cli.mjs)
+ if [ "${#bundles[@]}" -eq 0 ]; then
+ echo "::error::No API CLI bundle found in cargo-dist local artifacts"
+ exit 1
+ fi
+ for bundle in "${bundles[@]}"; do
+ if [ ! -s "$bundle" ]; then
+ echo "::error::API CLI bundle is empty: $bundle"
+ exit 1
+ fi
+ done
- id: cargo-dist
name: Post-build
# We force bash here just because github makes it really hard to get values up
@@ -480,6 +509,20 @@ jobs:
pattern: artifacts-*
path: target/distrib/
merge-multiple: true
+ - name: Setup pnpm
+ uses: pnpm/action-setup@0e279bb959325dab635dd2c09392533439d90093 # v6.0.8
+ - name: Setup Node.js
+ uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
+ with:
+ node-version-file: .nvmrc
+ cache: 'pnpm'
+ - name: Install API CLI dependencies
+ run: pnpm --filter '@posthog/mcp...' install --frozen-lockfile
+ - name: Build API CLI release bundle
+ run: pnpm --dir services/mcp run build:cli:release
+ - name: Verify API CLI release bundle
+ run: |
+ node -e "const { existsSync, statSync } = require('node:fs'); const path = 'cli/lib/posthog-api-cli.mjs'; if (!existsSync(path) || statSync(path).size <= 0) { console.error('::error::API CLI bundle is missing or empty: ' + path); process.exit(1); }"
- id: cargo-dist
shell: bash
run: |
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 62adcbc876ea..8a3d65cd5fb8 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -165,12 +165,28 @@ jobs:
- name: Build API CLI release bundle
run: pnpm --dir services/mcp run build:cli:release
- name: Verify API CLI release bundle
- run: node -e "const { statSync } = require('node:fs'); if (statSync('cli/lib/posthog-api-cli.mjs').size <= 0) process.exit(1)"
+ run: |
+ node -e "const { existsSync, statSync } = require('node:fs'); const path = 'cli/lib/posthog-api-cli.mjs'; if (!existsSync(path) || statSync(path).size <= 0) { console.error('::error::API CLI bundle is missing or empty: ' + path); process.exit(1); }"
- name: Build artifacts
run: |
# Actually do builds and make zips and whatnot
dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json
echo "dist ran successfully"
+ - name: Verify API CLI bundle in local artifacts
+ shell: bash
+ run: |
+ shopt -s nullglob
+ bundles=(target/distrib/posthog-cli-*/lib/posthog-api-cli.mjs)
+ if [ "${#bundles[@]}" -eq 0 ]; then
+ echo "::error::No API CLI bundle found in cargo-dist local artifacts"
+ exit 1
+ fi
+ for bundle in "${bundles[@]}"; do
+ if [ ! -s "$bundle" ]; then
+ echo "::error::API CLI bundle is empty: $bundle"
+ exit 1
+ fi
+ done
- id: cargo-dist
name: Post-build
# We force bash here just because github makes it really hard to get values up
@@ -232,7 +248,8 @@ jobs:
- name: Build API CLI release bundle
run: pnpm --dir services/mcp run build:cli:release
- name: Verify API CLI release bundle
- run: node -e "const { statSync } = require('node:fs'); if (statSync('cli/lib/posthog-api-cli.mjs').size <= 0) process.exit(1)"
+ run: |
+ node -e "const { existsSync, statSync } = require('node:fs'); const path = 'cli/lib/posthog-api-cli.mjs'; if (!existsSync(path) || statSync(path).size <= 0) { console.error('::error::API CLI bundle is missing or empty: ' + path); process.exit(1); }"
- id: cargo-dist
shell: bash
run: |
diff --git a/cli/.sampo/changesets/steady-api-bundle.md b/cli/.sampo/changesets/steady-api-bundle.md
new file mode 100644
index 000000000000..86db187197ca
--- /dev/null
+++ b/cli/.sampo/changesets/steady-api-bundle.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-cli: patch
+---
+
+Fix API CLI bundle packaging and lookup
diff --git a/cli/CONTRIBUTING.md b/cli/CONTRIBUTING.md
index fccac3f83205..76cc7d9f3b8a 100644
--- a/cli/CONTRIBUTING.md
+++ b/cli/CONTRIBUTING.md
@@ -36,6 +36,19 @@ To reproduce that release bundle locally, run:
pnpm --dir services/mcp run build:cli:release
```
+To smoke-test the packaged CLI before cutting a release, build the same cargo-dist archive and installer locally,
+then run both the unpacked archive and the generated shell installer from a temporary home directory:
+
+```bash
+flox activate -- bash -c 'cargo install cargo-dist --version 0.32.0 --locked'
+DIST_BIN="$HOME/.cargo/bin/dist" flox activate -- bash -c './cli/scripts/smoke-release-artifact.sh'
+```
+
+If you are testing uncommitted local changes, set `CLI_RELEASE_SMOKE_ALLOW_DIRTY=1` for the second command.
+The smoke test verifies that the archive includes `lib/posthog-api-cli.mjs`, that `posthog-cli api --agent-help` works from the unpacked artifact, and that the generated shell installer produces a working `posthog-cli api` install without relying on a PostHog repo checkout.
+It serves `target/distrib` on `127.0.0.1:8765` while testing the installer; set `CLI_RELEASE_SMOKE_PORT` if that port is already in use.
+It does not replace any `posthog-cli` already on your `PATH`; to manually test the built artifact, run `target/distrib/posthog-cli-$(rustc -vV | sed -n 's/^host: //p')/posthog-cli api --agent-help`.
+
We release semi-regularly, as new features are added. If a release breaks your CI or workflow, please open an issue on GitHub, and tag one or all of the crate authors
## Running a local build
diff --git a/cli/build.rs b/cli/build.rs
index 133b6324dd2b..f9555023608e 100644
--- a/cli/build.rs
+++ b/cli/build.rs
@@ -1,9 +1,35 @@
+use std::env;
+use std::fs;
+use std::path::PathBuf;
+
// Debug token, used to get metrics for debug builds - team 89529
const DEBUG_POSTHOG_API_TOKEN: &str = "phc_raG2H9V246hkNZk6K89DZGG98qQyPrKKlicifGlpOXA";
+const API_CLI_BUNDLE: &str = "lib/posthog-api-cli.mjs";
+
+fn write_api_cli_bundle_include() {
+ let manifest_dir =
+ PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"));
+ let bundle_path = manifest_dir.join(API_CLI_BUNDLE);
+ let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is set by cargo"));
+ let out_path = out_dir.join("api_cli_bundle.rs");
+
+ println!("cargo:rerun-if-changed={}", bundle_path.display());
+
+ let contents = if bundle_path.is_file() {
+ let bundle_path_literal = format!("{bundle_path:?}");
+ format!("const EMBEDDED_API_CLI_BUNDLE: Option<&[u8]> = Some(include_bytes!({bundle_path_literal}));\n")
+ } else {
+ "const EMBEDDED_API_CLI_BUNDLE: Option<&[u8]> = None;\n".to_string()
+ };
+
+ fs::write(out_path, contents).expect("write embedded API CLI bundle include");
+}
// This build file just sets this token for debug builds - for production builds, we use the token from our CI's secrets
pub fn main() {
- let profile = std::env::var("PROFILE").expect("Profile variable is set by cargo");
+ write_api_cli_bundle_include();
+
+ let profile = env::var("PROFILE").expect("Profile variable is set by cargo");
if profile == "debug" {
println!("cargo:rustc-env=POSTHOG_API_TOKEN={DEBUG_POSTHOG_API_TOKEN}");
} else {
diff --git a/cli/scripts/smoke-release-artifact.sh b/cli/scripts/smoke-release-artifact.sh
new file mode 100755
index 000000000000..2e30e9aa9fb7
--- /dev/null
+++ b/cli/scripts/smoke-release-artifact.sh
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+repo_root="$(git rev-parse --show-toplevel)"
+target="${CLI_RELEASE_SMOKE_TARGET:-$(rustc -vV | sed -n 's/^host: //p')}"
+dist_bin="${DIST_BIN:-dist}"
+local_manifest="${CLI_RELEASE_SMOKE_MANIFEST:-/tmp/posthog-cli-local-dist-manifest.json}"
+global_manifest="${CLI_RELEASE_SMOKE_GLOBAL_MANIFEST:-/tmp/posthog-cli-local-dist-global-manifest.json}"
+python_bin="${PYTHON:-python3}"
+server_port="${CLI_RELEASE_SMOKE_PORT:-8765}"
+
+if ! command -v "$dist_bin" >/dev/null 2>&1; then
+ cat >&2 <<'EOF'
+cargo-dist is required for the release artifact smoke test.
+
+Install the pinned version from dist-workspace.toml, for example:
+
+ cargo install cargo-dist --version 0.32.0 --locked
+
+Or set DIST_BIN=/path/to/dist.
+EOF
+ exit 1
+fi
+
+if ! command -v "$python_bin" >/dev/null 2>&1; then
+ echo "python3 is required to serve local cargo-dist artifacts during the smoke test." >&2
+ exit 1
+fi
+
+if ! command -v curl >/dev/null 2>&1; then
+ echo "curl is required to check the local artifact server during the smoke test." >&2
+ exit 1
+fi
+
+echo "Building API CLI release bundle..."
+pnpm --dir "$repo_root/services/mcp" run build:cli:release
+test -s "$repo_root/cli/lib/posthog-api-cli.mjs"
+
+common_dist_args=()
+
+if [[ "${CLI_RELEASE_SMOKE_ALLOW_DIRTY:-}" == "1" ]]; then
+ common_dist_args+=(--allow-dirty)
+fi
+
+if [[ -n "${CLI_RELEASE_SMOKE_TAG:-}" ]]; then
+ common_dist_args+=(--tag "$CLI_RELEASE_SMOKE_TAG")
+fi
+
+local_dist_args=(
+ build
+ --artifacts=local
+ --target "$target"
+ --print=linkage
+ --output-format=json
+ "${common_dist_args[@]}"
+)
+
+echo "Building cargo-dist local artifact for $target..."
+"$dist_bin" "${local_dist_args[@]}" > "$local_manifest"
+
+archive="$repo_root/target/distrib/posthog-cli-$target.tar.gz"
+if [[ ! -f "$archive" ]]; then
+ echo "Expected archive not found: $archive" >&2
+ exit 1
+fi
+
+echo "Checking archive contains the API CLI bundle..."
+tar -tzf "$archive" | grep -qx "posthog-cli-$target/lib/posthog-api-cli.mjs"
+
+tmpdir="$(mktemp -d)"
+server_pid=""
+cleanup() {
+ if [[ -n "$server_pid" ]]; then
+ kill "$server_pid" >/dev/null 2>&1 || true
+ wait "$server_pid" >/dev/null 2>&1 || true
+ fi
+ rm -rf "$tmpdir"
+}
+trap cleanup EXIT
+mkdir -p "$tmpdir/home" "$tmpdir/unpack"
+
+tar -xzf "$archive" --strip-components 1 -C "$tmpdir/unpack"
+test -s "$tmpdir/unpack/lib/posthog-api-cli.mjs"
+
+echo "Running packaged posthog-cli api --agent-help..."
+if ! HOME="$tmpdir/home" "$tmpdir/unpack/posthog-cli" api --agent-help > "$tmpdir/agent-help.txt" 2> "$tmpdir/agent-help.err"; then
+ cat "$tmpdir/agent-help.err" >&2
+ exit 1
+fi
+grep -q "# PostHog API guide for agents" "$tmpdir/agent-help.txt"
+
+global_dist_args=(
+ build
+ --artifacts=global
+ --output-format=json
+ "${common_dist_args[@]}"
+)
+
+echo "Building cargo-dist installer artifacts..."
+"$dist_bin" "${global_dist_args[@]}" > "$global_manifest"
+
+installer="$repo_root/target/distrib/posthog-cli-installer.sh"
+if [[ ! -s "$installer" ]]; then
+ echo "Expected shell installer not found: $installer" >&2
+ exit 1
+fi
+
+echo "Serving local cargo-dist artifacts on http://127.0.0.1:$server_port..."
+"$python_bin" -m http.server "$server_port" --bind 127.0.0.1 --directory "$repo_root/target/distrib" > "$tmpdir/http-server.log" 2>&1 &
+server_pid=$!
+server_url="http://127.0.0.1:$server_port"
+server_ready=0
+for _ in {1..50}; do
+ if curl -fsSI "$server_url/$(basename "$archive")" >/dev/null 2>&1; then
+ server_ready=1
+ break
+ fi
+ if ! kill -0 "$server_pid" >/dev/null 2>&1; then
+ cat "$tmpdir/http-server.log" >&2
+ exit 1
+ fi
+ sleep 0.1
+done
+if [[ "$server_ready" != "1" ]]; then
+ cat "$tmpdir/http-server.log" >&2
+ echo "Timed out waiting for local artifact server. Set CLI_RELEASE_SMOKE_PORT to try a different port." >&2
+ exit 1
+fi
+
+mkdir -p "$tmpdir/installed-home" "$tmpdir/installed"
+
+echo "Running generated shell installer from local artifacts..."
+if ! HOME="$tmpdir/installed-home" \
+ INSTALLER_DOWNLOAD_URL="$server_url" \
+ CARGO_DIST_FORCE_INSTALL_DIR="$tmpdir/installed" \
+ INSTALLER_NO_MODIFY_PATH=1 \
+ POSTHOG_CLI_DISABLE_UPDATE=1 \
+ sh "$installer" --no-modify-path > "$tmpdir/installer.out" 2> "$tmpdir/installer.err"; then
+ cat "$tmpdir/installer.out" >&2
+ cat "$tmpdir/installer.err" >&2
+ exit 1
+fi
+
+test -x "$tmpdir/installed/posthog-cli"
+
+echo "Running installed posthog-cli api --agent-help..."
+if ! HOME="$tmpdir/installed-home" "$tmpdir/installed/posthog-cli" api --agent-help > "$tmpdir/installed-agent-help.txt" 2> "$tmpdir/installed-agent-help.err"; then
+ cat "$tmpdir/installed-agent-help.err" >&2
+ exit 1
+fi
+grep -q "# PostHog API guide for agents" "$tmpdir/installed-agent-help.txt"
+
+if [[ ! -s "$tmpdir/installed/lib/posthog-api-cli.mjs" ]]; then
+ shopt -s nullglob
+ materialized_bundles=("$tmpdir/installed-home/.posthog/api-cli"/*/posthog-api-cli.mjs)
+ if [[ "${#materialized_bundles[@]}" -eq 0 ]]; then
+ echo "Installed CLI worked, but no adjacent or materialized API CLI bundle was found." >&2
+ exit 1
+ fi
+fi
+
+echo "Release artifact smoke test passed: $archive"
+echo "Packaged CLI available at: $repo_root/target/distrib/posthog-cli-$target/posthog-cli"
+echo "Note: this smoke test does not replace any posthog-cli already on your PATH."
diff --git a/cli/src/api_proxy.rs b/cli/src/api_proxy.rs
index 12c1689aa835..bffd3eea86b9 100644
--- a/cli/src/api_proxy.rs
+++ b/cli/src/api_proxy.rs
@@ -1,15 +1,18 @@
-use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
+use std::{env, fs};
use anyhow::{bail, Context, Result};
use crate::error::CapturedError;
use crate::invocation_context::InvocationContext;
+use crate::utils::homedir::posthog_home_dir_if_available;
const API_CLI_BUNDLE: &str = "posthog-api-cli.mjs";
const ANALYTICS_HOST: &str = "https://us.i.posthog.com";
+include!(concat!(env!("OUT_DIR"), "/api_cli_bundle.rs"));
+
fn canonicalize_file(path: &Path) -> Option<PathBuf> {
let resolved = path.canonicalize().ok()?;
if resolved.is_file() {
@@ -20,7 +23,41 @@ fn canonicalize_file(path: &Path) -> Option<PathBuf> {
}
fn default_install_dir() -> Option<PathBuf> {
- Some(dirs::home_dir()?.join(".posthog"))
+ posthog_home_dir_if_available()
+}
+
+fn embedded_bundle_path(install_dir: &Path) -> PathBuf {
+ install_dir
+ .join("api-cli")
+ .join(env!("CARGO_PKG_VERSION"))
+ .join(API_CLI_BUNDLE)
+}
+
+fn materialize_embedded_script(
+ bundle: Option<&[u8]>,
+ install_dir: Option<&Path>,
+) -> Option<PathBuf> {
+ let bundle = bundle?;
+ let path = embedded_bundle_path(install_dir?);
+ fs::create_dir_all(path.parent()?).ok()?;
+ fs::write(&path, bundle).ok()?;
+ canonicalize_file(&path)
+}
+
+fn legacy_bundle_candidates(install_dir: Option<&Path>, development_dir: &Path) -> Vec<PathBuf> {
+ let mut candidates = Vec::new();
+
+ if let Some(install_dir) = install_dir {
+ candidates.extend([
+ install_dir.join("lib").join(API_CLI_BUNDLE),
+ install_dir.join("cli/lib").join(API_CLI_BUNDLE),
+ install_dir.join("api-cli").join(API_CLI_BUNDLE),
+ install_dir.join(API_CLI_BUNDLE),
+ ]);
+ }
+
+ candidates.push(development_dir.join("lib").join(API_CLI_BUNDLE));
+ candidates
}
fn find_script() -> Result<PathBuf> {
@@ -44,24 +81,20 @@ fn find_script() -> Result<PathBuf> {
return Ok(resolved);
}
- if let Some(install_dir) = default_install_dir() {
- for candidate in [
- install_dir.join("lib").join(API_CLI_BUNDLE),
- install_dir.join("cli/lib").join(API_CLI_BUNDLE),
- install_dir.join("api-cli").join(API_CLI_BUNDLE),
- install_dir.join(API_CLI_BUNDLE),
- ] {
- if let Some(resolved) = canonicalize_file(&candidate) {
- return Ok(resolved);
- }
- }
+ let install_dir = default_install_dir();
+ if let Some(resolved) =
+ materialize_embedded_script(EMBEDDED_API_CLI_BUNDLE, install_dir.as_deref())
+ {
+ return Ok(resolved);
}
- let development_bundle = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
- .join("lib")
- .join(API_CLI_BUNDLE);
- if let Some(resolved) = canonicalize_file(&development_bundle) {
- return Ok(resolved);
+ for candidate in legacy_bundle_candidates(
+ install_dir.as_deref(),
+ Path::new(env!("CARGO_MANIFEST_DIR")),
+ ) {
+ if let Some(resolved) = canonicalize_file(&candidate) {
+ return Ok(resolved);
+ }
}
bail!(
@@ -145,3 +178,128 @@ pub fn run(
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use std::ffi::OsString;
+ use std::fs;
+ use std::sync::Mutex;
+
+ use super::*;
+
+ static POSTHOG_HOME_ENV_LOCK: Mutex<()> = Mutex::new(());
+
+ struct EnvVarGuard {
+ name: &'static str,
+ previous: Option<OsString>,
+ }
+
+ impl EnvVarGuard {
+ fn set(name: &'static str, value: &Path) -> Self {
+ let previous = env::var_os(name);
+ env::set_var(name, value);
+ Self { name, previous }
+ }
+ }
+
+ impl Drop for EnvVarGuard {
+ fn drop(&mut self) {
+ match &self.previous {
+ Some(value) => env::set_var(self.name, value),
+ None => env::remove_var(self.name),
+ }
+ }
+ }
+
+ #[test]
+ fn legacy_bundle_candidates_include_install_and_development_paths() {
+ let install_dir = PathBuf::from("home").join(".posthog");
+ let development_dir = PathBuf::from("repo").join("cli");
+
+ let candidates = legacy_bundle_candidates(Some(&install_dir), &development_dir);
+
+ assert_eq!(candidates[0], install_dir.join("lib").join(API_CLI_BUNDLE));
+ assert_eq!(
+ candidates[1],
+ install_dir.join("cli/lib").join(API_CLI_BUNDLE)
+ );
+ assert_eq!(
+ candidates.last(),
+ Some(&development_dir.join("lib").join(API_CLI_BUNDLE))
+ );
+ }
+
+ #[test]
+ fn canonicalize_file_rejects_directories() {
+ let temp_dir = tempfile::tempdir().expect("create temp dir");
+
+ assert_eq!(canonicalize_file(temp_dir.path()), None);
+ }
+
+ #[test]
+ fn default_install_dir_honors_posthog_home() {
+ let _lock = POSTHOG_HOME_ENV_LOCK.lock().expect("lock POSTHOG_HOME");
+ let temp_dir = tempfile::tempdir().expect("create temp dir");
+ let _guard = EnvVarGuard::set("POSTHOG_HOME", temp_dir.path());
+
+ assert_eq!(default_install_dir(), Some(temp_dir.path().to_path_buf()));
+ }
+
+ #[test]
+ fn embedded_bundle_is_materialized_into_a_versioned_install_dir() {
+ let temp_dir = tempfile::tempdir().expect("create temp dir");
+
+ let resolved = materialize_embedded_script(Some(b"embedded bundle"), Some(temp_dir.path()))
+ .expect("materialize embedded bundle");
+
+ assert_eq!(
+ resolved,
+ temp_dir
+ .path()
+ .join("api-cli")
+ .join(env!("CARGO_PKG_VERSION"))
+ .join(API_CLI_BUNDLE)
+ .canonicalize()
+ .expect("canonicalize materialized bundle")
+ );
+ assert_eq!(
+ fs::read(resolved).expect("read materialized bundle"),
+ b"embedded bundle"
+ );
+ }
+
+ #[test]
+ fn embedded_bundle_is_ignored_when_it_was_not_built() {
+ let temp_dir = tempfile::tempdir().expect("create temp dir");
+
+ assert_eq!(
+ materialize_embedded_script(None, Some(temp_dir.path())),
+ None
+ );
+ }
+
+ #[test]
+ fn materialized_embedded_bundle_is_used_before_legacy_install() {
+ let temp_dir = tempfile::tempdir().expect("create temp dir");
+ let install_dir = temp_dir.path().join("home").join(".posthog");
+ let legacy_bundle = install_dir.join("lib").join(API_CLI_BUNDLE);
+
+ fs::create_dir_all(legacy_bundle.parent().expect("legacy parent"))
+ .expect("create legacy lib dir");
+ fs::write(&legacy_bundle, "legacy").expect("write legacy bundle");
+
+ let resolved = materialize_embedded_script(Some(b"embedded bundle"), Some(&install_dir))
+ .expect("materialize embedded bundle");
+
+ assert_eq!(
+ resolved,
+ embedded_bundle_path(&install_dir)
+ .canonicalize()
+ .expect("canonicalize embedded bundle")
+ );
+ assert_eq!(
+ fs::read(resolved).expect("read materialized bundle"),
+ b"embedded bundle"
+ );
+ }
+}
diff --git a/cli/src/utils/homedir.rs b/cli/src/utils/homedir.rs
index a00cedce9401..dfc59e5b40c7 100644
--- a/cli/src/utils/homedir.rs
+++ b/cli/src/utils/homedir.rs
@@ -3,15 +3,18 @@ use std::path::PathBuf;
use anyhow::{Context, Error};
// IF `POSTHOG_HOME` is set, use that, otherwise use $HOME/.posthog
-pub fn posthog_home_dir() -> PathBuf {
- match std::env::var("POSTHOG_HOME") {
- Ok(home) => PathBuf::from(home),
- Err(_) => {
- let mut home = dirs::home_dir().expect("Could not find home directory");
- home.push(".posthog");
- home
- }
+pub fn posthog_home_dir_if_available() -> Option<PathBuf> {
+ if let Some(home) = std::env::var_os("POSTHOG_HOME") {
+ return Some(PathBuf::from(home));
}
+
+ let mut home = dirs::home_dir()?;
+ home.push(".posthog");
+ Some(home)
+}
+
+pub fn posthog_home_dir() -> PathBuf {
+ posthog_home_dir_if_available().expect("Could not find home directory")
}
pub fn ensure_homedir_exists() -> Result<(), Error> {