: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(error-tracking): read release data from Info.plist (#87810)
Manoel Aranda Neto30bb8706d098
diff --git a/cli/.sampo/changesets/forthright-forgemaster-kullervo.md b/cli/.sampo/changesets/forthright-forgemaster-kullervo.mdnew file mode 100644index 000000000000..9df4e357240c--- /dev/null+++ b/cli/.sampo/changesets/forthright-forgemaster-kullervo.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: minor+---++Read iOS release metadata from Info.plist filesdiff --git a/cli/README.md b/cli/README.mdindex d4658c549bc0..b5c5254d0158 100644--- a/cli/README.md+++ b/cli/README.md@@ -109,6 +109,11 @@ 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.+Pass `--info-plist <path>` to read the release name, version, and build from `CFBundleIdentifier`, `CFBundleShortVersionString`, and `CFBundleVersion`.+The CLI resolves exact Xcode build-setting references such as `$(APP_VERSION)` and `${BUILD_NUMBER}` from the environment.+Missing, unresolved, or compound values fall back to `PRODUCT_BUNDLE_IDENTIFIER`, `MARKETING_VERSION`, and `CURRENT_PROJECT_VERSION`.+Explicit `--release-name`, `--release-version`, and `--build` values take precedence.+## 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.diff --git a/cli/src/debug_symbols/upload.rs b/cli/src/debug_symbols/upload.rsindex c4eb025ba14c..73d71353afbf 100644--- a/cli/src/debug_symbols/upload.rs+++ b/cli/src/debug_symbols/upload.rs@@ -45,7 +45,7 @@ pub fn upload(args: &Args) -> Result<()> {conflict,include_source,} = args;- let release_args = release;+ let release_args = release.resolve_info_plist()?;let directory = directory.canonicalize().map_err(|e| {anyhow!(diff --git a/cli/src/dsym/mod.rs b/cli/src/dsym/mod.rsindex 967bb7078a45..f74d93138401 100644--- a/cli/src/dsym/mod.rs+++ b/cli/src/dsym/mod.rs@@ -317,55 +317,3 @@ pub fn find_dsym_bundles(directory: &PathBuf) -> Result<Vec<PathBuf>> {Ok(dsyms)}--/// Info extracted from an Info.plist file-#[derive(Debug, Clone, Default, serde::Serialize)]-pub struct PlistInfo {- /// CFBundleIdentifier (e.g., com.example.app)- #[serde(rename = "CFBundleIdentifier")]- pub bundle_identifier: Option<String>,- /// CFBundleShortVersionString (e.g., 1.2.3)- #[serde(rename = "CFBundleShortVersionString")]- pub short_version: Option<String>,- /// CFBundleVersion (e.g., 42)- #[serde(rename = "CFBundleVersion")]- pub bundle_version: Option<String>,- /// CFBundleDevelopmentRegion (e.g., English, en)- #[serde(rename = "CFBundleDevelopmentRegion")]- pub development_region: Option<String>,-}--impl PlistInfo {- /// Extract version info from an Info.plist file path- pub fn from_plist(plist_path: &Path) -> Result<Self> {- if !plist_path.exists() {- anyhow::bail!("Info.plist not found at {}", plist_path.display());- }-- let plist = plist::Value::from_file(plist_path)- .map_err(|e| anyhow!("Failed to parse Info.plist: {e}"))?;-- let dict = plist- .as_dictionary()- .ok_or_else(|| anyhow!("Info.plist is not a dictionary"))?;-- Ok(Self {- bundle_identifier: dict- .get("CFBundleIdentifier")- .and_then(|v| v.as_string())- .map(|s| s.to_string()),- short_version: dict- .get("CFBundleShortVersionString")- .and_then(|v| v.as_string())- .map(|s| s.to_string()),- bundle_version: dict- .get("CFBundleVersion")- .and_then(|v| v.as_string())- .map(|s| s.to_string()),- development_region: dict- .get("CFBundleDevelopmentRegion")- .and_then(|v| v.as_string())- .map(|s| s.to_string()),- })- }-}diff --git a/cli/src/dsym/upload.rs b/cli/src/dsym/upload.rsindex 7f0605467bab..d450c2fcff54 100644--- a/cli/src/dsym/upload.rs+++ b/cli/src/dsym/upload.rs@@ -5,9 +5,9 @@ use tracing::info;use crate::{api::{self, releases::ReleaseBuilder, symbol_sets::SymbolSetUpload},- dsym::{find_dsym_bundles, DsymFile, PlistInfo},+ dsym::{find_dsym_bundles, DsymFile},sourcemaps::args::{pack_version, ReleaseArgs, UploadConflictArgs},- utils::git::get_git_info,+ utils::{git::get_git_info, xcode::PlistInfo},};#[derive(clap::Args, Clone)]@@ -52,7 +52,7 @@ pub fn upload(args: &Args) -> Result<()> {include_source,no_release_bind,} = args;- let release_args = release;+ let release_args = release.resolve_info_plist()?;let directory = directory.canonicalize().map_err(|e| {anyhow!(diff --git a/cli/src/proguard/upload.rs b/cli/src/proguard/upload.rsindex 511cab795821..a3b82cc5c66e 100644--- a/cli/src/proguard/upload.rs+++ b/cli/src/proguard/upload.rs@@ -56,12 +56,14 @@ pub fn upload(args: &Args) -> Result<()> {release_mode,} = args;+ let resolved_release = release.resolve_info_plist()?;let ReleaseArgs {name,version,build,+ info_plist: _,skip_release_on_fail,- } = release;+ } = &resolved_release;// Event mode leaves nothing on the symbol set for the server to fall back to, so an// exception resolves its release only from the app metadata on the event itself. Coordinatesdiff --git a/cli/src/release/mod.rs b/cli/src/release/mod.rsindex 19c70201629d..e39bd22909a1 100644--- a/cli/src/release/mod.rs+++ b/cli/src/release/mod.rs@@ -1,3 +1,5 @@+use std::path::PathBuf;+use anyhow::Result;use tracing::warn;@@ -29,6 +31,10 @@ pub struct ResolveArgs {#[arg(long)]pub build: Option<String>,+ /// Read missing release fields from an iOS Info.plist file.+ #[arg(long, value_name = "PATH")]+ pub info_plist: Option<PathBuf>,+/// Print the whole release as JSON instead of only its id#[arg(long, default_value_t = false)]pub json: bool,@@ -40,6 +46,7 @@ impl From<&ResolveArgs> for ReleaseArgs {name: args.name.clone(),version: args.version.clone(),build: args.build.clone(),+ info_plist: args.info_plist.clone(),// Only consulted when a symbol set upload is rejected over its release, and this// command uploads nothing.skip_release_on_fail: true,diff --git a/cli/src/sourcemaps/args.rs b/cli/src/sourcemaps/args.rsindex 72e0380f883c..6c72559c70fb 100644--- a/cli/src/sourcemaps/args.rs+++ b/cli/src/sourcemaps/args.rs@@ -9,7 +9,7 @@ use anyhow::{bail, Result};use crate::{api::{releases::ReleaseBuilder, symbol_sets::DEFAULT_UPLOAD_CONCURRENCY},- utils::files::FileSelection,+ utils::{files::FileSelection, xcode::PlistInfo},};pub const SOURCEMAP_UPLOAD_CONCURRENCY_ENV: &str = "POSTHOG_CLI_SOURCEMAP_UPLOAD_CONCURRENCY";@@ -119,10 +119,14 @@ pub struct ReleaseArgs {pub version: Option<String>,/// The build number (e.g., 42, CFBundleVersion on iOS, versionCode on Android).- /// Stored as release metadata. Optional — when omitted, no build info is recorded.+ /// Stored as release metadata. When omitted, no build info is recorded.#[arg(long)]pub build: Option<String>,+ /// Read missing release fields from an iOS Info.plist file.+ #[arg(long, value_name = "PATH")]+ pub info_plist: Option<PathBuf>,+/// If the server returns a release_id_mismatch error (symbol set already exists with a different release),/// retry the upload without associating a release instead of failing. [default: true]#[arg(long, default_value = "true")]@@ -180,6 +184,28 @@ impl UploadConflictArgs {}}+impl ReleaseArgs {+ pub fn resolve_info_plist(&self) -> Result<Self> {+ self.resolve_info_plist_with_environment(|name| std::env::var(name).ok())+ }++ fn resolve_info_plist_with_environment<F>(&self, environment: F) -> Result<Self>+ where+ F: Fn(&str) -> Option<String>,+ {+ let Some(info_plist) = &self.info_plist else {+ return Ok(self.clone());+ };++ let plist = PlistInfo::from_plist(info_plist)?.resolve_release_fields(environment);+ let mut resolved = self.clone();+ resolved.name = resolved.name.or(plist.bundle_identifier);+ resolved.version = resolved.version.or(plist.short_version);+ resolved.build = resolved.build.or(plist.bundle_version);+ Ok(resolved)+ }+}+/// Pack version and build into a single string for release uniqueness./// Releases are keyed on (name, version), so "1.0+42" and "1.0+43" are/// distinct releases. The UI splits on "+" to display them separately.@@ -207,7 +233,7 @@ impl From<ReleaseArgs> for ReleaseBuilder {mod tests {use super::*;use clap::Parser;- use std::sync::Mutex;+ use std::{collections::HashMap, fs, sync::Mutex};static CONCURRENCY_ENV_LOCK: Mutex<()> = Mutex::new(());@@ -241,6 +267,7 @@ mod tests {name: name.map(String::from),version: version.map(String::from),build: build.map(String::from),+ info_plist: None,skip_release_on_fail: true,}}@@ -266,6 +293,43 @@ mod tests {}}+ #[test]+ fn info_plist_fills_only_missing_release_fields() {+ let directory = tempfile::tempdir().expect("failed to create temporary directory");+ let info_plist = directory.path().join("Info.plist");+ fs::write(+ &info_plist,+ r#"<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0">+<dict>+ <key>CFBundleIdentifier</key>+ <string>com.plist.app</string>+ <key>CFBundleShortVersionString</key>+ <string>$(APP_VERSION)</string>+ <key>CFBundleVersion</key>+ <string>42</string>+</dict>+</plist>"#,+ )+ .expect("failed to write Info.plist");+ let environment = HashMap::from([("APP_VERSION".to_string(), "1.2.3".to_string())]);+ let args = ReleaseArgs {+ name: Some("com.explicit.app".to_string()),+ version: None,+ build: None,+ info_plist: Some(info_plist),+ skip_release_on_fail: true,+ };++ let resolved = args+ .resolve_info_plist_with_environment(|name| environment.get(name).cloned())+ .expect("Info.plist should resolve");++ assert_eq!(resolved.name.as_deref(), Some("com.explicit.app"));+ assert_eq!(resolved.version.as_deref(), Some("1.2.3"));+ assert_eq!(resolved.build.as_deref(), Some("42"));+ }+#[test]fn event_mode_always_overwrites() {let cases = [diff --git a/cli/src/sourcemaps/inject.rs b/cli/src/sourcemaps/inject.rsindex d5435d0980bf..80b7c34784fe 100644--- a/cli/src/sourcemaps/inject.rs+++ b/cli/src/sourcemaps/inject.rs@@ -218,8 +218,11 @@ fn resolve_release_id(/// 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();+ let release_args_were_provided = release.name.is_some()+ || release.version.is_some()+ || release.build.is_some()+ || release.info_plist.is_some();+ let release = release.resolve_info_plist()?;let mut builder: ReleaseBuilder = release.into();add_git_info_to_release_builder(&cwd, &mut builder, release_args_were_provided)?;if !builder.can_create() {@@ -235,6 +238,11 @@ pub fn get_release_for_maps<'a>() -> Result<Option<Release>> {// We need to fetch or create a release if: the user specified one, any pair is missing one, or the user// forced release overriding+ let release_args_were_provided = release.name.is_some()+ || release.version.is_some()+ || release.build.is_some()+ || release.info_plist.is_some();+ let release = release.resolve_info_plist()?;let needs_release = release.name.is_some()|| release.version.is_some()|| release.build.is_some()@@ -242,8 +250,6 @@ pub fn get_release_for_maps<'a>(let mut created_release = None;if needs_release {- let release_args_were_provided =- release.name.is_some() || release.version.is_some() || release.build.is_some();let mut builder: ReleaseBuilder = release.into();add_git_info_to_release_builder(directory, &mut builder, release_args_were_provided)?;@@ -359,6 +365,7 @@ mod tests {name: name.map(String::from),version: version.map(String::from),build: build.map(String::from),+ info_plist: None,skip_release_on_fail: true,}}diff --git a/cli/src/utils/mod.rs b/cli/src/utils/mod.rsindex 4d3b37f45352..187b50b5c79d 100644--- a/cli/src/utils/mod.rs+++ b/cli/src/utils/mod.rs@@ -8,6 +8,7 @@ pub mod files;pub mod git;pub mod homedir;pub mod throttler;+pub mod xcode;pub fn raise_for_err(response: Response) -> Result<Response> {if !response.status().is_success() {diff --git a/cli/src/utils/xcode.rs b/cli/src/utils/xcode.rsnew file mode 100644index 000000000000..56b24fa96380--- /dev/null+++ b/cli/src/utils/xcode.rs@@ -0,0 +1,164 @@+use std::path::Path;++use anyhow::{anyhow, Result};++/// Info extracted from an Info.plist file+#[derive(Debug, Clone, Default, serde::Serialize)]+pub struct PlistInfo {+ /// CFBundleIdentifier (e.g., com.example.app)+ #[serde(rename = "CFBundleIdentifier")]+ pub bundle_identifier: Option<String>,+ /// CFBundleShortVersionString (e.g., 1.2.3)+ #[serde(rename = "CFBundleShortVersionString")]+ pub short_version: Option<String>,+ /// CFBundleVersion (e.g., 42)+ #[serde(rename = "CFBundleVersion")]+ pub bundle_version: Option<String>,+ /// CFBundleDevelopmentRegion (e.g., English, en)+ #[serde(rename = "CFBundleDevelopmentRegion")]+ pub development_region: Option<String>,+}++impl PlistInfo {+ /// Extract version info from an Info.plist file path+ pub fn from_plist(plist_path: &Path) -> Result<Self> {+ if !plist_path.exists() {+ anyhow::bail!("Info.plist not found at {}", plist_path.display());+ }++ let plist = plist::Value::from_file(plist_path)+ .map_err(|error| anyhow!("Failed to parse Info.plist: {error}"))?;+ let dictionary = plist+ .as_dictionary()+ .ok_or_else(|| anyhow!("Info.plist is not a dictionary"))?;++ Ok(Self {+ bundle_identifier: plist_string(dictionary, "CFBundleIdentifier"),+ short_version: plist_string(dictionary, "CFBundleShortVersionString"),+ bundle_version: plist_string(dictionary, "CFBundleVersion"),+ development_region: plist_string(dictionary, "CFBundleDevelopmentRegion"),+ })+ }++ pub fn resolve_release_fields<F>(mut self, environment: F) -> Self+ where+ F: Fn(&str) -> Option<String>,+ {+ self.bundle_identifier =+ resolve_build_setting_value(self.bundle_identifier.as_deref(), &environment)+ .or_else(|| environment_value("PRODUCT_BUNDLE_IDENTIFIER", &environment));+ self.short_version =+ resolve_build_setting_value(self.short_version.as_deref(), &environment)+ .or_else(|| environment_value("MARKETING_VERSION", &environment));+ self.bundle_version =+ resolve_build_setting_value(self.bundle_version.as_deref(), &environment)+ .or_else(|| environment_value("CURRENT_PROJECT_VERSION", &environment));+ self+ }+}++fn plist_string(dictionary: &plist::Dictionary, key: &str) -> Option<String> {+ dictionary+ .get(key)+ .and_then(plist::Value::as_string)+ .map(String::from)+}++fn environment_value<F>(name: &str, environment: &F) -> Option<String>+where+ F: Fn(&str) -> Option<String>,+{+ environment(name).and_then(|value| literal_value(&value))+}++fn resolve_build_setting_value<F>(value: Option<&str>, environment: &F) -> Option<String>+where+ F: Fn(&str) -> Option<String>,+{+ let value = value?;+ if let Some(variable) = exact_build_setting_reference(value) {+ return environment_value(variable, environment);+ }+ literal_value(value)+}++fn exact_build_setting_reference(value: &str) -> Option<&str> {+ let variable = value+ .strip_prefix("$(")+ .and_then(|value| value.strip_suffix(')'))+ .or_else(|| {+ value+ .strip_prefix("${")+ .and_then(|value| value.strip_suffix('}'))+ })?;++ (!variable.is_empty()+ && variable+ .bytes()+ .all(|character| character.is_ascii_alphanumeric() || character == b'_'))+ .then_some(variable)+}++fn literal_value(value: &str) -> Option<String> {+ (!value.is_empty() && !value.contains("$(") && !value.contains("${")).then(|| value.to_string())+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use super::*;++ #[test]+ fn resolves_only_literal_values_and_exact_build_setting_references() {+ let environment = HashMap::from([+ ("VERSION".to_string(), "1.2.3".to_string()),+ ("BUILD".to_string(), "42".to_string()),+ ("INDIRECT".to_string(), "$(VERSION)".to_string()),+ ]);+ let lookup = |name: &str| environment.get(name).cloned();+ let cases = [+ (Some("1.2.3"), Some("1.2.3")),+ (Some("$(VERSION)"), Some("1.2.3")),+ (Some("${BUILD}"), Some("42")),+ (Some("$(MISSING)"), None),+ (Some("v$(VERSION)"), None),+ (Some("${VERSION}-release"), None),+ (Some("$(INDIRECT)"), None),+ (Some(""), None),+ (None, None),+ ];++ for (value, expected) in cases {+ assert_eq!(+ resolve_build_setting_value(value, &lookup).as_deref(),+ expected,+ "value={value:?}"+ );+ }+ }++ #[test]+ fn falls_back_to_xcode_release_environment_values() {+ let info = PlistInfo {+ bundle_identifier: Some("$(APP_ID)".to_string()),+ short_version: Some("v$(VERSION)".to_string()),+ bundle_version: None,+ development_region: None,+ };+ let environment = HashMap::from([+ ("APP_ID".to_string(), "com.example.app".to_string()),+ ("MARKETING_VERSION".to_string(), "1.2.3".to_string()),+ ("CURRENT_PROJECT_VERSION".to_string(), "42".to_string()),+ ]);++ let resolved = info.resolve_release_fields(|name| environment.get(name).cloned());++ assert_eq!(+ resolved.bundle_identifier.as_deref(),+ Some("com.example.app")+ );+ assert_eq!(resolved.short_version.as_deref(), Some("1.2.3"));+ assert_eq!(resolved.bundle_version.as_deref(), Some("42"));+ }+}