Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix: use --show-toplevel for repo_path() to support submodules (#762)

lajarre890c08ca2559
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 09e9d3f87..cafc54bd0 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -314,25 +314,60 @@ impl Repository {
self.git_common_dir().join("wt-logs")
}
- /// The repository root path.
+ /// The repository root path (the main worktree directory).
///
- /// For normal repositories: the main worktree directory (parent of .git).
- /// For bare repositories: the bare repository directory itself.
+ /// - Normal repositories: the main worktree directory (parent of .git)
+ /// - Bare repositories: the bare repository directory itself
+ /// - Submodules: the submodule's worktree (e.g., `/parent/sub`, not `/parent/.git/modules/sub`)
///
/// This is the base for template expansion (`{{ repo }}`, `{{ repo_path }}`).
/// NOT necessarily where established files live — use `primary_worktree()` for that.
///
/// Result is cached in the repository's shared cache (same for all clones).
+ ///
+ /// # Why we run from `git_common_dir`
+ ///
+ /// We need to return the *main* worktree regardless of which worktree we were discovered
+ /// from. For linked worktrees, `git_common_dir` is the stable reference that's shared
+ /// across all worktrees (e.g., `/myapp/.git` whether you're in `/myapp` or `/myapp.feature`).
+ ///
+ /// # Why the try-fallback approach
+ ///
+ /// `--show-toplevel` behavior depends on whether git has explicit worktree metadata:
+ ///
+ /// | git_common_dir location | Has `core.worktree`? | `--show-toplevel` works? |
+ /// |----------------------------|----------------------|--------------------------|
+ /// | Normal `.git` | No (implicit) | No — "not a work tree" |
+ /// | Submodule `.git/modules/X` | Yes (explicit) | Yes — reads config |
+ ///
+ /// Normal repos don't need `core.worktree` because the worktree is implicitly `parent(.git)`.
+ /// Submodules need it because their git data lives in the parent's `.git/modules/`.
+ ///
+ /// So we try `--show-toplevel` first (handles submodules), fall back to `parent()` (handles
+ /// normal repos). This avoids fragile path-based detection of submodules.
pub fn repo_path(&self) -> &Path {
self.cache.repo_path.get_or_init(|| {
+ // Bare repos have no worktree — the git directory IS the repo
if self.is_bare() {
- self.git_common_dir.clone()
- } else {
- self.git_common_dir
- .parent()
- .expect("Git directory has no parent")
- .to_path_buf()
+ return self.git_common_dir.clone();
}
+
+ // Submodules: --show-toplevel succeeds (git has explicit core.worktree config)
+ if let Ok(out) = Cmd::new("git")
+ .args(["rev-parse", "--show-toplevel"])
+ .current_dir(&self.git_common_dir)
+ .context(path_to_logging_context(&self.git_common_dir))
+ .run()
+ && out.status.success()
+ {
+ return PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
+ }
+
+ // Normal repos: --show-toplevel fails from inside .git, use implicit relationship
+ self.git_common_dir
+ .parent()
+ .expect("Git directory has no parent")
+ .to_path_buf()
})
}
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index ca33a89fd..0ed3a7f52 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -501,3 +501,157 @@ fn test_integration_functions_handle_remote_refs() {
assert!(repository.same_commit("origin/main", "main").unwrap());
assert!(repository.is_ancestor("origin/main", "main").unwrap());
}
+
+// =============================================================================
+// Bug: repo_path() inside git submodules
+// =============================================================================
+
+/// Test that `repo_path()` returns the correct working directory when run inside
+/// a git submodule.
+///
+/// Previously, `repo_path()` derived the path from `git_common_dir.parent()`, which
+/// fails for submodules where git data is stored in `parent/.git/modules/sub`.
+/// The fix tries `git rev-parse --show-toplevel` first (works for submodules),
+/// falling back to parent of git_common_dir for normal repos.
+#[test]
+fn test_repo_path_in_submodule() {
+ use tempfile::TempDir;
+
+ // Create parent repository
+ let parent_temp = TempDir::new().unwrap();
+ let parent_path = parent_temp.path().join("parent");
+ fs::create_dir(&parent_path).unwrap();
+
+ // Initialize parent repo with git config
+ let mut cmd = std::process::Command::new("git");
+ cmd.args(["init", "-q"])
+ .current_dir(&parent_path)
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .env("GIT_CONFIG_GLOBAL", "/dev/null");
+ let output = cmd.output().unwrap();
+ assert!(output.status.success(), "git init failed for parent");
+
+ // Configure git user for commits
+ std::process::Command::new("git")
+ .args(["config", "user.email", "[email protected]"])
+ .current_dir(&parent_path)
+ .output()
+ .unwrap();
+ std::process::Command::new("git")
+ .args(["config", "user.name", "Test User"])
+ .current_dir(&parent_path)
+ .output()
+ .unwrap();
+
+ // Create initial commit in parent
+ fs::write(parent_path.join("README.md"), "# Parent").unwrap();
+ std::process::Command::new("git")
+ .args(["add", "."])
+ .current_dir(&parent_path)
+ .output()
+ .unwrap();
+ std::process::Command::new("git")
+ .args(["commit", "-m", "Initial commit"])
+ .current_dir(&parent_path)
+ .output()
+ .unwrap();
+
+ // Create submodule repository (as a separate repo first)
+ let sub_temp = TempDir::new().unwrap();
+ let sub_origin_path = sub_temp.path().join("submodule-origin");
+ fs::create_dir(&sub_origin_path).unwrap();
+
+ let mut cmd = std::process::Command::new("git");
+ cmd.args(["init", "-q"])
+ .current_dir(&sub_origin_path)
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .env("GIT_CONFIG_GLOBAL", "/dev/null");
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "git init failed for submodule origin"
+ );
+
+ // Configure git user for submodule
+ std::process::Command::new("git")
+ .args(["config", "user.email", "[email protected]"])
+ .current_dir(&sub_origin_path)
+ .output()
+ .unwrap();
+ std::process::Command::new("git")
+ .args(["config", "user.name", "Test User"])
+ .current_dir(&sub_origin_path)
+ .output()
+ .unwrap();
+
+ // Create initial commit in submodule origin
+ fs::write(sub_origin_path.join("README.md"), "# Submodule").unwrap();
+ std::process::Command::new("git")
+ .args(["add", "."])
+ .current_dir(&sub_origin_path)
+ .output()
+ .unwrap();
+ std::process::Command::new("git")
+ .args(["commit", "-m", "Submodule initial commit"])
+ .current_dir(&sub_origin_path)
+ .output()
+ .unwrap();
+
+ // Add submodule to parent (using local path directly, with file transport allowed)
+ let output = std::process::Command::new("git")
+ .args([
+ "-c",
+ "protocol.file.allow=always",
+ "submodule",
+ "add",
+ sub_origin_path.to_str().unwrap(),
+ "sub",
+ ])
+ .current_dir(&parent_path)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "git submodule add failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Commit the submodule addition
+ std::process::Command::new("git")
+ .args(["commit", "-m", "Add submodule"])
+ .current_dir(&parent_path)
+ .output()
+ .unwrap();
+
+ // Now test: create Repository from inside the submodule
+ let submodule_path = parent_path.join("sub");
+ assert!(
+ submodule_path.exists(),
+ "Submodule path should exist: {:?}",
+ submodule_path
+ );
+
+ let repository = Repository::at(submodule_path.clone()).unwrap();
+
+ // The key assertion: repo_path() should return the submodule's working directory,
+ // NOT something like parent/.git/modules/sub
+ let repo_path = repository.repo_path();
+
+ // Canonicalize both paths for comparison (handles symlinks like /var -> /private/var on macOS)
+ let expected = dunce::canonicalize(&submodule_path).unwrap();
+ let actual = dunce::canonicalize(repo_path).unwrap();
+
+ assert_eq!(
+ actual, expected,
+ "repo_path() should return submodule's working directory ({:?}), not git modules path",
+ expected
+ );
+
+ // Also verify that git_common_dir is in the parent's .git/modules/ (confirming this is a real submodule)
+ let git_common_dir = repository.git_common_dir();
+ assert!(
+ git_common_dir.to_string_lossy().contains(".git/modules"),
+ "git_common_dir should be in parent's .git/modules/ for a submodule, got: {:?}",
+ git_common_dir
+ );
+}