: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
fix(cli): handle git worktrees and packed refs (#65141)
Hugues Pouillotd51a8775252d
diff --git a/cli/.sampo/changesets/grumpy-wavetamer-louhi.md b/cli/.sampo/changesets/grumpy-wavetamer-louhi.mdnew file mode 100644index 000000000000..5b98d33d8da5--- /dev/null+++ b/cli/.sampo/changesets/grumpy-wavetamer-louhi.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Handle Git worktrees and packed refs when detecting repository infodiff --git a/cli/src/utils/git.rs b/cli/src/utils/git.rsindex 1f8d4e2f8417..f89986edd2ec 100644--- a/cli/src/utils/git.rs+++ b/cli/src/utils/git.rs@@ -14,20 +14,28 @@ pub struct GitInfo {pub commit_id: String,}+struct GitRepositoryPaths {+ git_dir: PathBuf,+ common_dir: PathBuf,+ worktree_dir: PathBuf,+}+pub fn get_git_info(dir: Option<PathBuf>) -> Result<Option<GitInfo>> {if let Some(info) = get_git_info_from_env(get_env_variable) {return Ok(Some(info));}- let git_dir = match find_git_dir(dir) {- Some(dir) => dir,+ let repository_paths = match find_git_repository_paths(dir) {+ Some(paths) => paths,None => return Ok(None),};- let remote_url = get_remote_url(&git_dir);- let repo_name = get_repo_name(&git_dir);- let branch = get_branch_name(&git_dir).context("Failed to determine current branch")?;- let commit = get_commit_sha(&git_dir, &branch).context("Failed to determine commit sha")?;+ let remote_url = get_remote_url_from_paths(&repository_paths);+ let repo_name = get_repo_name_from_paths(&repository_paths);+ let branch =+ get_branch_name(&repository_paths.git_dir).context("Failed to determine current branch")?;+ let commit =+ get_commit_sha(&repository_paths, &branch).context("Failed to determine commit sha")?;Ok(Some(GitInfo {remote_url,@@ -99,13 +107,28 @@ fn build_vercel_remote_url(Some(format!("{base_url}/{owner}/{repo_slug}.git"))}-fn find_git_dir(dir: Option<PathBuf>) -> Option<PathBuf> {+fn find_git_repository_paths(dir: Option<PathBuf>) -> Option<GitRepositoryPaths> {let mut current_dir = dir.unwrap_or(std::env::current_dir().ok()?);loop {- let git_dir = current_dir.join(".git");- if git_dir.is_dir() {- return Some(git_dir);+ let git_path = current_dir.join(".git");+ if git_path.is_dir() {+ let git_dir = normalize_existing_path(git_path);+ return Some(GitRepositoryPaths {+ common_dir: git_dir.clone(),+ git_dir,+ worktree_dir: current_dir,+ });+ }++ if git_path.is_file() {+ let git_dir = parse_git_dir_file(&git_path)?;+ let common_dir = get_common_dir(&git_dir);+ return Some(GitRepositoryPaths {+ git_dir,+ common_dir,+ worktree_dir: current_dir,+ });}if !current_dir.pop() {@@ -114,13 +137,69 @@ fn find_git_dir(dir: Option<PathBuf>) -> Option<PathBuf> {}}+fn parse_git_dir_file(git_path: &Path) -> Option<PathBuf> {+ let content = fs::read_to_string(git_path).ok()?;+ let git_dir = content.trim().strip_prefix("gitdir:")?.trim();+ let git_dir = PathBuf::from(git_dir);++ let git_dir = if git_dir.is_absolute() {+ git_dir+ } else {+ git_path.parent()?.join(git_dir)+ };++ Some(normalize_existing_path(git_dir))+}++fn get_common_dir(git_dir: &Path) -> PathBuf {+ let commondir_path = git_dir.join("commondir");+ let Ok(commondir) = fs::read_to_string(commondir_path) else {+ return git_dir.to_path_buf();+ };++ let commondir = PathBuf::from(commondir.trim());+ let common_dir = if commondir.is_absolute() {+ commondir+ } else {+ git_dir.join(commondir)+ };++ normalize_existing_path(common_dir)+}++fn normalize_existing_path(path: PathBuf) -> PathBuf {+ fs::canonicalize(&path).unwrap_or(path)+}++fn config_paths(git_dir: &Path, common_dir: &Path) -> Vec<PathBuf> {+ let mut paths = vec![git_dir.join("config.worktree")];++ if common_dir != git_dir {+ paths.push(common_dir.join("config"));+ }++ paths.push(git_dir.join("config"));+ paths+}+pub fn get_remote_url(git_dir: &Path) -> Option<String> {+ get_remote_url_from_paths(&GitRepositoryPaths {+ git_dir: git_dir.to_path_buf(),+ common_dir: git_dir.to_path_buf(),+ worktree_dir: git_dir.parent().unwrap_or(git_dir).to_path_buf(),+ })+}++fn get_remote_url_from_paths(paths: &GitRepositoryPaths) -> Option<String> {// Try grab it from the git config- let config_path = git_dir.join("config");- if config_path.exists() {+ for config_path in config_paths(&paths.git_dir, &paths.common_dir) {+ if !config_path.exists() {+ continue;+ }+let config_content = match fs::read_to_string(&config_path) {Ok(content) => content,- Err(_) => return None,+ Err(_) => continue,};for line in config_content.lines() {@@ -141,12 +220,23 @@ pub fn get_remote_url(git_dir: &Path) -> Option<String> {}pub fn get_repo_name(git_dir: &Path) -> Option<String> {+ get_repo_name_from_paths(&GitRepositoryPaths {+ git_dir: git_dir.to_path_buf(),+ common_dir: git_dir.to_path_buf(),+ worktree_dir: git_dir.parent().unwrap_or(git_dir).to_path_buf(),+ })+}++fn get_repo_name_from_paths(paths: &GitRepositoryPaths) -> Option<String> {// Try grab it from the configured remote, otherwise just use the directory name- let config_path = git_dir.join("config");- if config_path.exists() {+ for config_path in config_paths(&paths.git_dir, &paths.common_dir) {+ if !config_path.exists() {+ continue;+ }+let config_content = match fs::read_to_string(&config_path) {Ok(content) => content,- Err(_) => return None,+ Err(_) => continue,};for line in config_content.lines() {@@ -161,10 +251,8 @@ pub fn get_repo_name(git_dir: &Path) -> Option<String> {}}- if let Some(parent) = git_dir.parent() {- if let Some(name) = parent.file_name() {- return Some(name.to_string_lossy().to_string());- }+ if let Some(name) = paths.worktree_dir.file_name() {+ return Some(name.to_string_lossy().to_string());}None@@ -192,7 +280,9 @@ fn get_branch_name(git_dir: &Path) -> Result<String> {}}-fn get_commit_sha(git_dir: &Path, branch: &str) -> Result<String> {+fn get_commit_sha(paths: &GitRepositoryPaths, branch: &str) -> Result<String> {+ let git_dir = &paths.git_dir;+if branch == "HEAD-detached" {// For detached HEAD, read directly from HEADlet head_path = git_dir.join("HEAD");@@ -205,9 +295,12 @@ fn get_commit_sha(git_dir: &Path, branch: &str) -> Result<String> {return Ok(head_content.trim().to_string());}- // Try to read the commit from the branch reference- let ref_path = git_dir.join("refs/heads").join(branch);- if ref_path.exists() {+ // Try to read the commit from the branch reference (loose ref)+ for ref_path in branch_ref_paths(paths, branch) {+ if !ref_path.exists() {+ continue;+ }+let mut commit_id = String::new();fs::File::open(&ref_path).with_context(|| format!("Failed to open branch reference at {ref_path:?}"))?@@ -217,9 +310,69 @@ fn get_commit_sha(git_dir: &Path, branch: &str) -> Result<String> {return Ok(commit_id.trim().to_string());}+ // Fall back to packed-refs — Git packs loose refs into this file during+ // garbage collection or clone, which is common on Windows and in CI.+ if let Some(commit_id) = get_packed_ref(paths, branch) {+ return Ok(commit_id);+ }+anyhow::bail!("Could not determine commit ID")}+fn branch_ref_paths(paths: &GitRepositoryPaths, branch: &str) -> Vec<PathBuf> {+ let mut ref_paths = vec![paths.git_dir.join("refs/heads").join(branch)];++ if paths.common_dir != paths.git_dir {+ ref_paths.push(paths.common_dir.join("refs/heads").join(branch));+ }++ ref_paths+}++fn get_packed_ref(paths: &GitRepositoryPaths, branch: &str) -> Option<String> {+ let ref_name = format!("refs/heads/{branch}");+ let mut packed_ref_paths = vec![paths.git_dir.join("packed-refs")];++ if paths.common_dir != paths.git_dir {+ packed_ref_paths.push(paths.common_dir.join("packed-refs"));+ }++ for path in packed_ref_paths {+ let Ok(content) = fs::read_to_string(path) else {+ continue;+ };++ if let Some(commit_id) = parse_packed_refs(&content, &ref_name) {+ return Some(commit_id);+ }+ }++ None+}++fn parse_packed_refs(content: &str, ref_name: &str) -> Option<String> {+ for line in content.lines() {+ let line = line.trim();+ if line.is_empty() || line.starts_with('#') || line.starts_with('^') {+ continue;+ }++ let mut parts = line.split_whitespace();+ let Some(commit_id) = parts.next() else {+ continue;+ };+ let Some(packed_ref) = parts.next() else {+ continue;+ };++ if packed_ref == ref_name {+ return Some(commit_id.to_string());+ }+ }++ None+}+fn get_env_variable(name: &str) -> Option<String> {let env_variable = std::env::var(name).ok()?.trim().to_string();match env_variable.as_ref() {diff --git a/cli/tests/git.rs b/cli/tests/git.rsindex 803f36a37423..6f076414557e 100644--- a/cli/tests/git.rs+++ b/cli/tests/git.rs@@ -1,7 +1,8 @@-use posthog_cli::utils::git::{get_git_info_from_env, get_remote_url, get_repo_name};+use posthog_cli::utils::git::{get_git_info, get_git_info_from_env, get_remote_url, get_repo_name};use std::collections::HashMap;use std::fs;use std::path::PathBuf;+use std::sync::{Mutex, MutexGuard};use uuid::Uuid;fn env_from<const N: usize>(values: [(&str, &str); N]) -> impl Fn(&str) -> Option<String> {@@ -12,6 +13,28 @@ fn env_from<const N: usize>(values: [(&str, &str); N]) -> impl Fn(&str) -> Optiomove |key| env.get(key).cloned()}+static ENV_LOCK: Mutex<()> = Mutex::new(());++fn lock_env() -> MutexGuard<'static, ()> {+ ENV_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++const GIT_INFO_ENV_VARS: &[&str] = &[+ "GITHUB_ACTIONS",+ "GITHUB_SHA",+ "GITHUB_REF_NAME",+ "GITHUB_REPOSITORY",+ "GITHUB_SERVER_URL",+ "VERCEL",+ "VERCEL_GIT_PROVIDER",+ "VERCEL_GIT_REPO_OWNER",+ "VERCEL_GIT_REPO_SLUG",+ "VERCEL_GIT_COMMIT_REF",+ "VERCEL_GIT_COMMIT_SHA",+];+fn make_git_dir_with_config(config_content: &str) -> PathBuf {let temp_root = std::env::temp_dir().join(format!("posthog_cli_git_test_{}", Uuid::now_v7()));let git_dir = temp_root.join(".git");@@ -21,6 +44,135 @@ fn make_git_dir_with_config(config_content: &str) -> PathBuf {git_dir}+fn remove_env_vars(names: &[&str]) -> Vec<(String, Option<String>)> {+ names+ .iter()+ .map(|name| {+ let value = std::env::var(name).ok();+ std::env::remove_var(name);+ ((*name).to_string(), value)+ })+ .collect()+}++struct EnvVarGuard(Vec<(String, Option<String>)>);++impl EnvVarGuard {+ fn clear(names: &[&str]) -> Self {+ Self(remove_env_vars(names))+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ for (name, value) in self.0.drain(..) {+ match value {+ Some(value) => std::env::set_var(name, value),+ None => std::env::remove_var(name),+ }+ }+ }+}++fn write_repo_config(git_dir: &std::path::Path) {+ fs::write(+ git_dir.join("config"),+ r#"+[core]+ repositoryformatversion = 0+[remote "origin"]+ url = https://github.com/PostHog/posthog.git+ fetch = +refs/heads/*:refs/remotes/origin/*+"#,+ )+ .expect("failed to write config");+}++fn write_head(git_dir: &std::path::Path, branch: &str) {+ fs::write(git_dir.join("HEAD"), format!("ref: refs/heads/{branch}\n"))+ .expect("failed to write HEAD");+}++fn write_loose_ref(git_dir: &std::path::Path, branch: &str, commit_id: &str) {+ let branch_ref = git_dir.join("refs/heads").join(branch);+ fs::create_dir_all(branch_ref.parent().unwrap()).expect("failed to create refs directory");+ fs::write(branch_ref, format!("{commit_id}\n")).expect("failed to write branch ref");+}++fn write_packed_ref(git_dir: &std::path::Path, branch: &str, commit_id: &str) {+ fs::write(+ git_dir.join("packed-refs"),+ format!("# pack-refs with: peeled fully-peeled sorted\n{commit_id} refs/heads/{branch}\n"),+ )+ .expect("failed to write packed-refs");+}++fn assert_posthog_git_info(worktree_dir: PathBuf, branch: &str, commit_id: &str) {+ let info = get_git_info(Some(worktree_dir))+ .expect("should not error")+ .expect("should return info");++ assert_eq!(info.branch, branch);+ assert_eq!(info.commit_id, commit_id);+ assert_eq!(+ info.remote_url.as_deref(),+ Some("https://github.com/PostHog/posthog.git")+ );+ assert_eq!(info.repo_name.as_deref(), Some("posthog"));+}++#[test]+fn test_get_commit_sha_from_loose_ref() {+ let _env_lock = lock_env();+ let _env_guard = EnvVarGuard::clear(GIT_INFO_ENV_VARS);++ let temp_root =+ std::env::temp_dir().join(format!("posthog_cli_loose_ref_test_{}", Uuid::now_v7()));+ let git_dir = temp_root.join(".git");+ let branch = "main";+ let commit_id = "abc123def456abc123def456abc123def456abc1";++ fs::create_dir_all(&git_dir).expect("failed to create .git directory");+ write_head(&git_dir, branch);+ write_loose_ref(&git_dir, branch, commit_id);++ let info = get_git_info(Some(temp_root.clone()))+ .expect("get_git_info failed")+ .expect("expected Some(GitInfo)");++ assert_eq!(info.branch, branch);+ assert_eq!(info.commit_id, commit_id);+ let _ = fs::remove_dir_all(temp_root);+}++#[test]+fn test_get_commit_sha_loose_ref_takes_precedence_over_packed_refs() {+ let _env_lock = lock_env();+ let _env_guard = EnvVarGuard::clear(GIT_INFO_ENV_VARS);++ let temp_root = std::env::temp_dir().join(format!(+ "posthog_cli_ref_precedence_test_{}",+ Uuid::now_v7()+ ));+ let git_dir = temp_root.join(".git");+ let branch = "main";+ let loose_commit_id = "1111111111111111111111111111111111111111";+ let packed_commit_id = "cafebabecafebabecafebabecafebabecafebabe";++ fs::create_dir_all(&git_dir).expect("failed to create .git directory");+ write_head(&git_dir, branch);+ write_loose_ref(&git_dir, branch, loose_commit_id);+ write_packed_ref(&git_dir, branch, packed_commit_id);++ let info = get_git_info(Some(temp_root.clone()))+ .expect("get_git_info failed")+ .expect("expected Some(GitInfo)");++ assert_eq!(info.branch, branch);+ assert_eq!(info.commit_id, loose_commit_id);+ let _ = fs::remove_dir_all(temp_root);+}+#[test]fn test_get_repo_infos_https_with_dot_git() {let cfg = r#"@@ -93,6 +245,155 @@ fn test_get_repo_infos_ssh_without_dot_git() {let _ = fs::remove_dir_all(git_dir.parent().unwrap());}+#[test]+fn test_get_git_info_from_regular_repo_packed_refs() {+ let _env_lock = lock_env();+ let _env_guard = EnvVarGuard::clear(GIT_INFO_ENV_VARS);++ let temp_root =+ std::env::temp_dir().join(format!("posthog_cli_regular_repo_test_{}", Uuid::now_v7()));+ let git_dir = temp_root.join(".git");+ let branch = "feature/packed";+ let commit_id = "0123456789abcdef0123456789abcdef01234567";++ fs::create_dir_all(&git_dir).expect("failed to create .git directory");+ write_head(&git_dir, branch);+ write_packed_ref(&git_dir, branch, commit_id);+ write_repo_config(&git_dir);++ assert_posthog_git_info(temp_root.clone(), branch, commit_id);++ let _ = fs::remove_dir_all(temp_root);+}++#[test]+fn test_get_git_info_from_worktree_git_file_cases() {+ let _env_lock = lock_env();+ let _env_guard = EnvVarGuard::clear(GIT_INFO_ENV_VARS);++ for (case_name, absolute_gitdir, commondir, use_packed_ref) in [+ (+ "relative loose ref in common dir",+ false,+ Some("../.."),+ false,+ ),+ (+ "absolute gitdir with packed ref in common dir",+ true,+ Some("../.."),+ true,+ ),+ (+ "no commondir uses worktree git dir packed ref",+ true,+ None,+ true,+ ),+ ] {+ let case_slug = case_name.replace(' ', "-");+ let temp_root = std::env::temp_dir().join(format!(+ "posthog_cli_worktree_test_{}_{}",+ case_slug,+ Uuid::now_v7()+ ));+ let worktree_dir = temp_root.join("worktree");+ let common_git_dir = temp_root.join("repo.git");+ let worktree_git_dir = common_git_dir.join("worktrees/worktree");+ let git_dir = if commondir.is_some() {+ worktree_git_dir.clone()+ } else {+ temp_root.join("single-worktree.git")+ };+ let branch = format!("feature/{case_slug}");+ let commit_id = "0123456789abcdef0123456789abcdef01234567";++ fs::create_dir_all(&worktree_dir).expect("failed to create worktree directory");+ fs::create_dir_all(&git_dir).expect("failed to create worktree git directory");+ fs::create_dir_all(&common_git_dir).expect("failed to create common git directory");++ let gitdir = if absolute_gitdir {+ git_dir.display().to_string()+ } else {+ "../repo.git/worktrees/worktree".to_string()+ };+ fs::write(worktree_dir.join(".git"), format!("gitdir: {gitdir}\n"))+ .expect("failed to write worktree .git file");+ if let Some(commondir) = commondir {+ fs::write(git_dir.join("commondir"), format!("{commondir}\n"))+ .expect("failed to write commondir");+ }+ write_head(&git_dir, &branch);++ let ref_git_dir = if commondir.is_some() {+ &common_git_dir+ } else {+ &git_dir+ };+ if use_packed_ref {+ write_packed_ref(ref_git_dir, &branch, commit_id);+ } else {+ write_loose_ref(ref_git_dir, &branch, commit_id);+ }+ write_repo_config(ref_git_dir);++ assert_posthog_git_info(worktree_dir, &branch, commit_id);++ let _ = fs::remove_dir_all(temp_root);+ }+}++#[test]+fn test_get_git_info_from_worktree_config_precedence() {+ let _env_lock = lock_env();+ let _env_guard = EnvVarGuard::clear(GIT_INFO_ENV_VARS);++ let temp_root = std::env::temp_dir().join(format!(+ "posthog_cli_worktree_config_test_{}",+ Uuid::now_v7()+ ));+ let worktree_dir = temp_root.join("worktree");+ let common_git_dir = temp_root.join("repo.git");+ let worktree_git_dir = common_git_dir.join("worktrees/worktree");+ let branch = "feature/config-worktree";+ let commit_id = "0123456789abcdef0123456789abcdef01234567";++ fs::create_dir_all(&worktree_dir).expect("failed to create worktree directory");+ fs::create_dir_all(&worktree_git_dir).expect("failed to create worktree git directory");+ fs::create_dir_all(&common_git_dir).expect("failed to create common git directory");+ fs::write(+ worktree_dir.join(".git"),+ format!("gitdir: {}\n", worktree_git_dir.display()),+ )+ .expect("failed to write worktree .git file");+ fs::write(worktree_git_dir.join("commondir"), "../..\n").expect("failed to write commondir");+ write_head(&worktree_git_dir, branch);+ write_loose_ref(&common_git_dir, branch, commit_id);+ write_repo_config(&common_git_dir);+ fs::write(+ worktree_git_dir.join("config.worktree"),+ r#"+[remote "origin"]+ url = https://github.com/PostHog/worktree-override.git+"#,+ )+ .expect("failed to write worktree config");++ let info = get_git_info(Some(worktree_dir))+ .expect("should not error")+ .expect("should return info");++ assert_eq!(info.branch, branch);+ assert_eq!(info.commit_id, commit_id);+ assert_eq!(+ info.remote_url.as_deref(),+ Some("https://github.com/PostHog/worktree-override.git")+ );+ assert_eq!(info.repo_name.as_deref(), Some("worktree-override"));++ let _ = fs::remove_dir_all(temp_root);+}+#[test]fn test_get_git_info_from_vercel_env() {let info = get_git_info_from_env(env_from([@@ -133,24 +434,3 @@ fn test_get_git_info_from_github_env() {Some("https://github.com/PostHog/posthog.git"));}--#[test]-fn test_get_git_info_prefers_github_env_over_vercel_env() {- let info = get_git_info_from_env(env_from([- ("GITHUB_ACTIONS", "true"),- ("GITHUB_SHA", "github-sha"),- ("GITHUB_REF_NAME", "github-branch"),- ("GITHUB_REPOSITORY", "PostHog/posthog"),- ("GITHUB_SERVER_URL", "https://github.com"),- ("VERCEL", "1"),- ("VERCEL_GIT_PROVIDER", "github"),- ("VERCEL_GIT_REPO_OWNER", "PostHog"),- ("VERCEL_GIT_REPO_SLUG", "posthog"),- ("VERCEL_GIT_COMMIT_REF", "vercel-branch"),- ("VERCEL_GIT_COMMIT_SHA", "vercel-sha"),- ]))- .expect("should return info");-- assert_eq!(info.branch, "github-branch");- assert_eq!(info.commit_id, "github-sha");-}