: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cli): add --dry-run flag to skip artifact uploads (#61247)
Catalin Irimie0517b96c8c80
diff --git a/cli/CHANGELOG.md b/cli/CHANGELOG.mdindex 713f632c619c..d1aec1623f82 100644--- a/cli/CHANGELOG.md+++ b/cli/CHANGELOG.md@@ -1,5 +1,9 @@# posthog-cli+# 0.7.16++- feat: add `--dry-run` flag (and `POSTHOG_CLI_DRY_RUN` env var) to skip artifact uploads (sourcemap, dSYM, Hermes, ProGuard) without contacting PostHog or requiring credentials — for CI gates that bundle to catch regressions but must not upload.+# 0.7.15- fix: make symbol upload retry logs clearer and report failed finalization explicitly.diff --git a/cli/Cargo.lock b/cli/Cargo.lockindex 6fb19c1af1da..e0e777a543ec 100644--- a/cli/Cargo.lock+++ b/cli/Cargo.lock@@ -1851,7 +1851,7 @@ dependencies = [[[package]]name = "posthog-cli"-version = "0.7.15"+version = "0.7.16"dependencies = ["anyhow","chrono",diff --git a/cli/Cargo.toml b/cli/Cargo.tomlindex b72789a94575..44d7c5942adf 100644--- a/cli/Cargo.toml+++ b/cli/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-cli"-version = "0.7.15"+version = "0.7.16"authors = ["David <[email protected]>","Olly <[email protected]>",diff --git a/cli/README.md b/cli/README.mdindex d2af5efa053b..6aac047e8e2e 100644--- a/cli/README.md+++ b/cli/README.md@@ -15,6 +15,7 @@ Commands:Options:--host <HOST> The PostHog host to connect to [default: https://us.posthog.com]+ --dry-run Skip artifact processing and upload without contacting PostHog or requiring credentials-h, --help Print help-V, --version Print version```@@ -31,6 +32,17 @@ These variables can also be loaded from a dotenv-style file via `--env-file <PATFull precedence: CLI args → process env → `--env-file` → `~/.posthog/credentials.json` (from `posthog-cli login`).+## 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.+(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.+Do not use it for release builds, since no symbols are uploaded.++The env var accepts the usual truthy/falsy values (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`).+### Personal API key scopesCommands require different API scopes. Make sure to set these scopes on your personal API key:diff --git a/cli/src/commands.rs b/cli/src/commands.rsindex 2c978b1cc85b..99d0e1e8470f 100644--- a/cli/src/commands.rs+++ b/cli/src/commands.rs@@ -2,7 +2,7 @@ use std::path::PathBuf;use anyhow::Context;use clap::{Parser, Subcommand};-use tracing::error;+use tracing::{error, warn};use crate::{download::SymbolSetsSubcommand,@@ -36,10 +36,44 @@ pub struct Cli {#[arg(long, value_name = "PATH")]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.+ #[arg(+ long,+ env = "POSTHOG_CLI_DRY_RUN",+ value_parser = clap::builder::BoolishValueParser::new(),+ num_args = 0..=1,+ require_equals = true,+ default_value = "false",+ default_missing_value = "true",+ )]+ dry_run: bool,+#[command(subcommand)]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).+fn dry_run_skipped_command(command: &Commands) -> Option<&'static str> {+ match command {+ Commands::Sourcemap { .. } => Some("sourcemap"),+ Commands::Dsym { .. } => Some("dSYM"),+ Commands::Hermes { .. } => Some("hermes sourcemap"),+ Commands::Proguard { .. } => Some("proguard"),+ Commands::Exp { cmd } => match cmd {+ ExpCommand::Hermes { .. } => Some("hermes sourcemap"),+ ExpCommand::Proguard { .. } => Some("proguard"),+ ExpCommand::Dsym { .. } => Some("dSYM"),+ _ => None,+ },+ _ => None,+ }+}+#[derive(Subcommand)]pub enum Commands {/// Interactively authenticate with PostHog, storing a personal API token locally. You can also use the@@ -169,6 +203,17 @@ impl Cli {}fn run_impl(self) -> Result<(), CapturedError> {+ 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. \+ Nothing was sent to PostHog and no credentials were used. \+ Do not use --dry-run for release builds."+ );+ return Ok(());+ }+ }+if !matches!(self.command,Commands::Login@@ -291,3 +336,130 @@ impl Cli {Ok(())}}++#[cfg(test)]+mod tests {+ use super::*;+ use clap::{CommandFactory, Parser};++ #[test]+ fn cli_definition_is_valid() {+ Cli::command().debug_assert();+ }++ #[test]+ fn dry_run_flag_is_wired_to_env_var() {+ let cmd = Cli::command();+ let arg = cmd+ .get_arguments()+ .find(|a| a.get_id().as_str() == "dry_run")+ .expect("dry_run arg should exist");+ assert_eq!(+ arg.get_env(),+ Some(std::ffi::OsStr::new("POSTHOG_CLI_DRY_RUN"))+ );+ }++ #[test]+ fn dry_run_defaults_to_false() {+ let cli = Cli::try_parse_from(["posthog-cli", "login"]).unwrap();+ assert!(!cli.dry_run);+ }++ #[test]+ fn dry_run_flag_sets_true_before_subcommand() {+ let cli = Cli::try_parse_from(["posthog-cli", "--dry-run", "login"]).unwrap();+ assert!(cli.dry_run);+ }++ #[test]+ fn dry_run_classifies_every_command() {+ // (argv, expected kind). `dry_run_skipped_command` matches on the top-level command, so one+ // representative subcommand per family is enough; the `exp` aliases get their own rows.+ let cases: &[(&[&str], Option<&str>)] = &[+ (&["sourcemap", "upload"], Some("sourcemap")),+ (&["dsym", "upload", "--directory", "d"], Some("dSYM")),+ (+ &[+ "hermes",+ "clone",+ "--minified-map-path",+ "m",+ "--composed-map-path",+ "c",+ ],+ Some("hermes sourcemap"),+ ),+ (+ &["proguard", "upload", "--path", "p", "--map-id", "m"],+ Some("proguard"),+ ),+ // hidden `exp` aliases must skip too+ (&["exp", "dsym", "upload", "--directory", "d"], Some("dSYM")),+ (+ &[+ "exp",+ "hermes",+ "clone",+ "--minified-map-path",+ "m",+ "--composed-map-path",+ "c",+ ],+ Some("hermes sourcemap"),+ ),+ (+ &["exp", "proguard", "upload", "--path", "p", "--map-id", "m"],+ Some("proguard"),+ ),+ // commands that don't upload artifacts must run normally+ (&["login"], None),+ (&["exp", "schema", "status"], None),+ (&["exp", "endpoints", "push", "f.yaml"], None),+ ];++ for (argv, expected) in cases {+ let cli = Cli::try_parse_from(std::iter::once(&"posthog-cli").chain(argv.iter()))+ .unwrap_or_else(|e| panic!("failed to parse {argv:?}: {e}"));+ assert_eq!(+ dry_run_skipped_command(&cli.command),+ *expected,+ "wrong dry-run classification for {argv:?}"+ );+ }+ }++ #[test]+ fn endpoints_dry_run_is_independent_of_top_level_flag() {+ // The `exp endpoints` commands have their own `--dry-run` (preview). The top-level flag is+ // not global, so `exp endpoints push --dry-run` sets only the endpoint flag, and the+ // top-level skip never fires for endpoints — preview semantics stay intact.+ use crate::experimental::endpoints::EndpointCommand;+ let cli = Cli::try_parse_from([+ "posthog-cli",+ "exp",+ "endpoints",+ "push",+ "f.yaml",+ "--dry-run",+ ])+ .unwrap();++ assert!(+ !cli.dry_run,+ "endpoint --dry-run must not set the top-level flag"+ );+ assert_eq!(dry_run_skipped_command(&cli.command), None);++ let Commands::Exp {+ cmd:+ ExpCommand::Endpoints {+ cmd: EndpointCommand::Push(args),+ },+ } = &cli.command+ else {+ panic!("expected `exp endpoints push`");+ };+ assert!(args.dry_run, "endpoint preview flag should be set");+ }+}