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.

feat(cli): add release resolve (#83231)

Aleksander Błaszkiewicz45016b12515b
diff --git a/cli/.sampo/changesets/release-resolve-command.md b/cli/.sampo/changesets/release-resolve-command.md
new file mode 100644
index 000000000000..854c1df5bbf0
--- /dev/null
+++ b/cli/.sampo/changesets/release-resolve-command.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-cli: minor
+---
+
+Add `posthog-cli release resolve`, which prints the id of the release the current build belongs to and creates the release if it doesn't exist yet. Only the id goes to stdout, so `RELEASE_ID=$(posthog-cli release resolve)` works; `--json` prints the whole release. It resolves the same release `sourcemap inject` would, so a bundler plugin that injects the release id into chunks itself lands on the same row. When nothing identifies a release, it prints nothing and exits `0`. `--dry-run` skips it, since resolving a release can create one.
diff --git a/cli/README.md b/cli/README.md
index fe0ba25d9633..d4658c549bc0 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -34,6 +34,7 @@ Commands:
hermes Upload hermes sourcemaps to PostHog
proguard Upload proguard mapping files to PostHog
symbol-sets Upload, download, and manage symbol sets
+ release Look up the release a build belongs to
api Agent-first PostHog API tools
help Print this message or the help of the given subcommand(s)
@@ -43,7 +44,7 @@ Options:
--skip-ssl-verification Skip SSL certificate verification when talking to the PostHog API. Use only with self-signed certificates
--rate-limit <RATE_LIMIT> Set the number of requests per minute for the Posthog API Client [env: POSTHOG_CLIENT_RATE_LIMIT=]
--dotenv-file <PATH> Load PostHog credentials from this dotenv-style file when not present in the process environment. Prefer this over the `--env-file` alias: the npm package runs the binary through a `node` wrapper, and Node's own built-in `--env-file` flag intercepts that spelling. Also settable as `POSTHOG_CLI_DOTENV_FILE`, for callers that control the environment but not the command line (e.g. an Xcode build phase invoking the iOS SDK's upload-symbols.sh) [env: POSTHOG_CLI_DOTENV_FILE=]
- --dry-run[=<DRY_RUN>] Skip artifact processing and upload (sourcemap, dSYM, hermes, proguard) without contacting PostHog or requiring credentials. Intended for CI gates that bundle to catch regressions but must not (or cannot) upload. Not for release builds. Pass it before the subcommand (`posthog-cli --dry-run hermes upload ...`) or set `POSTHOG_CLI_DRY_RUN`. This is distinct from the `exp endpoints` `--dry-run`, which previews endpoint changes [env: POSTHOG_CLI_DRY_RUN=] [default: false] [possible values: true, false]
+ --dry-run[=<DRY_RUN>] Skip artifact processing and upload (sourcemap, dSYM, hermes, proguard, release) without contacting PostHog or requiring credentials. Intended for CI gates that bundle to catch regressions but must not (or cannot) upload. Not for release builds. Pass it before the subcommand (`posthog-cli --dry-run hermes upload ...`) or set `POSTHOG_CLI_DRY_RUN`. This is distinct from the `exp endpoints` `--dry-run`, which previews endpoint changes [env: POSTHOG_CLI_DRY_RUN=] [default: false] [possible values: true, false]
-h, --help Print help
-V, --version Print version
```
@@ -89,10 +90,30 @@ POSTHOG_CLI_SOURCEMAP_UPLOAD_CONCURRENCY=32 npm run build
The CLI flag takes precedence over the environment variable. Both require a value greater than zero. This setting applies only to plain sourcemap uploads; other CLI concurrency remains unchanged.
+## Resolving a release
+
+`posthog-cli release resolve` prints the id of the release the current build belongs to, creating the release if it doesn't exist yet.
+The upload commands do this for you, so reach for it when something else needs the id: a bundler plugin that injects the release into your chunks itself, or a deploy script that wants to record which release it shipped.
+
+```bash
+posthog-cli release resolve --release-name my-app --release-version 1.4.0
+01a0002e-93b5-0000-24cf-fc02638acd46
+```
+
+Only the id goes to stdout, so `RELEASE_ID=$(posthog-cli release resolve)` works.
+Pass `--json` to get the whole release, including its hash id and the version that git or CI metadata filled in.
+
+Both `--release-name` and `--release-version` are read from git or CI metadata when you leave them out.
+When neither the flags nor that metadata identify a release, the command prints nothing (or `null` with `--json`) and exits `0`, so a build can carry on without one.
+A failed lookup exits non-zero instead.
+
+Add `--build` to give a build number its own release: it is packed into the version, so `--release-version 1.4.0 --build 42` resolves to a different release than `--release-version 1.4.0` alone.
+
## Skipping uploads (dry run)
Pass `--dry-run` before the subcommand (`posthog-cli --dry-run hermes upload ...`), or set `POSTHOG_CLI_DRY_RUN=true`, to turn the upload commands — `sourcemap`, `dsym`, `hermes`, and `proguard` — into a no-op.
-The CLI logs that it skipped the upload and exits `0` without contacting PostHog or requiring credentials.
+`release resolve` is skipped too, since resolving a release can create one.
+The CLI logs what it skipped and exits `0` without contacting PostHog or requiring credentials.
(This top-level flag is separate from the `exp endpoints` `--dry-run`, which previews endpoint changes.)
This is meant for CI gates that still want to run the bundling step (to catch Metro/Hermes or sourcemap regressions) but must not — or cannot — upload artifacts, for example pull-request checks that don't have PostHog credentials.
@@ -110,6 +131,7 @@ Commands require different API scopes. Make sure to set these scopes on your per
| `sourcemap` | `error_tracking:write` |
| `symbol-sets` | `error_tracking:write` |
| `dsym` | `error_tracking:write` |
+| `release` | `error_tracking:write` |
| `exp endpoints list/get/pull` | `endpoint:read` |
| `exp endpoints push` | `endpoint:write`, `insight_variable:write` |
| `exp endpoints run` | `query:read` |
diff --git a/cli/src/api/releases.rs b/cli/src/api/releases.rs
index 780e19ba3829..9320155365a7 100644
--- a/cli/src/api/releases.rs
+++ b/cli/src/api/releases.rs
@@ -14,7 +14,7 @@ use crate::{
const RELEASE_HASH_IN_USE_ERROR_CODE: &str = "release_hash_in_use";
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Release {
pub id: Uuid,
pub hash_id: String,
diff --git a/cli/src/commands.rs b/cli/src/commands.rs
index bc643ab9b884..b110069a7082 100644
--- a/cli/src/commands.rs
+++ b/cli/src/commands.rs
@@ -15,6 +15,7 @@ use crate::{
set_telemetry_env_id_from_environment, INVOCATION_CONTEXT,
},
proguard::ProguardSubcommand,
+ release::ReleaseSubcommand,
sourcemaps::{hermes::HermesSubcommand, plain::SourcemapCommand},
};
@@ -51,11 +52,11 @@ pub struct Cli {
)]
env_file: Option<PathBuf>,
- /// Skip artifact processing and upload (sourcemap, dSYM, hermes, proguard) without contacting
- /// PostHog or requiring credentials. Intended for CI gates that bundle to catch regressions but
- /// must not (or cannot) upload. Not for release builds. Pass it before the subcommand
- /// (`posthog-cli --dry-run hermes upload ...`) or set `POSTHOG_CLI_DRY_RUN`. This is distinct
- /// from the `exp endpoints` `--dry-run`, which previews endpoint changes.
+ /// Skip artifact processing and upload (sourcemap, dSYM, hermes, proguard, release) without
+ /// contacting PostHog or requiring credentials. Intended for CI gates that bundle to catch
+ /// regressions but must not (or cannot) upload. Not for release builds. Pass it before the
+ /// subcommand (`posthog-cli --dry-run hermes upload ...`) or set `POSTHOG_CLI_DRY_RUN`. This is
+ /// distinct from the `exp endpoints` `--dry-run`, which previews endpoint changes.
#[arg(
long,
env = "POSTHOG_CLI_DRY_RUN",
@@ -71,8 +72,9 @@ pub struct Cli {
command: Commands,
}
-/// Commands that `--dry-run` turns into a no-op. Returns the artifact kind, for logging, or `None`
-/// for commands that don't upload anything (login, queries, schema sync, symbol-set downloads).
+/// Commands that `--dry-run` turns into a no-op. Returns what gets skipped, for logging, or `None`
+/// for commands that don't write anything to PostHog (login, queries, schema sync, symbol-set
+/// downloads).
fn dry_run_skipped_command(command: &Commands) -> Option<&'static str> {
match command {
Commands::Sourcemap { .. } => Some("sourcemap"),
@@ -82,6 +84,9 @@ fn dry_run_skipped_command(command: &Commands) -> Option<&'static str> {
} => Some("native debug symbols"),
Commands::Hermes { .. } => Some("hermes sourcemap"),
Commands::Proguard { .. } => Some("proguard"),
+ // Resolving a release creates the row when it doesn't exist yet, which a dry run must not
+ // do. The command prints nothing, so a caller injecting the id ships a bundle without one.
+ Commands::Release { .. } => Some("release"),
Commands::Exp { cmd } => match cmd {
ExpCommand::Hermes { .. } => Some("hermes sourcemap"),
ExpCommand::Proguard { .. } => Some("proguard"),
@@ -161,6 +166,12 @@ pub enum Commands {
cmd: SymbolSetsSubcommand,
},
+ #[command(about = "Look up the release a build belongs to")]
+ Release {
+ #[command(subcommand)]
+ cmd: ReleaseSubcommand,
+ },
+
#[command(
about = "Agent-first PostHog API tools",
long_about = "Agent-first PostHog API tools.\n\n\
@@ -279,6 +290,9 @@ impl Commands {
SymbolSetsSubcommand::Download(_) => "symbolset_download",
SymbolSetsSubcommand::Extract(_) => "symbolset_extract",
},
+ Commands::Release { cmd } => match cmd {
+ ReleaseSubcommand::Resolve(_) => "release_resolve",
+ },
Commands::Api { .. } => "api",
}
}
@@ -360,7 +374,7 @@ impl Cli {
if self.dry_run {
if let Some(kind) = dry_run_skipped_command(&self.command) {
warn!(
- "Dry run enabled (--dry-run / POSTHOG_CLI_DRY_RUN): skipping {kind} upload. \
+ "Dry run enabled (--dry-run / POSTHOG_CLI_DRY_RUN): skipping the {kind} step. \
Nothing was sent to PostHog and no credentials were used. \
Do not use --dry-run for release builds."
);
@@ -443,6 +457,11 @@ impl Cli {
crate::download::extract(&args)?;
}
},
+ Commands::Release { cmd } => match cmd {
+ ReleaseSubcommand::Resolve(args) => {
+ crate::release::resolve(&args)?;
+ }
+ },
Commands::Api { args } => {
// The proxy often runs without stored credentials (env-var auth,
// metadata subcommands), so attach the project id from the
@@ -593,6 +612,8 @@ mod tests {
&["proguard", "upload", "--path", "p", "--map-id", "m"],
Some("proguard"),
),
+ // resolving a release creates the row, so a dry run must not reach it
+ (&["release", "resolve"], Some("release")),
// hidden `exp` aliases must skip too
(&["exp", "dsym", "upload", "--directory", "d"], Some("dSYM")),
(
diff --git a/cli/src/lib.rs b/cli/src/lib.rs
index 85eb9eee8a2f..39df09b2677d 100644
--- a/cli/src/lib.rs
+++ b/cli/src/lib.rs
@@ -9,6 +9,7 @@ pub mod experimental;
pub mod invocation_context;
pub mod login;
pub mod proguard;
+pub mod release;
pub mod sourcemaps;
pub mod utils;
diff --git a/cli/src/release/mod.rs b/cli/src/release/mod.rs
new file mode 100644
index 000000000000..19c70201629d
--- /dev/null
+++ b/cli/src/release/mod.rs
@@ -0,0 +1,115 @@
+use anyhow::Result;
+use tracing::warn;
+
+use crate::{
+ api::releases::Release,
+ invocation_context::context,
+ sourcemaps::{args::ReleaseArgs, inject::resolve_release},
+};
+
+#[derive(clap::Subcommand)]
+pub enum ReleaseSubcommand {
+ /// Print the id of the release for this build, creating the release if it doesn't exist yet
+ Resolve(ResolveArgs),
+}
+
+#[derive(clap::Args)]
+pub struct ResolveArgs {
+ /// The name of the project this release belongs to. Read from git or CI metadata when omitted.
+ #[arg(long = "release-name")]
+ pub name: Option<String>,
+
+ /// The version of the project: a version number, a semantic version, or a git commit hash.
+ /// Read from git or CI metadata when omitted.
+ #[arg(long = "release-version")]
+ pub version: Option<String>,
+
+ /// The build number (e.g. 42, CFBundleVersion on iOS, versionCode on Android). Packed into the
+ /// version, so each build number is a release of its own.
+ #[arg(long)]
+ pub build: Option<String>,
+
+ /// Print the whole release as JSON instead of only its id
+ #[arg(long, default_value_t = false)]
+ pub json: bool,
+}
+
+impl From<&ResolveArgs> for ReleaseArgs {
+ fn from(args: &ResolveArgs) -> Self {
+ Self {
+ name: args.name.clone(),
+ version: args.version.clone(),
+ build: args.build.clone(),
+ // Only consulted when a symbol set upload is rejected over its release, and this
+ // command uploads nothing.
+ skip_release_on_fail: true,
+ }
+ }
+}
+
+pub fn resolve(args: &ResolveArgs) -> Result<()> {
+ context().capture_command_invoked("release_resolve");
+
+ let Some(release) = resolve_release(args.into())? else {
+ // Exiting zero keeps "this build identifies no release" distinct from a lookup that
+ // failed, which exits non-zero. Build tools depend on the difference: the first case
+ // still ships a bundle, only without a release id injected into it.
+ warn!(
+ "No release could be resolved. Pass --release-name and --release-version, or run \
+ this from a git repository or a supported CI environment."
+ );
+ if args.json {
+ // Empty stdout is not valid JSON, so emit `null` for a --json consumer to parse.
+ println!("null");
+ }
+ return Ok(());
+ };
+
+ println!("{}", render_release(&release, args.json)?);
+ Ok(())
+}
+
+/// Render the release for stdout: the bare id by default, so `$(posthog-cli release resolve)` is
+/// the id itself, and the whole row under `--json` for callers that also want the hash id or the
+/// version that git and CI metadata filled in.
+fn render_release(release: &Release, json: bool) -> Result<String> {
+ if json {
+ return Ok(serde_json::to_string_pretty(release)?);
+ }
+ Ok(release.id.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const ID: &str = "0e9b3c7a-5d1f-42a8-b6c4-e2d0f8a17593";
+
+ fn release() -> Release {
+ Release {
+ id: ID.parse().expect("test id is a uuid"),
+ hash_id: "e3b0c44298fc1c14".to_string(),
+ version: "1.0.0+42".to_string(),
+ project: "my-app".to_string(),
+ }
+ }
+
+ #[test]
+ fn plain_output_is_the_id_alone() {
+ // Callers pipe stdout straight into an injected snippet, so a label or any other
+ // decoration around the id would end up in their bundle.
+ assert_eq!(render_release(&release(), false).unwrap(), ID);
+ }
+
+ #[test]
+ fn json_output_keeps_the_field_names_callers_read() {
+ let rendered = render_release(&release(), true).unwrap();
+
+ let parsed: serde_json::Value =
+ serde_json::from_str(&rendered).expect("rendered json parses");
+ assert_eq!(parsed["id"], ID);
+ assert_eq!(parsed["hash_id"], "e3b0c44298fc1c14");
+ assert_eq!(parsed["version"], "1.0.0+42");
+ assert_eq!(parsed["project"], "my-app");
+ }
+}
diff --git a/cli/src/sourcemaps/inject.rs b/cli/src/sourcemaps/inject.rs
index 939f6504371a..40217e77340b 100644
--- a/cli/src/sourcemaps/inject.rs
+++ b/cli/src/sourcemaps/inject.rs
@@ -189,7 +189,16 @@ fn resolve_release_id(
if let Some(r) = existing_release {
return Ok(Some(r.id.to_string()));
}
+ Ok(resolve_release(release)?.map(|r| r.id.to_string()))
+}
+/// Fetch or create the release identified by `release`, filling in whichever of name and version
+/// the flags left out from git and CI metadata. Returns `None` when neither source identifies a
+/// release.
+///
+/// Shared with the `release resolve` command, so a build tool that injects the release id itself
+/// lands on the same row `sourcemap inject --release-mode=event` would have injected.
+pub fn resolve_release(release: ReleaseArgs) -> Result<Option<Release>> {
let cwd = std::env::current_dir()?;
let release_args_were_provided =
release.name.is_some() || release.version.is_some() || release.build.is_some();
@@ -198,7 +207,7 @@ fn resolve_release_id(
if !builder.can_create() {
return Ok(None);
}
- Ok(Some(builder.fetch_or_create()?.id.to_string()))
+ Ok(Some(builder.fetch_or_create()?))
}
pub fn get_release_for_maps<'a>(