Skip to content

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

Feat: Add `configure-shell` command to automate shell integration

Maximilian Roosd378fa7e7e63
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
new file mode 100644
index 000000000..8e14bdbff
--- /dev/null
+++ b/src/commands/configure_shell.rs
@@ -0,0 +1,271 @@
+use std::fs::{self, OpenOptions};
+use std::io::{BufRead, BufReader, Write};
+use std::path::{Path, PathBuf};
+use worktrunk::shell::Shell;
+
+pub struct ConfigureResult {
+ pub shell: Shell,
+ pub path: PathBuf,
+ pub action: ConfigAction,
+}
+
+#[derive(Debug, PartialEq)]
+pub enum ConfigAction {
+ Added,
+ AlreadyExists,
+ Created,
+ WouldAdd,
+ WouldCreate,
+}
+
+impl ConfigAction {
+ pub fn description(&self) -> &str {
+ match self {
+ ConfigAction::Added => "Added",
+ ConfigAction::AlreadyExists => "Already configured",
+ ConfigAction::Created => "Created",
+ ConfigAction::WouldAdd => "Would add to",
+ ConfigAction::WouldCreate => "Would create",
+ }
+ }
+}
+
+pub fn handle_configure_shell(
+ shell_filter: Option<Shell>,
+ cmd_prefix: &str,
+ dry_run: bool,
+) -> Result<Vec<ConfigureResult>, String> {
+ let shells = if let Some(shell) = shell_filter {
+ vec![shell]
+ } else {
+ // Try all shells in consistent order
+ vec![
+ Shell::Bash,
+ Shell::Zsh,
+ Shell::Fish,
+ Shell::Nushell,
+ Shell::Powershell,
+ Shell::Oil,
+ Shell::Elvish,
+ Shell::Xonsh,
+ ]
+ };
+
+ let mut results = Vec::new();
+ let mut checked_paths = Vec::new();
+
+ for shell in shells {
+ let paths = shell.config_paths(cmd_prefix);
+
+ // Find the first existing config file
+ let target_path = paths.iter().find(|p| p.exists());
+
+ // Track all checked paths for better error messages
+ checked_paths.extend(paths.iter().map(|p| (shell, p.clone())));
+
+ // Only configure if explicitly targeting this shell OR if config file exists
+ let should_configure = shell_filter.is_some() || target_path.is_some();
+
+ if should_configure {
+ let path = target_path.or_else(|| paths.first());
+ if let Some(path) = path {
+ match configure_shell_file(shell, path, cmd_prefix, dry_run, shell_filter.is_some())
+ {
+ Ok(Some(result)) => results.push(result),
+ Ok(None) => {} // No action needed
+ Err(e) => {
+ // For non-critical errors, we could continue with other shells
+ // but for now we'll fail fast
+ return Err(format!("Failed to configure {}: {}", shell, e));
+ }
+ }
+ }
+ }
+ }
+
+ if results.is_empty() && shell_filter.is_none() {
+ // Provide helpful error message with checked locations
+ let example_paths: Vec<String> = checked_paths
+ .iter()
+ .take(3)
+ .map(|(_, p)| p.display().to_string())
+ .collect();
+
+ return Err(format!(
+ "No shell config files found in $HOME. Checked: {}, and more. Create a config file or use --shell to specify a shell.",
+ example_paths.join(", ")
+ ));
+ }
+
+ Ok(results)
+}
+
+fn configure_shell_file(
+ shell: Shell,
+ path: &Path,
+ cmd_prefix: &str,
+ dry_run: bool,
+ explicit_shell: bool,
+) -> Result<Option<ConfigureResult>, String> {
+ let config_content = shell.config_line(cmd_prefix);
+
+ // For Fish, we write to a separate conf.d/ file
+ if matches!(shell, Shell::Fish) {
+ return configure_fish_file(
+ shell,
+ path,
+ &config_content,
+ cmd_prefix,
+ dry_run,
+ explicit_shell,
+ );
+ }
+
+ // For other shells, check if file exists
+ if path.exists() {
+ // Read the file and check if our integration already exists
+ let file = fs::File::open(path)
+ .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
+
+ let reader = BufReader::new(file);
+
+ // More precise pattern matching for the eval statement
+ let eval_pattern = format!("eval \"$({} init", cmd_prefix);
+ let eval_pattern_single_quote = format!("eval '$({} init", cmd_prefix);
+
+ for line in reader.lines() {
+ let line = line.map_err(|e| format!("Failed to read line: {}", e))?;
+ let trimmed = line.trim();
+
+ // Check for the actual eval statement, not just any mention of "wt init"
+ if trimmed.starts_with(&eval_pattern) || trimmed.starts_with(&eval_pattern_single_quote)
+ {
+ return Ok(Some(ConfigureResult {
+ shell,
+ path: path.to_path_buf(),
+ action: ConfigAction::AlreadyExists,
+ }));
+ }
+ }
+
+ // Line doesn't exist, add it
+ if dry_run {
+ return Ok(Some(ConfigureResult {
+ shell,
+ path: path.to_path_buf(),
+ action: ConfigAction::WouldAdd,
+ }));
+ }
+
+ // Append the line with proper spacing
+ let mut file = OpenOptions::new()
+ .append(true)
+ .open(path)
+ .map_err(|e| format!("Failed to open {} for writing: {}", path.display(), e))?;
+
+ // Add blank line before config, then the config line with its own newline
+ write!(file, "\n{}\n", config_content)
+ .map_err(|e| format!("Failed to write to {}: {}", path.display(), e))?;
+
+ Ok(Some(ConfigureResult {
+ shell,
+ path: path.to_path_buf(),
+ action: ConfigAction::Added,
+ }))
+ } else {
+ // File doesn't exist
+ // Only create if explicitly targeting this shell
+ if explicit_shell {
+ if dry_run {
+ return Ok(Some(ConfigureResult {
+ shell,
+ path: path.to_path_buf(),
+ action: ConfigAction::WouldCreate,
+ }));
+ }
+
+ // Create parent directories if they don't exist
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).map_err(|e| {
+ format!("Failed to create directory {}: {}", parent.display(), e)
+ })?;
+ }
+
+ // Write the config content
+ fs::write(path, format!("{}\n", config_content))
+ .map_err(|e| format!("Failed to write to {}: {}", path.display(), e))?;
+
+ Ok(Some(ConfigureResult {
+ shell,
+ path: path.to_path_buf(),
+ action: ConfigAction::Created,
+ }))
+ } else {
+ // Don't create config files for shells the user might not use
+ Ok(None)
+ }
+ }
+}
+
+fn configure_fish_file(
+ shell: Shell,
+ path: &Path,
+ content: &str,
+ cmd_prefix: &str,
+ dry_run: bool,
+ explicit_shell: bool,
+) -> Result<Option<ConfigureResult>, String> {
+ // For Fish, we write to conf.d/{cmd_prefix}.fish (separate file)
+
+ // Check if it already exists and has our integration
+ if path.exists() {
+ let existing_content = fs::read_to_string(path)
+ .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
+
+ // Check for specific patterns that indicate our integration is present
+ let function_pattern = format!("function {}", cmd_prefix);
+ let has_integration = existing_content.contains(&function_pattern);
+
+ if has_integration {
+ return Ok(Some(ConfigureResult {
+ shell,
+ path: path.to_path_buf(),
+ action: ConfigAction::AlreadyExists,
+ }));
+ }
+ }
+
+ // File doesn't exist or doesn't have our integration
+ // Only create if explicitly targeting this shell (consistent with other shells)
+ if !explicit_shell && !path.exists() {
+ return Ok(None);
+ }
+
+ if dry_run {
+ return Ok(Some(ConfigureResult {
+ shell,
+ path: path.to_path_buf(),
+ action: if path.exists() {
+ ConfigAction::WouldAdd
+ } else {
+ ConfigAction::WouldCreate
+ },
+ }));
+ }
+
+ // Create parent directories if they don't exist
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("Failed to create directory {}: {}", parent.display(), e))?;
+ }
+
+ // Write the full content
+ fs::write(path, content)
+ .map_err(|e| format!("Failed to write to {}: {}", path.display(), e))?;
+
+ Ok(Some(ConfigureResult {
+ shell,
+ path: path.to_path_buf(),
+ action: ConfigAction::Created,
+ }))
+}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index ae8bb0846..d9aa2fed8 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -1,10 +1,12 @@
pub mod completion;
+pub mod configure_shell;
pub mod init;
pub mod list;
pub mod merge;
pub mod worktree;
pub use completion::{handle_complete, handle_completion};
+pub use configure_shell::handle_configure_shell;
pub use init::handle_init;
pub use list::handle_list;
pub use merge::handle_merge;
diff --git a/src/main.rs b/src/main.rs
index bff75d68d..1f0f567b8 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -8,8 +8,8 @@ mod display;
mod llm;
use commands::{
- Shell, handle_complete, handle_completion, handle_init, handle_list, handle_merge, handle_push,
- handle_remove, handle_switch,
+ Shell, handle_complete, handle_completion, handle_configure_shell, handle_init, handle_list,
+ handle_merge, handle_push, handle_remove, handle_switch,
};
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
@@ -42,6 +42,21 @@ enum Commands {
cmd: String,
},
+ /// Configure shell by writing to config files
+ ConfigureShell {
+ /// Specific shell to configure (default: all shells with existing config files)
+ #[arg(long, value_enum)]
+ shell: Option<Shell>,
+
+ /// Command prefix (default: wt)
+ #[arg(long, default_value = "wt")]
+ cmd: String,
+
+ /// Show what would be done without making changes
+ #[arg(long)]
+ dry_run: bool,
+ },
+
/// List all worktrees
List {
/// Output format
@@ -123,6 +138,22 @@ fn main() {
let mut cli_cmd = Cli::command();
handle_init(&shell, &cmd, &mut cli_cmd).map_err(GitError::CommandFailed)
}
+ Commands::ConfigureShell {
+ shell,
+ cmd,
+ dry_run,
+ } => handle_configure_shell(shell, &cmd, dry_run)
+ .map(|results| {
+ for result in results {
+ println!(
+ "{:12} {} {}",
+ result.action.description(),
+ result.shell,
+ result.path.display()
+ );
+ }
+ })
+ .map_err(GitError::CommandFailed),
Commands::List { format } => handle_list(format),
Commands::Switch {
branch,
diff --git a/src/shell.rs b/src/shell.rs
index 7021be781..0f92f27b6 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -1,5 +1,6 @@
use askama::Template;
use std::fmt;
+use std::path::PathBuf;
/// Supported shells
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
@@ -52,6 +53,93 @@ impl Shell {
pub fn supports_completion(&self) -> bool {
matches!(self, Self::Bash | Self::Fish | Self::Zsh | Self::Oil)
}
+
+ /// Returns the standard config file paths for this shell
+ ///
+ /// Returns paths in order of preference. The first existing file should be used.
+ /// For Fish, the cmd_prefix is used to name the conf.d file.
+ pub fn config_paths(&self, cmd_prefix: &str) -> Vec<PathBuf> {
+ let home = PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".to_string()));
+
+ match self {
+ Self::Bash => {
+ // macOS uses .bash_profile, Linux typically uses .bashrc
+ if cfg!(target_os = "macos") {
+ vec![home.join(".bash_profile"), home.join(".profile")]
+ } else {
+ vec![home.join(".bashrc"), home.join(".bash_profile")]
+ }
+ }
+ Self::Zsh => {
+ let zdotdir = std::env::var("ZDOTDIR")
+ .map(PathBuf::from)
+ .unwrap_or_else(|_| home.clone());
+ vec![zdotdir.join(".zshrc")]
+ }
+ Self::Fish => {
+ // For fish, we write to conf.d/ which is auto-sourced
+ // Use cmd_prefix in the filename
+ vec![
+ home.join(".config")
+ .join("fish")
+ .join("conf.d")
+ .join(format!("{}.fish", cmd_prefix)),
+ ]
+ }
+ Self::Nushell => {
+ vec![home.join(".config").join("nushell").join("config.nu")]
+ }
+ Self::Powershell => {
+ if cfg!(target_os = "windows") {
+ let userprofile = PathBuf::from(
+ std::env::var("USERPROFILE").unwrap_or_else(|_| ".".to_string()),
+ );
+ vec![
+ userprofile
+ .join("Documents")
+ .join("PowerShell")
+ .join("Microsoft.PowerShell_profile.ps1"),
+ ]
+ } else {
+ vec![
+ home.join(".config")
+ .join("powershell")
+ .join("Microsoft.PowerShell_profile.ps1"),
+ ]
+ }
+ }
+ Self::Oil => {
+ vec![home.join(".config").join("oil").join("oshrc")]
+ }
+ Self::Elvish => {
+ vec![home.join(".config").join("elvish").join("rc.elv")]
+ }
+ Self::Xonsh => {
+ vec![home.join(".xonshrc")]
+ }
+ }
+ }
+
+ /// Returns the line to add to the config file for shell integration
+ ///
+ /// For most shells, this is an eval statement. For Fish, this returns
+ /// the full integration code since it goes into a separate conf.d/ file.
+ pub fn config_line(&self, cmd_prefix: &str) -> String {
+ match self {
+ Self::Fish => {
+ // Fish uses a separate file in conf.d/, so we generate the full content
+ ShellInit::new(*self, cmd_prefix.to_string())
+ .generate()
+ .unwrap_or_else(|_| {
+ format!("# Error generating fish config for {}", cmd_prefix)
+ })
+ }
+ _ => {
+ // All other shells use eval pattern
+ format!("eval \"$({} init {})\"", cmd_prefix, self)
+ }
+ }
+ }
}
/// Shell integration configuration
diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rs
new file mode 100644
index 000000000..4cee75dd5
--- /dev/null
+++ b/tests/integration_tests/configure_shell.rs
@@ -0,0 +1,268 @@
+use crate::common::TestRepo;
+use insta::Settings;
+use insta_cmd::{assert_cmd_snapshot, get_cargo_bin};
+use std::fs;
+use std::process::Command;
+use tempfile::TempDir;
+
+/// Test configure-shell with dry-run flag
+#[test]
+fn test_configure_shell_dry_run() {
+ let repo = TestRepo::new();
+ let temp_home = TempDir::new().unwrap();
+
+ // Create a fake .zshrc file
+ let zshrc_path = temp_home.path().join(".zshrc");
+ fs::write(&zshrc_path, "# Existing config\n").unwrap();
+
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("configure-shell")
+ .arg("--dry-run")
+ .env("HOME", temp_home.path())
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!("configure_shell_dry_run", cmd);
+ });
+}
+
+/// Test configure-shell with specific shell
+#[test]
+fn test_configure_shell_specific_shell() {
+ let repo = TestRepo::new();
+ let temp_home = TempDir::new().unwrap();
+
+ // Create a fake .zshrc file
+ let zshrc_path = temp_home.path().join(".zshrc");
+ fs::write(&zshrc_path, "# Existing config\n").unwrap();
+
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("configure-shell")
+ .arg("--shell")
+ .arg("zsh")
+ .env("HOME", temp_home.path())
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!("configure_shell_zsh", cmd);
+ });
+
+ // Verify the file was modified
+ let content = fs::read_to_string(&zshrc_path).unwrap();
+ assert!(content.contains("eval \"$(wt init zsh)\""));
+}
+
+/// Test configure-shell when line already exists
+#[test]
+fn test_configure_shell_already_exists() {
+ let repo = TestRepo::new();
+ let temp_home = TempDir::new().unwrap();
+
+ // Create a fake .zshrc file with the line already present
+ let zshrc_path = temp_home.path().join(".zshrc");
+ fs::write(&zshrc_path, "# Existing config\neval \"$(wt init zsh)\"\n").unwrap();
+
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("configure-shell")
+ .arg("--shell")
+ .arg("zsh")
+ .env("HOME", temp_home.path())
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!("configure_shell_already_exists", cmd);
+ });
+
+ // Verify the file was not modified (no duplicate)
+ let content = fs::read_to_string(&zshrc_path).unwrap();
+ let count = content.matches("wt init").count();
+ assert_eq!(count, 1, "Should only have one wt init line");
+}
+
+/// Test configure-shell with custom command prefix
+#[test]
+fn test_configure_shell_custom_prefix() {
+ let repo = TestRepo::new();
+ let temp_home = TempDir::new().unwrap();
+
+ // Create the appropriate bash config file based on platform
+ let bash_config_path = if cfg!(target_os = "macos") {
+ temp_home.path().join(".bash_profile")
+ } else {
+ temp_home.path().join(".bashrc")
+ };
+ fs::write(&bash_config_path, "# Existing config\n").unwrap();
+
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("configure-shell")
+ .arg("--shell")
+ .arg("bash")
+ .arg("--cmd")
+ .arg("worktree")
+ .env("HOME", temp_home.path())
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!("configure_shell_custom_prefix", cmd);
+ });
+
+ // Verify the file has the custom prefix
+ let content = fs::read_to_string(&bash_config_path).unwrap();
+ assert!(content.contains("eval \"$(worktree init bash)\""));
+}
+
+/// Test configure-shell for Fish (creates new file in conf.d/)
+#[test]
+fn test_configure_shell_fish() {
+ let repo = TestRepo::new();
+ let temp_home = TempDir::new().unwrap();
+
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("configure-shell")
+ .arg("--shell")
+ .arg("fish")
+ .env("HOME", temp_home.path())
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!("configure_shell_fish", cmd);
+ });
+
+ // Verify the fish conf.d file was created
+ let fish_config = temp_home.path().join(".config/fish/conf.d/wt.fish");
+ assert!(fish_config.exists(), "Fish config file should be created");
+
+ let content = fs::read_to_string(&fish_config).unwrap();
+ assert!(
+ content.contains("function wt"),
+ "Should contain wt function"
+ );
+}
+
+/// Test configure-shell when no config files exist
+#[test]
+fn test_configure_shell_no_files() {
+ let repo = TestRepo::new();
+ let temp_home = TempDir::new().unwrap();
+
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("configure-shell")
+ .env("HOME", temp_home.path())
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!("configure_shell_no_files", cmd);
+ });
+}
+
+/// Test configure-shell for Fish with custom prefix
+#[test]
+fn test_configure_shell_fish_custom_prefix() {
+ let repo = TestRepo::new();
+ let temp_home = TempDir::new().unwrap();
+
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("configure-shell")
+ .arg("--shell")
+ .arg("fish")
+ .arg("--cmd")
+ .arg("worktree")
+ .env("HOME", temp_home.path())
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!("configure_shell_fish_custom_prefix", cmd);
+ });
+
+ // Verify the fish conf.d file was created with correct prefix in filename
+ let fish_config = temp_home.path().join(".config/fish/conf.d/worktree.fish");
+ assert!(
+ fish_config.exists(),
+ "Fish config file should be created with custom prefix in filename"
+ );
+
+ let content = fs::read_to_string(&fish_config).unwrap();
+ assert!(
+ content.contains("function worktree"),
+ "Should contain worktree function with custom prefix"
+ );
+}
+
+/// Test configure-shell with multiple existing config files
+#[test]
+fn test_configure_shell_multiple_configs() {
+ let repo = TestRepo::new();
+ let temp_home = TempDir::new().unwrap();
+
+ // Create multiple shell config files (platform-aware for Bash)
+ let bash_config_path = if cfg!(target_os = "macos") {
+ temp_home.path().join(".bash_profile")
+ } else {
+ temp_home.path().join(".bashrc")
+ };
+ let zshrc_path = temp_home.path().join(".zshrc");
+ fs::write(&bash_config_path, "# Existing bash config\n").unwrap();
+ fs::write(&zshrc_path, "# Existing zsh config\n").unwrap();
+
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ settings.add_filter(&temp_home.path().to_string_lossy(), "[TEMP_HOME]");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("configure-shell")
+ .env("HOME", temp_home.path())
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!("configure_shell_multiple_configs", cmd);
+ });
+
+ // Verify both files were modified
+ let bash_content = fs::read_to_string(&bash_config_path).unwrap();
+ assert!(
+ bash_content.contains("eval \"$(wt init bash)\""),
+ "Bash config should be updated"
+ );
+
+ let zsh_content = fs::read_to_string(&zshrc_path).unwrap();
+ assert!(
+ zsh_content.contains("eval \"$(wt init zsh)\""),
+ "Zsh config should be updated"
+ );
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index 619f5dbaa..461cf62d5 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -1,4 +1,5 @@
pub mod completion;
+pub mod configure_shell;
pub mod default_branch;
pub mod directives;
pub mod e2e_shell;
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_already_exists.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_already_exists.snap
new file mode 100644
index 000000000..411bd0a91
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_already_exists.snap
@@ -0,0 +1,26 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ - "--shell"
+ - zsh
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpwfHd1M
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Already configured zsh [TEMP_HOME]/.zshrc
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_custom_prefix.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_custom_prefix.snap
new file mode 100644
index 000000000..9c6d1fc32
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_custom_prefix.snap
@@ -0,0 +1,28 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ - "--shell"
+ - bash
+ - "--cmd"
+ - worktree
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpb4zFg2
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Added bash [TEMP_HOME]/.bash_profile
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_dry_run.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_dry_run.snap
new file mode 100644
index 000000000..f50241474
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_dry_run.snap
@@ -0,0 +1,25 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ - "--dry-run"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnODeol
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Would add to zsh [TEMP_HOME]/.zshrc
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish.snap
new file mode 100644
index 000000000..a7d5de0e8
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish.snap
@@ -0,0 +1,26 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ - "--shell"
+ - fish
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpkyQDxi
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Created fish [TEMP_HOME]/.config/fish/conf.d/wt.fish
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_custom_prefix.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_custom_prefix.snap
new file mode 100644
index 000000000..af8676afa
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_custom_prefix.snap
@@ -0,0 +1,28 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ - "--shell"
+ - fish
+ - "--cmd"
+ - worktree
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp34TZwb
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Created fish [TEMP_HOME]/.config/fish/conf.d/worktree.fish
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_multiple_configs.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_multiple_configs.snap
new file mode 100644
index 000000000..1bf9c89d6
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_multiple_configs.snap
@@ -0,0 +1,25 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpybQMOW
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Added bash [TEMP_HOME]/.bash_profile
+Added zsh [TEMP_HOME]/.zshrc
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_no_files.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_no_files.snap
new file mode 100644
index 000000000..ed5335a3b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_no_files.snap
@@ -0,0 +1,24 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpQPnent
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+No shell config files found in $HOME. Checked: [TEMP_HOME]/.bash_profile, [TEMP_HOME]/.profile, [TEMP_HOME]/.zshrc, and more. Create a config file or use --shell to specify a shell.
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_zsh.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_zsh.snap
new file mode 100644
index 000000000..f93e83f37
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_zsh.snap
@@ -0,0 +1,26 @@
+---
+source: tests/integration_tests/configure_shell.rs
+info:
+ program: wt
+ args:
+ - configure-shell
+ - "--shell"
+ - zsh
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpuxXUM5
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Added zsh [TEMP_HOME]/.zshrc
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 94aa4fd86..5919c63e4 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -95,6 +95,9 @@ _wt() {
wt,completion)
cmd="wt__completion"
;;
+ wt,configure-shell)
+ cmd="wt__configure__shell"
+ ;;
wt,init)
cmd="wt__init"
;;
@@ -120,7 +123,7 @@ _wt() {
case "${cmd}" in
wt)
- opts="-h -V --help --version init list switch remove push merge completion complete"
+ opts="-h -V --help --version init configure-shell list switch remove push merge completion complete"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
@@ -161,6 +164,28 @@ _wt() {
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
;;
+ wt__configure__shell)
+ opts="-h --shell --cmd --dry-run --help"
+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ fi
+ case "${prev}" in
+ --shell)
+ COMPREPLY=($(compgen -W "bash elvish fish nushell oil powershell xonsh zsh" -- "${cur}"))
+ return 0
+ ;;
+ --cmd)
+ COMPREPLY=($(compgen -f "${cur}"))
+ return 0
+ ;;
+ *)
+ COMPREPLY=()
+ ;;
+ esac
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ ;;
wt__init)
opts="-h --cmd --help <SHELL>"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
index 3f3d4027d..e0b5355cd 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
@@ -97,6 +97,9 @@ _wt() {
wt,completion)
cmd="wt__completion"
;;
+ wt,configure-shell)
+ cmd="wt__configure__shell"
+ ;;
wt,init)
cmd="wt__init"
;;
@@ -122,7 +125,7 @@ _wt() {
case "${cmd}" in
wt)
- opts="-h -V --help --version init list switch remove push merge completion complete"
+ opts="-h -V --help --version init configure-shell list switch remove push merge completion complete"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
@@ -163,6 +166,28 @@ _wt() {
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
;;
+ wt__configure__shell)
+ opts="-h --shell --cmd --dry-run --help"
+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ fi
+ case "${prev}" in
+ --shell)
+ COMPREPLY=($(compgen -W "bash elvish fish nushell oil powershell xonsh zsh" -- "${cur}"))
+ return 0
+ ;;
+ --cmd)
+ COMPREPLY=($(compgen -f "${cur}"))
+ return 0
+ ;;
+ *)
+ COMPREPLY=()
+ ;;
+ esac
+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
+ return 0
+ ;;
wt__init)
opts="-h --cmd --help <SHELL>"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 17067d472..0735d96cf 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -97,6 +97,7 @@ end
complete -c wt -n "__fish_wt_needs_command" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_needs_command" -s V -l version -d 'Print version'
complete -c wt -n "__fish_wt_needs_command" -f -a "init" -d 'Generate shell integration code'
+complete -c wt -n "__fish_wt_needs_command" -f -a "configure-shell" -d 'Configure shell by writing to config files'
complete -c wt -n "__fish_wt_needs_command" -f -a "list" -d 'List all worktrees'
complete -c wt -n "__fish_wt_needs_command" -f -a "switch" -d 'Switch to a worktree'
complete -c wt -n "__fish_wt_needs_command" -f -a "remove" -d 'Finish current worktree, returning to primary if current'
@@ -104,6 +105,17 @@ complete -c wt -n "__fish_wt_needs_command" -f -a "push" -d 'Push changes betwee
complete -c wt -n "__fish_wt_needs_command" -f -a "merge" -d 'Merge worktree into target branch'
complete -c wt -n "__fish_wt_using_subcommand init" -l cmd -d 'Command prefix (default: wt)' -r
complete -c wt -n "__fish_wt_using_subcommand init" -s h -l help -d 'Print help'
+complete -c wt -n "__fish_wt_using_subcommand configure-shell" -l shell -d 'Specific shell to configure (default: all shells with existing config files)' -r -f -a "bash\t''
+elvish\t''
+fish\t''
+nushell\t''
+oil\t''
+powershell\t''
+xonsh\t''
+zsh\t''"
+complete -c wt -n "__fish_wt_using_subcommand configure-shell" -l cmd -d 'Command prefix (default: wt)' -r
+complete -c wt -n "__fish_wt_using_subcommand configure-shell" -l dry-run -d 'Show what would be done without making changes'
+complete -c wt -n "__fish_wt_using_subcommand configure-shell" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand list" -l format -d 'Output format' -r -f -a "table\t'Human-readable table format'
json\t'JSON format'"
complete -c wt -n "__fish_wt_using_subcommand list" -s h -l help -d 'Print help (see more with \'--help\')'
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index fbcab426e..efd567808 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -109,6 +109,15 @@ _arguments "${_arguments_options[@]}" : \
':shell -- Shell to generate code for (bash, fish, zsh):_default' \
&& ret=0
;;
+(configure-shell)
+_arguments "${_arguments_options[@]}" : \
+'--shell=[Specific shell to configure (default\: all shells with existing config files)]:SHELL:(bash elvish fish nushell oil powershell xonsh zsh)' \
+'--cmd=[Command prefix (default\: wt)]:CMD:_default' \
+'--dry-run[Show what would be done without making changes]' \
+'-h[Print help]' \
+'--help[Print help]' \
+&& ret=0
+;;
(list)
_arguments "${_arguments_options[@]}" : \
'--format=[Output format]:FORMAT:((table\:"Human-readable table format"
@@ -178,6 +187,7 @@ esac
_wt_commands() {
local commands; commands=(
'init:Generate shell integration code' \
+'configure-shell:Configure shell by writing to config files' \
'list:List all worktrees' \
'switch:Switch to a worktree' \
'remove:Finish current worktree, returning to primary if current' \
@@ -198,6 +208,11 @@ _wt__completion_commands() {
local commands; commands=()
_describe -t commands 'wt completion commands' commands "$@"
}
+(( $+functions[_wt__configure-shell_commands] )) ||
+_wt__configure-shell_commands() {
+ local commands; commands=()
+ _describe -t commands 'wt configure-shell commands' commands "$@"
+}
(( $+functions[_wt__init_commands] )) ||
_wt__init_commands() {
local commands; commands=()