: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): read the remote URL from the remote sections of the Git config (#107565)
Hugues Pouillot09644fddca48
diff --git a/cli/.sampo/changesets/section-aware-git-config.md b/cli/.sampo/changesets/section-aware-git-config.mdnew file mode 100644index 000000000000..8757ad4c2ec6--- /dev/null+++ b/cli/.sampo/changesets/section-aware-git-config.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Read the remote URL from the `[remote "..."]` sections of the Git config only, and prefer `origin`. A repository that records another URL in its config, such as a superproject that records the URL of a submodule, no longer gets the wrong remote URL and repository name in its release metadata.diff --git a/cli/src/utils/git.rs b/cli/src/utils/git.rsindex 1e6ddc0ccd62..f9d9041a78d7 100644--- a/cli/src/utils/git.rs+++ b/cli/src/utils/git.rs@@ -192,35 +192,199 @@ pub fn get_remote_url(git_dir: &Path) -> Option<String> {}fn get_remote_url_from_paths(paths: &GitRepositoryPaths) -> Option<String> {- // Try grab it from the git config+ let url = find_remote_url(paths)?;+ let sanitized = strip_credentials(&url)?;++ if sanitized.ends_with(".git") {+ Some(sanitized)+ } else {+ Some(format!("{sanitized}.git"))+ }+}++/// Finds the URL of the repository's own remote, across the config files that apply to this+/// worktree. `origin` wins when it is present, because that is the remote the release belongs+/// to; otherwise the first remote in config precedence order is used.+fn find_remote_url(paths: &GitRepositoryPaths) -> Option<String> {+ // Ordered from the highest precedence config file to the lowest, so the first URL found+ // for a remote name is the one git itself would use.+ let mut remotes: Vec<(String, String)> = Vec::new();+for config_path in config_paths(&paths.git_dir, &paths.common_dir) {- if !config_path.exists() {+ let Ok(config_content) = fs::read_to_string(&config_path) else {continue;+ };++ for (name, url) in parse_remote_urls(&config_content) {+ if !remotes.iter().any(|(known, _)| *known == name) {+ remotes.push((name, url));+ }}+ }- let config_content = match fs::read_to_string(&config_path) {- Ok(content) => content,- Err(_) => continue,+ remotes+ .iter()+ .find(|(name, _)| name == "origin")+ .or_else(|| remotes.first())+ .map(|(_, url)| url.clone())+}++/// Reads every `[remote "<name>"] url = <url>` entry out of one git config file, in file order.+///+/// Git config is section based, so a scan that only looks for a `url = ` line also matches+/// sections that are not remotes. A superproject with submodules is the common case: `git+/// submodule add` writes a `[submodule "<path>"] url = ...` entry, and that entry sits above+/// the `[remote "origin"]` section whenever the repository got its remote after its+/// submodules. A section blind reader then reports the submodule's URL as the repository's+/// remote.+fn parse_remote_urls(config_content: &str) -> Vec<(String, String)> {+ let mut remotes = Vec::new();+ let mut remote_name: Option<String> = None;++ for line in config_content.lines() {+ let mut line = strip_config_comment(line.trim());++ if line.starts_with('[') {+ let Some(header_end) = find_section_header_end(line) else {+ // The section is unreadable, so every key below it is too.+ remote_name = None;+ continue;+ };+ remote_name = parse_remote_section_header(&line[1..header_end]);+ // Git allows a key on the same line as the section header.+ line = line[header_end + 1..].trim();+ }++ let Some(remote_name) = remote_name.as_deref() else {+ continue;+ };+ let Some((key, value)) = line.split_once('=') else {+ continue;};+ if !key.trim().eq_ignore_ascii_case("url") {+ continue;+ }- for line in config_content.lines() {- let line = line.trim();- if line.starts_with("url = ") {- let url = line.trim_start_matches("url = ").trim();- let sanitized = strip_credentials(url)?;- let normalized = if sanitized.ends_with(".git") {- sanitized- } else {- format!("{sanitized}.git")- };- return Some(normalized);- }+ let url = parse_config_value(value);+ if !url.is_empty() {+ remotes.push((remote_name.to_string(), url));+ }+ }++ remotes+}++/// Returns the index of the `]` that closes a section header. A subsection name is quoted and+/// can hold a `]` of its own, which git accepts: `git remote add 'deploy]prod' <url>` writes+/// `[remote "deploy]prod"]`.+fn find_section_header_end(line: &str) -> Option<usize> {+ let mut in_quotes = false;+ let mut escaped = false;++ for (index, character) in line.char_indices() {+ if escaped {+ escaped = false;+ continue;+ }++ match character {+ '\\' => escaped = true,+ '"' => in_quotes = !in_quotes,+ ']' if !in_quotes => return Some(index),+ _ => {}}}None}+/// Returns the remote name of a `remote "<name>"` section header, and `None` for every other+/// section. Section names are case insensitive, subsection names are not.+fn parse_remote_section_header(header: &str) -> Option<String> {+ let (section, subsection) = header.trim().split_once('"')?;+ if !section.trim().eq_ignore_ascii_case("remote") {+ return None;+ }++ let name = unescape_config_subsection(subsection.strip_suffix('"')?);+ if name.is_empty() {+ return None;+ }++ Some(name)+}++/// Drops a trailing `#` or `;` comment. A `#` inside a quoted value is part of the value, and a+/// URL can hold one as a fragment.+fn strip_config_comment(line: &str) -> &str {+ let mut in_quotes = false;+ let mut escaped = false;++ for (index, character) in line.char_indices() {+ if escaped {+ escaped = false;+ continue;+ }++ match character {+ '\\' => escaped = true,+ '"' => in_quotes = !in_quotes,+ '#' | ';' if !in_quotes => return line[..index].trim_end(),+ _ => {}+ }+ }++ line+}++/// Decodes a git config subsection name. Git keeps the escaped character of `\"` and `\\`, and+/// drops a backslash that precedes anything else: it reads `[remote "ori\gin"]` as the remote+/// `origin` and `[remote "tab\there"]` as `tabthere`. A value follows different rules, so it+/// has its own decoder.+fn unescape_config_subsection(name: &str) -> String {+ let mut parsed = String::with_capacity(name.len());+ let mut characters = name.chars();++ while let Some(character) = characters.next() {+ match character {+ '\\' => parsed.extend(characters.next()),+ _ => parsed.push(character),+ }+ }++ parsed+}++/// Unwraps a git config value: it can be quoted, and a quoted value can escape a quote or a+/// backslash.+fn parse_config_value(value: &str) -> String {+ unescape_config_string(value.trim())+}++/// Drops the quotes around a git config string, and resolves the escapes a quoted string can+/// hold.+fn unescape_config_string(value: &str) -> String {+ let mut parsed = String::with_capacity(value.len());+ let mut characters = value.chars();++ while let Some(character) = characters.next() {+ match character {+ '"' => {}+ '\\' => match characters.next() {+ Some(escaped @ ('"' | '\\')) => parsed.push(escaped),+ Some(other) => {+ parsed.push('\\');+ parsed.push(other);+ }+ None => parsed.push('\\'),+ },+ _ => parsed.push(character),+ }+ }++ parsed+}+/// Drops every part of a URL that can carry a credential before it is stored anywhere: the/// userinfo component (`user[:pass]@`), the query, and the fragment. CI checkouts commonly/// write a remote URL with an embedded credential (e.g. `actions/checkout`'s@@ -295,34 +459,15 @@ pub fn get_repo_name(git_dir: &Path) -> Option<String> {}fn get_repo_name_from_paths(paths: &GitRepositoryPaths) -> Option<String> {- // Try grab it from the configured remote, otherwise just use the directory name- 'configs: 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(_) => continue,- };-- for line in config_content.lines() {- let line = line.trim();- if line.starts_with("url = ") {- let url = line.trim_start_matches("url = ").trim();- // A remote with no path puts the authority in the last segment, so the name- // is taken from the sanitized URL. Fall back to the directory name when the- // URL cannot be sanitized, rather than name the repository after a credential.- let Some(sanitized) = strip_credentials(url) else {- break 'configs;- };- if let Some(repo_name) = sanitized.split('/').next_back() {- let clean_name = repo_name.trim_end_matches(".git");- if !clean_name.is_empty() {- return Some(clean_name.to_string());- }- }- break 'configs;+ // Try grab it from the configured remote, otherwise just use the directory name.+ // A remote with no path puts the authority in the last segment, so the name is taken from+ // the sanitized URL. Fall back to the directory name when the URL cannot be sanitized,+ // rather than name the repository after a credential.+ if let Some(sanitized) = find_remote_url(paths).and_then(|url| strip_credentials(&url)) {+ if let Some(repo_name) = sanitized.split('/').next_back() {+ let clean_name = repo_name.trim_end_matches(".git");+ if !clean_name.is_empty() {+ return Some(clean_name.to_string());}}}@@ -568,14 +713,14 @@ mod tests {}fn write_config(url: &str) -> (tempfile::TempDir, GitRepositoryPaths) {+ write_config_content(&format!("[remote \"origin\"]\n\turl = {url}\n"))+ }++ fn write_config_content(content: &str) -> (tempfile::TempDir, GitRepositoryPaths) {let dir = tempfile::tempdir().unwrap();let git_dir = dir.path().join(".git");fs::create_dir_all(&git_dir).unwrap();- fs::write(- git_dir.join("config"),- format!("[remote \"origin\"]\n\turl = {url}\n"),- )- .unwrap();+ fs::write(git_dir.join("config"), content).unwrap();let paths = GitRepositoryPaths {git_dir: git_dir.clone(),common_dir: git_dir,@@ -584,6 +729,216 @@ mod tests {(dir, paths)}+ #[test]+ fn parse_remote_urls_reads_only_remote_sections() {+ let config = r#"+[core]+ repositoryformatversion = 0+[submodule "vendor/lib"]+ url = https://github.com/PostHog/vendored.git+ active = true+[remote "upstream"]+ url = https://github.com/Other/upstream.git+[remote "origin"]+ url = https://github.com/PostHog/posthog.git+ pushurl = https://github.com/PostHog/fork.git+"#;++ assert_eq!(+ parse_remote_urls(config),+ vec![+ (+ "upstream".to_string(),+ "https://github.com/Other/upstream.git".to_string()+ ),+ (+ "origin".to_string(),+ "https://github.com/PostHog/posthog.git".to_string()+ ),+ ]+ );+ }++ #[test]+ fn parse_remote_urls_handles_config_syntax() {+ let cases = [+ (+ "no spaces around the separator",+ "[remote \"origin\"]\nurl=https://github.com/PostHog/posthog.git\n",+ vec!["https://github.com/PostHog/posthog.git"],+ ),+ (+ "a quoted value",+ "[remote \"origin\"]\n\turl = \"https://github.com/PostHog/posthog.git\"\n",+ vec!["https://github.com/PostHog/posthog.git"],+ ),+ (+ "a key on the section header line",+ "[remote \"origin\"] url = https://github.com/PostHog/posthog.git\n",+ vec!["https://github.com/PostHog/posthog.git"],+ ),+ (+ "a trailing comment",+ "[remote \"origin\"]\n\turl = https://github.com/PostHog/posthog.git ; the remote\n",+ vec!["https://github.com/PostHog/posthog.git"],+ ),+ (+ "a section name in a different case",+ "[REMOTE \"origin\"]\n\tURL = https://github.com/PostHog/posthog.git\n",+ vec!["https://github.com/PostHog/posthog.git"],+ ),+ (+ "a url section, which names the URL in the header rather than a value",+ "[url \"[email protected]:\"]\n\tinsteadOf = https://github.com/\n",+ vec![],+ ),+ (+ "a key that only ends in url",+ "[remote \"origin\"]\n\tpushurl = https://github.com/PostHog/fork.git\n",+ vec![],+ ),+ (+ "an unterminated section header",+ "[remote \"origin\"\n\turl = https://github.com/PostHog/posthog.git\n",+ vec![],+ ),+ ];++ for (name, config, expected) in cases {+ let urls: Vec<String> = parse_remote_urls(config)+ .into_iter()+ .map(|(_, url)| url)+ .collect();+ assert_eq!(urls, expected, "case: {name}");+ }+ }++ #[test]+ fn parse_remote_urls_reads_a_remote_name_that_holds_config_syntax() {+ // `git remote add 'deploy]prod' <url>` is accepted and writes this header, so the+ // closing bracket of the header is the one outside the quoted name.+ let cases = [+ (+ "a bracket in the name",+ "[remote \"deploy]prod\"]\n\turl = https://github.com/PostHog/posthog.git\n",+ "deploy]prod",+ ),+ (+ "a comment character in the name",+ "[remote \"deploy#1\"]\n\turl = https://github.com/PostHog/posthog.git\n",+ "deploy#1",+ ),+ (+ "an escaped quote in the name",+ "[remote \"deploy\\\"prod\"]\n\turl = https://github.com/PostHog/posthog.git\n",+ "deploy\"prod",+ ),+ (+ "an escaped backslash in the name",+ "[remote \"back\\\\slash\"]\n\turl = https://github.com/PostHog/posthog.git\n",+ "back\\slash",+ ),+ (+ // Git drops a backslash that precedes anything else, so this names `origin`.+ "a backslash before another character in the name",+ "[remote \"ori\\gin\"]\n\turl = https://github.com/PostHog/posthog.git\n",+ "origin",+ ),+ ];++ for (name, config, expected_remote) in cases {+ assert_eq!(+ parse_remote_urls(config),+ vec![(+ expected_remote.to_string(),+ "https://github.com/PostHog/posthog.git".to_string()+ )],+ "case: {name}"+ );+ }+ }++ #[test]+ fn get_repo_infos_prefer_origin_written_with_a_dropped_escape() {+ // Git reads `[remote "ori\gin"]` as the remote `origin`, so the release belongs to it+ // rather than to the remote above it.+ let (_dir, paths) = write_config_content(+ "[remote \"upstream\"]\n\turl = https://github.com/Other/upstream.git\n\+ [remote \"ori\\gin\"]\n\turl = https://github.com/PostHog/posthog.git\n",+ );++ assert_eq!(+ get_remote_url_from_paths(&paths),+ Some("https://github.com/PostHog/posthog.git".to_string())+ );+ }++ #[test]+ fn get_repo_infos_prefer_origin_over_another_remote() {+ let (_dir, paths) = write_config_content(+ r#"+[submodule "vendor/lib"]+ url = https://github.com/PostHog/vendored.git+[remote "upstream"]+ url = https://github.com/Other/upstream.git+[remote "origin"]+ url = https://github.com/PostHog/posthog.git+"#,+ );++ assert_eq!(+ get_remote_url_from_paths(&paths),+ Some("https://github.com/PostHog/posthog.git".to_string())+ );+ assert_eq!(+ get_repo_name_from_paths(&paths),+ Some("posthog".to_string())+ );+ }++ #[test]+ fn get_repo_infos_use_the_only_remote_when_there_is_no_origin() {+ let (_dir, paths) = write_config_content(+ r#"+[submodule "vendor/lib"]+ url = https://github.com/PostHog/vendored.git+[remote "upstream"]+ url = https://github.com/Other/upstream.git+"#,+ );++ assert_eq!(+ get_remote_url_from_paths(&paths),+ Some("https://github.com/Other/upstream.git".to_string())+ );+ assert_eq!(+ get_repo_name_from_paths(&paths),+ Some("upstream".to_string())+ );+ }++ #[test]+ fn get_repo_infos_ignore_a_submodule_url_and_fall_back_to_the_directory_name() {+ let (dir, paths) = write_config_content(+ r#"+[submodule "vendor/lib"]+ url = https://github.com/PostHog/vendored.git+"#,+ );++ assert_eq!(get_remote_url_from_paths(&paths), None);+ assert_eq!(+ get_repo_name_from_paths(&paths),+ Some(+ dir.path()+ .file_name()+ .unwrap()+ .to_string_lossy()+ .to_string()+ )+ );+ }+#[test]fn get_remote_url_from_paths_strips_credential_from_config() {let (_dir, paths) =diff --git a/cli/tests/git.rs b/cli/tests/git.rsindex 6f076414557e..d4eafba72d6f 100644--- a/cli/tests/git.rs+++ b/cli/tests/git.rs@@ -1,7 +1,8 @@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::path::{Path, PathBuf};+use std::process::Command;use std::sync::{Mutex, MutexGuard};use uuid::Uuid;@@ -394,6 +395,198 @@ fn test_get_git_info_from_worktree_config_precedence() {let _ = fs::remove_dir_all(temp_root);}+/// Runs git in `dir` and returns its trimmed standard output.+fn git(dir: &Path, args: &[&str]) -> String {+ let output = Command::new("git")+ .args(args)+ .current_dir(dir)+ .env("GIT_CONFIG_GLOBAL", "/dev/null")+ .env("GIT_CONFIG_SYSTEM", "/dev/null")+ .output()+ .unwrap_or_else(|error| panic!("failed to run git {args:?}: {error}"));++ assert!(+ output.status.success(),+ "git {args:?} failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ String::from_utf8_lossy(&output.stdout).trim().to_string()+}++fn git_is_available() -> bool {+ Command::new("git")+ .arg("--version")+ .output()+ .is_ok_and(|output| output.status.success())+}++/// Creates a repository with one commit on `main` and the given remote.+///+/// The commit is written with plumbing rather than `git commit`, so the test does not depend on+/// the hooks or the signing configuration of the machine that runs it.+fn init_repo_with_commit(dir: &Path, remote_url: Option<&str>) -> String {+ fs::create_dir_all(dir).expect("failed to create repository directory");+ git(dir, &["init", "-q", "-b", "main", "."]);+ if let Some(remote_url) = remote_url {+ git(dir, &["remote", "add", "origin", remote_url]);+ }++ fs::create_dir_all(dir.join("nested")).expect("failed to create nested directory");+ fs::write(dir.join("nested/file.txt"), "content").expect("failed to write file");+ git(dir, &["add", "."]);++ let tree = git(dir, &["write-tree"]);+ let commit = git(+ dir,+ &[+ "-c",+ "user.name=posthog-cli test",+ "-c",+ "[email protected]",+ "commit-tree",+ &tree,+ "-m",+ "initial commit",+ ],+ );+ git(dir, &["update-ref", "refs/heads/main", &commit]);++ commit+}++fn temp_root(name: &str) -> PathBuf {+ let root = std::env::temp_dir().join(format!("posthog_cli_{name}_{}", Uuid::now_v7()));+ fs::create_dir_all(&root).expect("failed to create temp root");+ root+}++fn git_info_of(dir: &Path) -> posthog_cli::utils::git::GitInfo {+ get_git_info(Some(dir.to_path_buf()))+ .unwrap_or_else(|error| panic!("get_git_info failed for {}: {error:#}", dir.display()))+ .unwrap_or_else(|| panic!("no git info for {}", dir.display()))+}++/// The layout of a real `git worktree`: `.git` is a file, HEAD lives in the worktree's own git+/// directory, and the branch ref and the config live in the common git directory.+#[test]+fn test_get_git_info_from_a_real_worktree() {+ if !git_is_available() {+ eprintln!("skipping: git is not on PATH");+ return;+ }++ let _env_lock = lock_env();+ let _env_guard = EnvVarGuard::clear(GIT_INFO_ENV_VARS);++ let root = temp_root("real_worktree");+ let main_dir = root.join("main");+ let commit = init_repo_with_commit(&main_dir, Some("https://github.com/PostHog/posthog.git"));++ let worktree_dir = root.join("feature-worktree");+ git(+ &main_dir,+ &[+ "worktree",+ "add",+ "-q",+ worktree_dir.to_str().unwrap(),+ "-b",+ "feature/in-a-worktree",+ ],+ );++ for dir in [&worktree_dir, &worktree_dir.join("nested")] {+ let info = git_info_of(dir);+ assert_eq!(info.branch, "feature/in-a-worktree");+ assert_eq!(info.commit_id, commit);+ assert_eq!(+ info.remote_url.as_deref(),+ Some("https://github.com/PostHog/posthog.git")+ );+ assert_eq!(info.repo_name.as_deref(), Some("posthog"));+ }++ // Packing the refs removes the loose branch ref the worktree read above.+ git(&main_dir, &["pack-refs", "--all"]);+ let info = git_info_of(&worktree_dir);+ assert_eq!(info.branch, "feature/in-a-worktree");+ assert_eq!(info.commit_id, commit);++ let detached_dir = root.join("detached-worktree");+ git(+ &main_dir,+ &[+ "worktree",+ "add",+ "-q",+ "--detach",+ detached_dir.to_str().unwrap(),+ &commit,+ ],+ );+ let info = git_info_of(&detached_dir);+ assert_eq!(info.branch, "HEAD-detached");+ assert_eq!(info.commit_id, commit);++ let _ = fs::remove_dir_all(root);+}++/// A superproject records its submodules' URLs in its own config. The submodule section comes+/// before the remote section when the repository gets its remote after its submodules, so the+/// reader has to know which section a URL sits in.+#[test]+fn test_get_git_info_from_a_real_superproject_reports_its_own_remote() {+ if !git_is_available() {+ eprintln!("skipping: git is not on PATH");+ return;+ }++ let _env_lock = lock_env();+ let _env_guard = EnvVarGuard::clear(GIT_INFO_ENV_VARS);++ let root = temp_root("real_superproject");+ let submodule_dir = root.join("submodule");+ init_repo_with_commit(&submodule_dir, None);++ let super_dir = root.join("superproject");+ let commit = init_repo_with_commit(&super_dir, None);+ git(&super_dir, &["reset", "-q", "--hard", "main"]);+ git(+ &super_dir,+ &[+ "-c",+ "protocol.file.allow=always",+ "submodule",+ "add",+ "-q",+ submodule_dir.to_str().unwrap(),+ "vendor/lib",+ ],+ );+ git(+ &super_dir,+ &[+ "remote",+ "add",+ "origin",+ "https://github.com/PostHog/posthog.git",+ ],+ );++ let info = git_info_of(&super_dir);+ assert_eq!(info.branch, "main");+ assert_eq!(info.commit_id, commit);+ assert_eq!(+ info.remote_url.as_deref(),+ Some("https://github.com/PostHog/posthog.git"),+ "the superproject's own remote, not a submodule's"+ );+ assert_eq!(info.repo_name.as_deref(), Some("posthog"));++ let _ = fs::remove_dir_all(root);+}+#[test]fn test_get_git_info_from_vercel_env() {let info = get_git_info_from_env(env_from([