Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor: Improve completion filtering and add validation tests
Maximilian Roos4acfd0459fa8
diff --git a/src/commands/init.rs b/src/commands/init.rsindex 557f7d2ab..dc41b0677 100644--- a/src/commands/init.rs+++ b/src/commands/init.rs@@ -36,20 +36,39 @@ pub fn handle_init(shell_name: &str, cmd_name: &str, cli_cmd: &mut Command) -> R};generate(completion_shell, cli_cmd, "wt", &mut completion_output);- // Filter out lines for hidden commands (completion, complete)+ // Filter out lines for hidden commands (completion, complete) and hidden flags (--internal)let completion_str = String::from_utf8_lossy(&completion_output);- let filtered: Vec<&str> = completion_str- .lines()- .filter(|line| {- // Remove lines that complete the hidden commands- !(line.contains("\"completion\"")- || line.contains("\"complete\"")- || line.contains("-a \"completion\"")- || line.contains("-a \"complete\""))- })- .collect();-- for line in filtered {++ for line in completion_str.lines() {+ // Skip lines that complete the hidden commands+ if line.contains("\"completion\"")+ || line.contains("\"complete\"")+ || line.contains("-a \"completion\"")+ || line.contains("-a \"complete\"")+ {+ continue;+ }++ // Skip lines that are specifically for completing --internal flag+ // But DON'T skip opts= lines that just mention --internal in the list+ if line.contains("-l internal") && !line.contains("opts=") {+ // Fish: complete -c wt ... -l internal ...+ continue;+ }+ if line.contains("'--internal[") {+ // Zsh: '--internal[Use internal mode]'+ continue;+ }++ // For bash opts= lines and zsh argument specs, remove --internal from the string+ let line = if line.contains("--internal") {+ // Bash: opts="-c -b --create --base --internal --help"+ // Remove --internal and -internal from opts strings+ line.replace(" --internal", "").replace("--internal ", "")+ } else {+ line.to_string()+ };+println!("{}", line);}diff --git a/templates/fish.fish b/templates/fish.fishindex 3ecfce15b..b23d6360e 100644--- a/templates/fish.fish+++ b/templates/fish.fish@@ -44,4 +44,3 @@ endcomplete -c {{ cmd_prefix }} -n '__fish_seen_subcommand_from switch' -f -a '(__{{ cmd_prefix }}_complete)' -d 'Branch'complete -c {{ cmd_prefix }} -n '__fish_seen_subcommand_from push' -f -a '(__{{ cmd_prefix }}_complete)' -d 'Target branch'complete -c {{ cmd_prefix }} -n '__fish_seen_subcommand_from merge' -f -a '(__{{ cmd_prefix }}_complete)' -d 'Target branch'-complete -c {{ cmd_prefix }} -l base -f -a '(__{{ cmd_prefix }}_complete)' -d 'Base branch'diff --git a/tests/integration_tests/completion_validation.rs b/tests/integration_tests/completion_validation.rsnew file mode 100644index 000000000..3fc004415--- /dev/null+++ b/tests/integration_tests/completion_validation.rs@@ -0,0 +1,327 @@+use assert_cmd::Command;+use std::collections::HashSet;++/// Issue found during validation+#[derive(Debug)]+struct Issue {+ shell: String,+ severity: Severity,+ category: Category,+ message: String,+}++#[derive(Debug, PartialEq)]+enum Severity {+ Error,+ Warning,+}++#[derive(Debug)]+enum Category {+ HiddenFlag,+ Consistency,+}++impl Issue {+ fn error(shell: impl Into<String>, category: Category, message: impl Into<String>) -> Self {+ Self {+ shell: shell.into(),+ severity: Severity::Error,+ category,+ message: message.into(),+ }+ }++ fn warning(shell: impl Into<String>, category: Category, message: impl Into<String>) -> Self {+ Self {+ shell: shell.into(),+ severity: Severity::Warning,+ category,+ message: message.into(),+ }+ }+}++/// Validate fish shell completions+fn validate_fish(content: &str) -> Vec<Issue> {+ let mut issues = Vec::new();++ // Check for hidden flags+ for line in content.lines() {+ if line.contains("complete -c wt") && line.contains("-l internal") {+ issues.push(Issue::error(+ "fish",+ Category::HiddenFlag,+ "Hidden flag --internal appears in completions",+ ));+ }+ }++ issues+}++/// Validate bash shell completions+fn validate_bash(content: &str) -> Vec<Issue> {+ let mut issues = Vec::new();++ // Check for hidden flags in opts strings+ // Note: We don't validate bash syntax here. If you need that, use shellcheck.+ // We only check that our filtering logic removed hidden flags.+ for line in content.lines() {+ if line.contains("opts=") && line.contains("--internal") {+ issues.push(Issue::error(+ "bash",+ Category::HiddenFlag,+ "Hidden flag --internal appears in opts",+ ));+ }+ }++ issues+}++/// Validate zsh shell completions+fn validate_zsh(content: &str) -> Vec<Issue> {+ let mut issues = Vec::new();++ // Check for hidden flags in argument specs+ for line in content.lines() {+ if line.contains("'--internal[") {+ issues.push(Issue::error(+ "zsh",+ Category::HiddenFlag,+ "Hidden flag --internal appears in completions",+ ));+ }+ }++ issues+}++/// Extract flags from shell completion content+fn extract_flags(content: &str, shell: &str) -> HashSet<String> {+ let mut flags = HashSet::new();++ match shell {+ "fish" => {+ // Only from 'complete -c wt' lines, not local variables+ for line in content.lines() {+ if line.contains("complete -c wt")+ && let Some(captures) = line.split("-l ").nth(1)+ && let Some(flag) = captures.split_whitespace().next()+ {+ flags.insert(flag.to_string());+ }+ }+ }+ "bash" => {+ // From opts= lines+ for line in content.lines() {+ if let Some(opts_start) = line.find("opts=\"") {+ // Find the closing quote+ let search_from = opts_start + 6;+ if let Some(rel_end) = line[search_from..].find('"') {+ let opts_end = search_from + rel_end;+ let opts_str = &line[search_from..opts_end];+ for word in opts_str.split_whitespace() {+ if let Some(flag) = word.strip_prefix("--") {+ flags.insert(flag.to_string());+ }+ }+ }+ }+ }+ // Also from case statements+ for line in content.lines() {+ if let Some(stripped) = line+ .trim()+ .strip_prefix("--")+ .and_then(|s| s.strip_suffix(')'))+ {+ flags.insert(stripped.to_string());+ }+ }+ }+ "zsh" => {+ // From _arguments lines+ for line in content.lines() {+ if let Some(start) = line.find("'--")+ && let Some(rest) = line[start + 3..].split(&['[', '='][..]).next()+ {+ flags.insert(rest.to_string());+ }+ }+ }+ _ => {}+ }++ flags+}++/// Validate cross-shell consistency+fn validate_cross_shell(fish_content: &str, bash_content: &str, zsh_content: &str) -> Vec<Issue> {+ let mut issues = Vec::new();++ let fish_flags = extract_flags(fish_content, "fish");+ let bash_flags = extract_flags(bash_content, "bash");+ let zsh_flags = extract_flags(zsh_content, "zsh");++ // Flags that should be hidden+ let hidden_flags: HashSet<String> = ["internal"].iter().map(|s| s.to_string()).collect();++ // Check if hidden flags appear anywhere+ for flag in &hidden_flags {+ let mut appears_in = Vec::new();+ if fish_flags.contains(flag) {+ appears_in.push("fish");+ }+ if bash_flags.contains(flag) {+ appears_in.push("bash");+ }+ if zsh_flags.contains(flag) {+ appears_in.push("zsh");+ }++ if !appears_in.is_empty() {+ issues.push(Issue::error(+ "cross-shell",+ Category::HiddenFlag,+ format!(+ "Hidden flag --{} appears in: {}",+ flag,+ appears_in.join(", ")+ ),+ ));+ }+ }++ // Check for flags missing from some shells+ // (only report if missing from multiple shells - single shell might be intentional)+ let all_flags: HashSet<_> = fish_flags+ .union(&bash_flags)+ .chain(zsh_flags.iter())+ .filter(|f| !hidden_flags.contains(*f))+ .collect();++ for flag in all_flags {+ let in_fish = fish_flags.contains(flag);+ let in_bash = bash_flags.contains(flag);+ let in_zsh = zsh_flags.contains(flag);++ let present_count = [in_fish, in_bash, in_zsh].iter().filter(|&&x| x).count();++ // Only warn if flag is in exactly one shell (likely a bug)+ // If it's in 2 shells, might be intentional+ if present_count == 1 {+ let mut missing = Vec::new();+ if !in_fish {+ missing.push("fish");+ }+ if !in_bash {+ missing.push("bash");+ }+ if !in_zsh {+ missing.push("zsh");+ }++ issues.push(Issue::warning(+ "cross-shell",+ Category::Consistency,+ format!("Flag --{} missing from: {}", flag, missing.join(", ")),+ ));+ }+ }++ issues+}++#[test]+fn test_completion_validation() {+ // Generate completions+ let fish_output = Command::cargo_bin("wt")+ .unwrap()+ .arg("init")+ .arg("fish")+ .output()+ .expect("Failed to generate fish completion");++ let bash_output = Command::cargo_bin("wt")+ .unwrap()+ .arg("init")+ .arg("bash")+ .output()+ .expect("Failed to generate bash completion");++ let zsh_output = Command::cargo_bin("wt")+ .unwrap()+ .arg("init")+ .arg("zsh")+ .output()+ .expect("Failed to generate zsh completion");++ assert!(fish_output.status.success());+ assert!(bash_output.status.success());+ assert!(zsh_output.status.success());++ let fish_content = String::from_utf8_lossy(&fish_output.stdout);+ let bash_content = String::from_utf8_lossy(&bash_output.stdout);+ let zsh_content = String::from_utf8_lossy(&zsh_output.stdout);++ // Run all validators+ let mut all_issues = Vec::new();+ all_issues.extend(validate_fish(&fish_content));+ all_issues.extend(validate_bash(&bash_content));+ all_issues.extend(validate_zsh(&zsh_content));+ all_issues.extend(validate_cross_shell(+ &fish_content,+ &bash_content,+ &zsh_content,+ ));++ // Separate errors and warnings+ let errors: Vec<_> = all_issues+ .iter()+ .filter(|i| i.severity == Severity::Error)+ .collect();+ let warnings: Vec<_> = all_issues+ .iter()+ .filter(|i| i.severity == Severity::Warning)+ .collect();++ // Report issues+ if !errors.is_empty() {+ eprintln!("\n{}", "=".repeat(80));+ eprintln!("COMPLETION VALIDATION ERRORS ({})", errors.len());+ eprintln!("{}", "=".repeat(80));+ for issue in &errors {+ eprintln!(+ "❌ [{}] {:?}: {}",+ issue.shell, issue.category, issue.message+ );+ }+ }++ if !warnings.is_empty() {+ eprintln!("\n{}", "=".repeat(80));+ eprintln!("COMPLETION VALIDATION WARNINGS ({})", warnings.len());+ eprintln!("{}", "=".repeat(80));+ for issue in &warnings {+ eprintln!(+ "⚠️ [{}] {:?}: {}",+ issue.shell, issue.category, issue.message+ );+ }+ }++ // Fail on errors only+ if !errors.is_empty() {+ panic!(+ "\n{} completion validation error(s) found - see output above",+ errors.len()+ );+ }++ if errors.is_empty() && warnings.is_empty() {+ println!("✅ All shell completions validated successfully!");+ }+}diff --git a/tests/integration_tests/init.rs b/tests/integration_tests/init.rsindex e1bb56568..25dfaca2c 100644--- a/tests/integration_tests/init.rs+++ b/tests/integration_tests/init.rs@@ -61,3 +61,30 @@ fn test_init_invalid_shell() {assert_cmd_snapshot!("init_invalid_shell", cmd);});}++#[test]+fn test_fish_no_duplicate_base_completion() {+ // Verify that the fish completion doesn't have duplicate entries for --base+ let repo = TestRepo::new();+ let mut cmd = Command::new(get_cargo_bin("wt"));+ repo.clean_cli_env(&mut cmd);+ cmd.arg("init").arg("fish").current_dir(repo.root_path());++ let output = cmd.output().expect("Failed to run wt init fish");+ let stdout = String::from_utf8_lossy(&output.stdout);++ // Count how many lines contain "complete -c wt" and "-l base"+ let base_completions: Vec<&str> = stdout+ .lines()+ .filter(|line| line.contains("complete -c wt") && line.contains("-l base"))+ .collect();++ // Should only have one completion for --base (from clap's static generation)+ assert_eq!(+ base_completions.len(),+ 1,+ "Expected exactly 1 completion for --base, but found {}:\n{}",+ base_completions.len(),+ base_completions.join("\n")+ );+}diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex 461cf62d5..e2b7a8a50 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -1,4 +1,5 @@pub mod completion;+pub mod completion_validation;pub mod configure_shell;pub mod default_branch;pub mod directives;diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 5919c63e4..d50b14a80 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -251,7 +251,7 @@ _wt() {return 0;;wt__remove)- opts="-h --internal --help"+ opts="-h --help"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0@@ -265,7 +265,7 @@ _wt() {return 0;;wt__switch)- opts="-c -b -h --create --base --internal --help <BRANCH>"+ opts="-c -b -h --create --base --help <BRANCH>"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snapindex e0b5355cd..3286ac704 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@@ -253,7 +253,7 @@ _wt() {return 0;;wt__remove)- opts="-h --internal --help"+ opts="-h --help"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0@@ -267,7 +267,7 @@ _wt() {return 0;;wt__switch)- opts="-c -b -h --create --base --internal --help <BRANCH>"+ opts="-c -b -h --create --base --help <BRANCH>"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex 0735d96cf..fb89db7d6 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -65,7 +65,6 @@ endcomplete -c wt -n '__fish_seen_subcommand_from switch' -f -a '(__wt_complete)' -d 'Branch'complete -c wt -n '__fish_seen_subcommand_from push' -f -a '(__wt_complete)' -d 'Target branch'complete -c wt -n '__fish_seen_subcommand_from merge' -f -a '(__wt_complete)' -d 'Target branch'-complete -c wt -l base -f -a '(__wt_complete)' -d 'Base branch'# Static completions (commands and flags)# Print an optspec for argparse to handle cmd's options that are independent of any subcommand.@@ -121,9 +120,7 @@ json\t'JSON format'"complete -c wt -n "__fish_wt_using_subcommand list" -s h -l help -d 'Print help (see more with \'--help\')'complete -c wt -n "__fish_wt_using_subcommand switch" -s b -l base -d 'Base branch to create from (only with --create)' -rcomplete -c wt -n "__fish_wt_using_subcommand switch" -s c -l create -d 'Create a new branch'-complete -c wt -n "__fish_wt_using_subcommand switch" -l internal -d 'Use internal mode (outputs directives for shell wrapper)'complete -c wt -n "__fish_wt_using_subcommand switch" -s h -l help -d 'Print help'-complete -c wt -n "__fish_wt_using_subcommand remove" -l internal -d 'Use internal mode (outputs directives for shell wrapper)'complete -c wt -n "__fish_wt_using_subcommand remove" -s h -l help -d 'Print help'complete -c wt -n "__fish_wt_using_subcommand push" -l allow-merge-commits -d 'Allow pushing merge commits (non-linear history)'complete -c wt -n "__fish_wt_using_subcommand push" -s h -l help -d 'Print help'diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex efd567808..630cc07ac 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -132,7 +132,6 @@ _arguments "${_arguments_options[@]}" : \'--base=[Base branch to create from (only with --create)]:BASE:_default' \'-c[Create a new branch]' \'--create[Create a new branch]' \-'--internal[Use internal mode (outputs directives for shell wrapper)]' \'-h[Print help]' \'--help[Print help]' \':branch -- Branch name or worktree path:_default' \@@ -140,7 +139,6 @@ _arguments "${_arguments_options[@]}" : \;;(remove)_arguments "${_arguments_options[@]}" : \-'--internal[Use internal mode (outputs directives for shell wrapper)]' \'-h[Print help]' \'--help[Print help]' \&& ret=0