cascade_cli/cli/commands/
hooks.rs

1use crate::cli::output::Output;
2use crate::config::Settings;
3use crate::errors::{CascadeError, Result};
4use crate::git::find_repository_root;
5use dialoguer::{theme::ColorfulTheme, Confirm};
6use std::env;
7use std::fs;
8use std::path::{Path, PathBuf};
9use std::process::Command;
10
11/// Git repository type detection
12#[derive(Debug, Clone, PartialEq)]
13pub enum RepositoryType {
14    Bitbucket,
15    GitHub,
16    GitLab,
17    AzureDevOps,
18    Unknown,
19}
20
21/// Branch type classification
22#[derive(Debug, Clone, PartialEq)]
23pub enum BranchType {
24    Main,    // main, master, develop
25    Feature, // feature branches
26    Unknown,
27}
28
29/// Installation options for smart hook activation
30#[derive(Debug, Clone)]
31pub struct InstallOptions {
32    pub check_prerequisites: bool,
33    pub feature_branches_only: bool,
34    pub confirm: bool,
35    pub force: bool,
36}
37
38impl Default for InstallOptions {
39    fn default() -> Self {
40        Self {
41            check_prerequisites: true,
42            feature_branches_only: true,
43            confirm: true,
44            force: false,
45        }
46    }
47}
48
49/// Git hooks integration for Cascade CLI
50pub struct HooksManager {
51    repo_path: PathBuf,
52    repo_id: String,
53}
54
55/// Available Git hooks that Cascade can install
56#[derive(Debug, Clone)]
57pub enum HookType {
58    /// Validates commits are added to stacks
59    PostCommit,
60    /// Prevents force pushes and validates stack state
61    PrePush,
62    /// Validates commit messages follow conventions
63    CommitMsg,
64    /// Smart edit mode guidance before commit
65    PreCommit,
66    /// Prepares commit message with stack context
67    PrepareCommitMsg,
68}
69
70impl HookType {
71    fn filename(&self) -> String {
72        let base_name = match self {
73            HookType::PostCommit => "post-commit",
74            HookType::PrePush => "pre-push",
75            HookType::CommitMsg => "commit-msg",
76            HookType::PreCommit => "pre-commit",
77            HookType::PrepareCommitMsg => "prepare-commit-msg",
78        };
79        format!(
80            "{}{}",
81            base_name,
82            crate::utils::platform::git_hook_extension()
83        )
84    }
85
86    fn description(&self) -> &'static str {
87        match self {
88            HookType::PostCommit => "Auto-add new commits to active stack",
89            HookType::PrePush => "Prevent force pushes and validate stack state",
90            HookType::CommitMsg => "Validate commit message format",
91            HookType::PreCommit => "Smart edit mode guidance for better UX",
92            HookType::PrepareCommitMsg => "Add stack context to commit messages",
93        }
94    }
95}
96
97impl HooksManager {
98    pub fn new(repo_path: &Path) -> Result<Self> {
99        // Verify this is a git repository
100        let git_dir = repo_path.join(".git");
101        if !git_dir.exists() {
102            return Err(CascadeError::config(
103                "Not a Git repository. Git hooks require a valid Git repository.".to_string(),
104            ));
105        }
106
107        // Generate a unique repo ID based on remote URL
108        let repo_id = Self::generate_repo_id(repo_path)?;
109
110        Ok(Self {
111            repo_path: repo_path.to_path_buf(),
112            repo_id,
113        })
114    }
115
116    /// Generate a unique repository identifier based on remote URL
117    fn generate_repo_id(repo_path: &Path) -> Result<String> {
118        use std::process::Command;
119
120        let output = Command::new("git")
121            .args(["remote", "get-url", "origin"])
122            .current_dir(repo_path)
123            .output()
124            .map_err(|e| CascadeError::config(format!("Failed to get remote URL: {e}")))?;
125
126        if !output.status.success() {
127            // Fallback to absolute path hash if no remote
128            use sha2::{Digest, Sha256};
129            let canonical_path = repo_path
130                .canonicalize()
131                .unwrap_or_else(|_| repo_path.to_path_buf());
132            let path_str = canonical_path.to_string_lossy();
133            let mut hasher = Sha256::new();
134            hasher.update(path_str.as_bytes());
135            let result = hasher.finalize();
136            let hash = format!("{result:x}");
137            return Ok(format!("local-{}", &hash[..8]));
138        }
139
140        let remote_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
141
142        // Convert URL to safe directory name
143        // e.g., https://github.com/user/repo.git -> github.com-user-repo
144        let safe_name = remote_url
145            .replace("https://", "")
146            .replace("http://", "")
147            .replace("git@", "")
148            .replace("ssh://", "")
149            .replace(".git", "")
150            .replace([':', '/', '\\'], "-")
151            .chars()
152            .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '.' || *c == '_')
153            .collect::<String>();
154
155        Ok(safe_name)
156    }
157
158    /// Get the Cascade-specific hooks directory for this repo
159    fn get_cascade_hooks_dir(&self) -> Result<PathBuf> {
160        let home = dirs::home_dir()
161            .ok_or_else(|| CascadeError::config("Could not find home directory".to_string()))?;
162        let cascade_hooks = home.join(".cascade").join("hooks").join(&self.repo_id);
163        Ok(cascade_hooks)
164    }
165
166    /// Get the Cascade config directory for this repo
167    fn get_cascade_config_dir(&self) -> Result<PathBuf> {
168        let home = dirs::home_dir()
169            .ok_or_else(|| CascadeError::config("Could not find home directory".to_string()))?;
170        let cascade_config = home.join(".cascade").join("config").join(&self.repo_id);
171        Ok(cascade_config)
172    }
173
174    /// Save the current core.hooksPath value for later restoration
175    fn save_original_hooks_path(&self) -> Result<()> {
176        use std::process::Command;
177
178        let config_dir = self.get_cascade_config_dir()?;
179        fs::create_dir_all(&config_dir)
180            .map_err(|e| CascadeError::config(format!("Failed to create config directory: {e}")))?;
181
182        let original_path_file = config_dir.join("original-hooks-path");
183
184        // Only save if we haven't already saved it (don't overwrite on subsequent hook installs)
185        if original_path_file.exists() {
186            return Ok(());
187        }
188
189        let output = Command::new("git")
190            .args(["config", "--get", "core.hooksPath"])
191            .current_dir(&self.repo_path)
192            .output()
193            .map_err(|e| CascadeError::config(format!("Failed to check git config: {e}")))?;
194
195        let original_path = if output.status.success() {
196            String::from_utf8_lossy(&output.stdout).trim().to_string()
197        } else {
198            // Empty string means it wasn't set
199            String::new()
200        };
201
202        fs::write(original_path_file, original_path).map_err(|e| {
203            CascadeError::config(format!("Failed to save original hooks path: {e}"))
204        })?;
205
206        Ok(())
207    }
208
209    /// Restore the original core.hooksPath value
210    fn restore_original_hooks_path(&self) -> Result<()> {
211        use std::process::Command;
212
213        let config_dir = self.get_cascade_config_dir()?;
214        let original_path_file = config_dir.join("original-hooks-path");
215
216        if !original_path_file.exists() {
217            // Nothing to restore
218            return Ok(());
219        }
220
221        let original_path = fs::read_to_string(&original_path_file).map_err(|e| {
222            CascadeError::config(format!("Failed to read original hooks path: {e}"))
223        })?;
224
225        if original_path.is_empty() {
226            // It wasn't set originally, so unset it
227            Command::new("git")
228                .args(["config", "--unset", "core.hooksPath"])
229                .current_dir(&self.repo_path)
230                .output()
231                .map_err(|e| {
232                    CascadeError::config(format!("Failed to unset core.hooksPath: {e}"))
233                })?;
234        } else {
235            // Restore the original value
236            Command::new("git")
237                .args(["config", "core.hooksPath", &original_path])
238                .current_dir(&self.repo_path)
239                .output()
240                .map_err(|e| {
241                    CascadeError::config(format!("Failed to restore core.hooksPath: {e}"))
242                })?;
243        }
244
245        // Clean up the saved file
246        fs::remove_file(original_path_file).ok();
247
248        Ok(())
249    }
250
251    /// Get the actual hooks directory path, respecting core.hooksPath configuration
252    #[allow(dead_code)]
253    fn get_hooks_path(repo_path: &Path) -> Result<PathBuf> {
254        use std::process::Command;
255
256        // Try to get core.hooksPath configuration
257        let output = Command::new("git")
258            .args(["config", "--get", "core.hooksPath"])
259            .current_dir(repo_path)
260            .output()
261            .map_err(|e| CascadeError::config(format!("Failed to check git config: {e}")))?;
262
263        let hooks_path = if output.status.success() {
264            let configured_path = String::from_utf8_lossy(&output.stdout).trim().to_string();
265            if configured_path.is_empty() {
266                // Empty value means default
267                repo_path.join(".git").join("hooks")
268            } else if configured_path.starts_with('/') {
269                // Absolute path
270                PathBuf::from(configured_path)
271            } else {
272                // Relative path - relative to repo root
273                repo_path.join(configured_path)
274            }
275        } else {
276            // No core.hooksPath configured, use default
277            repo_path.join(".git").join("hooks")
278        };
279
280        Ok(hooks_path)
281    }
282
283    /// Install all recommended Cascade hooks
284    pub fn install_all(&self) -> Result<()> {
285        self.install_with_options(&InstallOptions::default())
286    }
287
288    /// Install only essential hooks (for setup) - excludes post-commit
289    pub fn install_essential(&self) -> Result<()> {
290        Output::progress("Installing essential Cascade Git hooks");
291
292        let essential_hooks = vec![
293            HookType::PrePush,
294            HookType::CommitMsg,
295            HookType::PrepareCommitMsg,
296            HookType::PreCommit,
297        ];
298
299        for hook in essential_hooks {
300            self.install_hook(&hook)?;
301        }
302
303        Output::success("Essential Cascade hooks installed successfully!");
304        Output::tip("Note: Post-commit auto-add hook available with 'ca hooks install --all'");
305        Output::section("Hooks installed");
306        self.list_installed_hooks()?;
307
308        Ok(())
309    }
310
311    /// Install hooks with smart validation options
312    pub fn install_with_options(&self, options: &InstallOptions) -> Result<()> {
313        if options.check_prerequisites && !options.force {
314            self.validate_prerequisites()?;
315        }
316
317        if options.feature_branches_only && !options.force {
318            self.validate_branch_suitability()?;
319        }
320
321        if options.confirm && !options.force {
322            self.confirm_installation()?;
323        }
324
325        Output::progress("Installing all Cascade Git hooks");
326
327        // Install ALL hooks (all 5 HookType variants)
328        let hooks = vec![
329            HookType::PostCommit,
330            HookType::PrePush,
331            HookType::CommitMsg,
332            HookType::PrepareCommitMsg,
333            HookType::PreCommit,
334        ];
335
336        for hook in hooks {
337            self.install_hook(&hook)?;
338        }
339
340        Output::success("All Cascade hooks installed successfully!");
341        Output::section("Hooks installed");
342        self.list_installed_hooks()?;
343
344        Ok(())
345    }
346
347    /// Install a specific hook
348    pub fn install_hook(&self, hook_type: &HookType) -> Result<()> {
349        // Ensure we've saved the original hooks path first
350        self.save_original_hooks_path()?;
351
352        // Create cascade hooks directory
353        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
354        fs::create_dir_all(&cascade_hooks_dir).map_err(|e| {
355            CascadeError::config(format!("Failed to create cascade hooks directory: {e}"))
356        })?;
357
358        // Generate hook that chains to original
359        let hook_content = self.generate_chaining_hook_script(hook_type)?;
360        let hook_path = cascade_hooks_dir.join(hook_type.filename());
361
362        // Write the hook
363        fs::write(&hook_path, hook_content)
364            .map_err(|e| CascadeError::config(format!("Failed to write hook file: {e}")))?;
365
366        // Make executable (platform-specific)
367        crate::utils::platform::make_executable(&hook_path)
368            .map_err(|e| CascadeError::config(format!("Failed to make hook executable: {e}")))?;
369
370        // Set core.hooksPath to our cascade directory
371        self.set_cascade_hooks_path()?;
372
373        Output::success(format!("Installed {} hook", hook_type.filename()));
374        Ok(())
375    }
376
377    /// Set git's core.hooksPath to our cascade hooks directory
378    fn set_cascade_hooks_path(&self) -> Result<()> {
379        use std::process::Command;
380
381        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
382        let hooks_path_str = cascade_hooks_dir.to_string_lossy();
383
384        let output = Command::new("git")
385            .args(["config", "core.hooksPath", &hooks_path_str])
386            .current_dir(&self.repo_path)
387            .output()
388            .map_err(|e| CascadeError::config(format!("Failed to set core.hooksPath: {e}")))?;
389
390        if !output.status.success() {
391            return Err(CascadeError::config(format!(
392                "Failed to set core.hooksPath: {}",
393                String::from_utf8_lossy(&output.stderr)
394            )));
395        }
396
397        Ok(())
398    }
399
400    /// Remove all Cascade hooks
401    pub fn uninstall_all(&self) -> Result<()> {
402        Output::progress("Removing Cascade Git hooks");
403
404        // Restore original core.hooksPath
405        self.restore_original_hooks_path()?;
406
407        // Clean up cascade hooks directory
408        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
409        if cascade_hooks_dir.exists() {
410            fs::remove_dir_all(&cascade_hooks_dir).map_err(|e| {
411                CascadeError::config(format!("Failed to remove cascade hooks directory: {e}"))
412            })?;
413        }
414
415        // Clean up config directory if empty
416        let cascade_config_dir = self.get_cascade_config_dir()?;
417        if cascade_config_dir.exists() {
418            // Try to remove, but ignore if not empty
419            fs::remove_dir(&cascade_config_dir).ok();
420        }
421
422        Output::success("All Cascade hooks removed!");
423        Ok(())
424    }
425
426    /// Remove a specific hook
427    pub fn uninstall_hook(&self, hook_type: &HookType) -> Result<()> {
428        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
429        let hook_path = cascade_hooks_dir.join(hook_type.filename());
430
431        if hook_path.exists() {
432            fs::remove_file(&hook_path)
433                .map_err(|e| CascadeError::config(format!("Failed to remove hook file: {e}")))?;
434            Output::success(format!("Removed {} hook", hook_type.filename()));
435
436            // If no more hooks in cascade directory, restore original hooks path
437            let remaining_hooks = fs::read_dir(&cascade_hooks_dir)
438                .map_err(|e| CascadeError::config(format!("Failed to read hooks directory: {e}")))?
439                .filter_map(|entry| entry.ok())
440                .filter(|entry| {
441                    entry.path().is_file() && !entry.file_name().to_string_lossy().starts_with('.')
442                })
443                .count();
444
445            if remaining_hooks == 0 {
446                Output::info(
447                    "No more Cascade hooks installed, restoring original hooks configuration",
448                );
449                self.restore_original_hooks_path()?;
450                fs::remove_dir(&cascade_hooks_dir).ok();
451            }
452        } else {
453            Output::info(format!("{} hook not found", hook_type.filename()));
454        }
455
456        Ok(())
457    }
458
459    /// List all installed hooks and their status
460    pub fn list_installed_hooks(&self) -> Result<()> {
461        let hooks = vec![
462            HookType::PostCommit,
463            HookType::PrePush,
464            HookType::CommitMsg,
465            HookType::PrepareCommitMsg,
466            HookType::PreCommit,
467        ];
468
469        Output::section("Git Hooks Status");
470
471        // Check if we're using cascade hooks directory
472        let cascade_hooks_dir = self.get_cascade_hooks_dir()?;
473        let using_cascade_hooks = cascade_hooks_dir.exists()
474            && self.get_current_hooks_path()?
475                == Some(cascade_hooks_dir.to_string_lossy().to_string());
476
477        if using_cascade_hooks {
478            Output::success("✓ Cascade hooks are installed and active");
479            Output::info(format!(
480                "  Hooks directory: {}",
481                cascade_hooks_dir.display()
482            ));
483
484            // Check what original hooks path was saved
485            let config_dir = self.get_cascade_config_dir()?;
486            let original_path_file = config_dir.join("original-hooks-path");
487            if original_path_file.exists() {
488                let original_path = fs::read_to_string(original_path_file).unwrap_or_default();
489                if !original_path.is_empty() {
490                    Output::info(format!("  Chaining to original hooks: {original_path}"));
491                } else {
492                    Output::info("  Chaining to original hooks: .git/hooks");
493                }
494            }
495            println!();
496        } else {
497            Output::warning("Cascade hooks are NOT installed in this repository");
498            println!();
499            Output::sub_item("To install Cascade hooks:");
500            Output::command_example("ca hooks install            # recommended: 4 essential hooks");
501            Output::command_example(
502                "ca hooks install --all      # all 5 hooks + post-commit auto-add",
503            );
504            println!();
505            Output::sub_item("Both options preserve existing hooks by chaining to them");
506            println!();
507        }
508
509        for hook in hooks {
510            let cascade_hook_path = cascade_hooks_dir.join(hook.filename());
511
512            if using_cascade_hooks && cascade_hook_path.exists() {
513                Output::success(format!("{}: {} ✓", hook.filename(), hook.description()));
514            } else {
515                // Check default location
516                let default_hook_path = self
517                    .repo_path
518                    .join(".git")
519                    .join("hooks")
520                    .join(hook.filename());
521                if default_hook_path.exists() {
522                    Output::warning(format!(
523                        "{}: {} (In .git/hooks, not managed by Cascade)",
524                        hook.filename(),
525                        hook.description()
526                    ));
527                } else {
528                    Output::error(format!(
529                        "{}: {} (Not installed)",
530                        hook.filename(),
531                        hook.description()
532                    ));
533                }
534            }
535        }
536
537        Ok(())
538    }
539
540    /// Get the current core.hooksPath value
541    fn get_current_hooks_path(&self) -> Result<Option<String>> {
542        use std::process::Command;
543
544        let output = Command::new("git")
545            .args(["config", "--get", "core.hooksPath"])
546            .current_dir(&self.repo_path)
547            .output()
548            .map_err(|e| CascadeError::config(format!("Failed to check git config: {e}")))?;
549
550        if output.status.success() {
551            let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
552            if path.is_empty() {
553                Ok(None)
554            } else {
555                Ok(Some(path))
556            }
557        } else {
558            Ok(None)
559        }
560    }
561
562    /// Generate hook script content
563    pub fn generate_hook_script(&self, hook_type: &HookType) -> Result<String> {
564        let cascade_cli = env::current_exe()
565            .map_err(|e| {
566                CascadeError::config(format!("Failed to get current executable path: {e}"))
567            })?
568            .to_string_lossy()
569            .to_string();
570
571        let script = match hook_type {
572            HookType::PostCommit => self.generate_post_commit_hook(&cascade_cli),
573            HookType::PrePush => self.generate_pre_push_hook(&cascade_cli),
574            HookType::CommitMsg => self.generate_commit_msg_hook(&cascade_cli),
575            HookType::PreCommit => self.generate_pre_commit_hook(&cascade_cli),
576            HookType::PrepareCommitMsg => self.generate_prepare_commit_msg_hook(&cascade_cli),
577        };
578
579        Ok(script)
580    }
581
582    /// Generate hook script that chains to original hooks
583    pub fn generate_chaining_hook_script(&self, hook_type: &HookType) -> Result<String> {
584        let cascade_cli = env::current_exe()
585            .map_err(|e| {
586                CascadeError::config(format!("Failed to get current executable path: {e}"))
587            })?
588            .to_string_lossy()
589            .to_string();
590
591        let config_dir = self.get_cascade_config_dir()?;
592        let hook_name = match hook_type {
593            HookType::PostCommit => "post-commit",
594            HookType::PrePush => "pre-push",
595            HookType::CommitMsg => "commit-msg",
596            HookType::PreCommit => "pre-commit",
597            HookType::PrepareCommitMsg => "prepare-commit-msg",
598        };
599
600        // Generate the cascade-specific hook logic
601        let cascade_logic = match hook_type {
602            HookType::PostCommit => self.generate_post_commit_hook(&cascade_cli),
603            HookType::PrePush => self.generate_pre_push_hook(&cascade_cli),
604            HookType::CommitMsg => self.generate_commit_msg_hook(&cascade_cli),
605            HookType::PreCommit => self.generate_pre_commit_hook(&cascade_cli),
606            HookType::PrepareCommitMsg => self.generate_prepare_commit_msg_hook(&cascade_cli),
607        };
608
609        // Create wrapper that chains to original
610        #[cfg(windows)]
611        return Ok(format!(
612                "@echo off\n\
613                 rem Cascade CLI Hook Wrapper - {}\n\
614                 rem This hook runs Cascade logic first, then chains to original hooks\n\n\
615                 rem Run Cascade logic first\n\
616                 call :cascade_logic %*\n\
617                 set CASCADE_RESULT=%ERRORLEVEL%\n\
618                 if %CASCADE_RESULT% neq 0 exit /b %CASCADE_RESULT%\n\n\
619                 rem Check for original hook\n\
620                 set ORIGINAL_HOOKS_PATH=\n\
621                 if exist \"{}\\original-hooks-path\" (\n\
622                     set /p ORIGINAL_HOOKS_PATH=<\"{}\\original-hooks-path\"\n\
623                 )\n\n\
624                 if \"%ORIGINAL_HOOKS_PATH%\"==\"\" (\n\
625                     rem Default location\n\
626                     for /f \"tokens=*\" %%i in ('git rev-parse --git-dir 2^>nul') do set GIT_DIR=%%i\n\
627                     if exist \"%GIT_DIR%\\hooks\\{}\" (\n\
628                         call \"%GIT_DIR%\\hooks\\{}\" %*\n\
629                         exit /b %ERRORLEVEL%\n\
630                     )\n\
631                 ) else (\n\
632                     rem Custom hooks path\n\
633                     if exist \"%ORIGINAL_HOOKS_PATH%\\{}\" (\n\
634                         call \"%ORIGINAL_HOOKS_PATH%\\{}\" %*\n\
635                         exit /b %ERRORLEVEL%\n\
636                     )\n\
637                 )\n\n\
638                 exit /b 0\n\n\
639                 :cascade_logic\n\
640                 {}\n\
641                 exit /b %ERRORLEVEL%\n",
642                hook_name,
643                config_dir.to_string_lossy(),
644                config_dir.to_string_lossy(),
645                hook_name,
646                hook_name,
647                hook_name,
648                hook_name,
649                cascade_logic
650            ));
651
652        #[cfg(not(windows))]
653        {
654            // Build the wrapper using string concatenation to avoid double-escaping issues
655            let trimmed_logic = cascade_logic
656                .trim_start_matches("#!/bin/sh\n")
657                .trim_start_matches("set -e\n");
658
659            let wrapper = format!(
660                "#!/bin/sh\n\
661                 # Cascade CLI Hook Wrapper - {}\n\
662                 # This hook runs Cascade logic first, then chains to original hooks\n\n\
663                 set -e\n\n\
664                 # Function to run Cascade logic\n\
665                 cascade_logic() {{\n",
666                hook_name
667            );
668
669            let chaining_logic = format!(
670                "\n\
671                 }}\n\n\
672                 # Run Cascade logic first\n\
673                 cascade_logic \"$@\"\n\
674                 CASCADE_RESULT=$?\n\
675                 if [ $CASCADE_RESULT -ne 0 ]; then\n\
676                     exit $CASCADE_RESULT\n\
677                 fi\n\n\
678                 # Check for original hook\n\
679                 ORIGINAL_HOOKS_PATH=\"\"\n\
680                 if [ -f \"{}/original-hooks-path\" ]; then\n\
681                     ORIGINAL_HOOKS_PATH=$(cat \"{}/original-hooks-path\" 2>/dev/null || echo \"\")\n\
682                 fi\n\n\
683                 if [ -z \"$ORIGINAL_HOOKS_PATH\" ]; then\n\
684                     # Default location\n\
685                     GIT_DIR=$(git rev-parse --git-dir 2>/dev/null || echo \".git\")\n\
686                     ORIGINAL_HOOK=\"$GIT_DIR/hooks/{}\"\n\
687                 else\n\
688                     # Custom hooks path\n\
689                     ORIGINAL_HOOK=\"$ORIGINAL_HOOKS_PATH/{}\"\n\
690                 fi\n\n\
691                 # Run original hook if it exists and is executable\n\
692                 if [ -x \"$ORIGINAL_HOOK\" ]; then\n\
693                     \"$ORIGINAL_HOOK\" \"$@\"\n\
694                     exit $?\n\
695                 fi\n\n\
696                 exit 0\n",
697                config_dir.to_string_lossy(),
698                config_dir.to_string_lossy(),
699                hook_name,
700                hook_name
701            );
702
703            Ok(format!("{}{}{}", wrapper, trimmed_logic, chaining_logic))
704        }
705    }
706
707    fn generate_post_commit_hook(&self, cascade_cli: &str) -> String {
708        #[cfg(windows)]
709        {
710            format!(
711                "@echo off\n\
712                 rem Cascade CLI Hook - Post Commit\n\
713                 rem Automatically adds new commits to the active stack\n\n\
714                 rem Get the commit hash and message\n\
715                 for /f \"tokens=*\" %%i in ('git rev-parse HEAD') do set COMMIT_HASH=%%i\n\
716                 for /f \"tokens=*\" %%i in ('git log --format=%%s -n 1 HEAD') do set COMMIT_MSG=%%i\n\n\
717                 rem Find repository root and check if Cascade is initialized\n\
718                 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
719                 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
720                 if not exist \"%REPO_ROOT%\\.cascade\" (\n\
721                     echo ℹ️ Cascade not initialized, skipping stack management\n\
722                     echo 💡 Run 'ca init' to start using stacked diffs\n\
723                     exit /b 0\n\
724                 )\n\n\
725                 rem Check if there's an active stack\n\
726                 \"{cascade_cli}\" stack list --active >nul 2>&1\n\
727                 if %ERRORLEVEL% neq 0 (\n\
728                     echo ℹ️ No active stack found, commit will not be added to any stack\n\
729                     echo 💡 Use 'ca stack create ^<name^>' to create a stack for this commit\n\
730                     exit /b 0\n\
731                 )\n\n\
732                 rem Add commit to active stack\n\
733                 echo 🪝 Adding commit to active stack...\n\
734                 echo 📝 Commit: %COMMIT_MSG%\n\
735                 \"{cascade_cli}\" stack push --commit \"%COMMIT_HASH%\" --message \"%COMMIT_MSG%\"\n\
736                 if %ERRORLEVEL% equ 0 (\n\
737                     echo ✅ Commit added to stack successfully\n\
738                     echo 💡 Next: 'ca submit' to create PRs when ready\n\
739                 ) else (\n\
740                     echo ⚠️ Failed to add commit to stack\n\
741                     echo 💡 You can manually add it with: ca push --commit %COMMIT_HASH%\n\
742                 )\n"
743            )
744        }
745
746        #[cfg(not(windows))]
747        {
748            format!(
749                "#!/bin/sh\n\
750                 # Cascade CLI Hook - Post Commit\n\
751                 # Automatically adds new commits to the active stack\n\n\
752                 set -e\n\n\
753                 # Get the commit hash and message\n\
754                 COMMIT_HASH=$(git rev-parse HEAD)\n\
755                 COMMIT_MSG=$(git log --format=%s -n 1 HEAD)\n\n\
756                 # Find repository root and check if Cascade is initialized\n\
757                 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
758                 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
759                     echo \"ℹ️ Cascade not initialized, skipping stack management\"\n\
760                     echo \"💡 Run 'ca init' to start using stacked diffs\"\n\
761                     exit 0\n\
762                 fi\n\n\
763                 # Check if there's an active stack\n\
764                 if ! \"{cascade_cli}\" stack list --active > /dev/null 2>&1; then\n\
765                     echo \"ℹ️ No active stack found, commit will not be added to any stack\"\n\
766                     echo \"💡 Use 'ca stack create <name>' to create a stack for this commit\"\n\
767                     exit 0\n\
768                 fi\n\n\
769                 # Add commit to active stack (using specific commit targeting)\n\
770                 echo \"🪝 Adding commit to active stack...\"\n\
771                 echo \"📝 Commit: $COMMIT_MSG\"\n\
772                 if \"{cascade_cli}\" stack push --commit \"$COMMIT_HASH\" --message \"$COMMIT_MSG\"; then\n\
773                     echo \"✅ Commit added to stack successfully\"\n\
774                     echo \"💡 Next: 'ca submit' to create PRs when ready\"\n\
775                 else\n\
776                     echo \"⚠️ Failed to add commit to stack\"\n\
777                     echo \"💡 You can manually add it with: ca push --commit $COMMIT_HASH\"\n\
778                 fi\n"
779            )
780        }
781    }
782
783    fn generate_pre_push_hook(&self, cascade_cli: &str) -> String {
784        #[cfg(windows)]
785        {
786            format!(
787                "@echo off\n\
788                 rem Cascade CLI Hook - Pre Push\n\
789                 rem Prevents force pushes and validates stack state\n\n\
790                 rem Check for force push\n\
791                 echo %* | findstr /C:\"--force\" /C:\"--force-with-lease\" /C:\"-f\" >nul\n\
792                 if %ERRORLEVEL% equ 0 (\n\
793                     echo ❌ Force push detected!\n\
794                     echo 🌊 Cascade CLI uses stacked diffs - force pushes can break stack integrity\n\
795                     echo.\n\
796                     echo 💡 Instead of force pushing, try these streamlined commands:\n\
797                     echo    • ca sync      - Sync with remote changes ^(handles rebasing^)\n\
798                     echo    • ca push      - Push all unpushed commits ^(new default^)\n\
799                     echo    • ca submit    - Submit all entries for review ^(new default^)\n\
800                     echo    • ca autoland  - Auto-merge when approved + builds pass\n\
801                     echo.\n\
802                     echo 🚨 If you really need to force push, run:\n\
803                     echo    git push --force-with-lease [remote] [branch]\n\
804                     echo    ^(But consider if this will affect other stack entries^)\n\
805                     exit /b 1\n\
806                 )\n\n\
807                 rem Find repository root and check if Cascade is initialized\n\
808                 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
809                 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
810                 if not exist \"%REPO_ROOT%\\.cascade\" (\n\
811                     echo ℹ️ Cascade not initialized, allowing push\n\
812                     exit /b 0\n\
813                 )\n\n\
814                 rem Validate stack state\n\
815                 echo 🪝 Validating stack state before push...\n\
816                 \"{cascade_cli}\" stack validate\n\
817                 if %ERRORLEVEL% equ 0 (\n\
818                     echo ✅ Stack validation passed\n\
819                 ) else (\n\
820                     echo ❌ Stack validation failed\n\
821                     echo 💡 Fix validation errors before pushing:\n\
822                     echo    • ca doctor       - Check overall health\n\
823                     echo    • ca status       - Check current stack status\n\
824                     echo    • ca sync         - Sync with remote and rebase if needed\n\
825                     exit /b 1\n\
826                 )\n\n\
827                 echo ✅ Pre-push validation complete\n"
828            )
829        }
830
831        #[cfg(not(windows))]
832        {
833            format!(
834                "#!/bin/sh\n\
835                 # Cascade CLI Hook - Pre Push\n\
836                 # Prevents force pushes and validates stack state\n\n\
837                 set -e\n\n\
838                 # Check for force push\n\
839                 if echo \"$*\" | grep -q -- \"--force\\|--force-with-lease\\|-f\"; then\n\
840                     echo \"❌ Force push detected!\"\n\
841                     echo \"🌊 Cascade CLI uses stacked diffs - force pushes can break stack integrity\"\n\
842                     echo \"\"\n\
843                     echo \"💡 Instead of force pushing, try these streamlined commands:\"\n\
844                     echo \"   • ca sync      - Sync with remote changes (handles rebasing)\"\n\
845                     echo \"   • ca push      - Push all unpushed commits (new default)\"\n\
846                     echo \"   • ca submit    - Submit all entries for review (new default)\"\n\
847                     echo \"   • ca autoland  - Auto-merge when approved + builds pass\"\n\
848                     echo \"\"\n\
849                     echo \"🚨 If you really need to force push, run:\"\n\
850                     echo \"   git push --force-with-lease [remote] [branch]\"\n\
851                     echo \"   (But consider if this will affect other stack entries)\"\n\
852                     exit 1\n\
853                 fi\n\n\
854                 # Find repository root and check if Cascade is initialized\n\
855                 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
856                 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
857                     echo \"ℹ️ Cascade not initialized, allowing push\"\n\
858                     exit 0\n\
859                 fi\n\n\
860                 # Validate stack state\n\
861                 echo \"🪝 Validating stack state before push...\"\n\
862                 if \"{cascade_cli}\" stack validate; then\n\
863                     echo \"✅ Stack validation passed\"\n\
864                 else\n\
865                     echo \"❌ Stack validation failed\"\n\
866                     echo \"💡 Fix validation errors before pushing:\"\n\
867                     echo \"   • ca doctor       - Check overall health\"\n\
868                     echo \"   • ca status       - Check current stack status\"\n\
869                     echo \"   • ca sync         - Sync with remote and rebase if needed\"\n\
870                     exit 1\n\
871                 fi\n\n\
872                 echo \"✅ Pre-push validation complete\"\n"
873            )
874        }
875    }
876
877    fn generate_commit_msg_hook(&self, _cascade_cli: &str) -> String {
878        #[cfg(windows)]
879        {
880            r#"@echo off
881rem Cascade CLI Hook - Commit Message
882rem Validates commit message format
883
884set COMMIT_MSG_FILE=%1
885if "%COMMIT_MSG_FILE%"=="" (
886    echo ❌ No commit message file provided
887    exit /b 1
888)
889
890rem Read commit message (Windows batch is limited, but this covers basic cases)
891for /f "delims=" %%i in ('type "%COMMIT_MSG_FILE%"') do set COMMIT_MSG=%%i
892
893rem Skip validation for merge commits, fixup commits, etc.
894echo %COMMIT_MSG% | findstr /B /C:"Merge" /C:"Revert" /C:"fixup!" /C:"squash!" >nul
895if %ERRORLEVEL% equ 0 exit /b 0
896
897rem Find repository root and check if Cascade is initialized
898for /f "tokens=*" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i
899if "%REPO_ROOT%"=="" set REPO_ROOT=.
900if not exist "%REPO_ROOT%\.cascade" exit /b 0
901
902rem Basic commit message validation
903echo %COMMIT_MSG% | findstr /R "^..........*" >nul
904if %ERRORLEVEL% neq 0 (
905    echo ❌ Commit message too short (minimum 10 characters)
906    echo 💡 Write a descriptive commit message for better stack management
907    exit /b 1
908)
909
910rem Check for very long messages (approximate check in batch)
911echo %COMMIT_MSG% | findstr /R "^..................................................................................*" >nul
912if %ERRORLEVEL% equ 0 (
913    echo ⚠️ Warning: Commit message longer than 72 characters
914    echo 💡 Consider keeping the first line short for better readability
915)
916
917rem Check for conventional commit format (optional)
918echo %COMMIT_MSG% | findstr /R "^(feat|fix|docs|style|refactor|test|chore|perf|ci|build)" >nul
919if %ERRORLEVEL% neq 0 (
920    echo 💡 Consider using conventional commit format:
921    echo    feat: add new feature
922    echo    fix: resolve bug
923    echo    docs: update documentation
924    echo    etc.
925)
926
927echo ✅ Commit message validation passed
928"#.to_string()
929        }
930
931        #[cfg(not(windows))]
932        {
933            r#"#!/bin/sh
934# Cascade CLI Hook - Commit Message
935# Validates commit message format
936
937set -e
938
939COMMIT_MSG_FILE="$1"
940COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")
941
942# Skip validation for merge commits, fixup commits, etc.
943if echo "$COMMIT_MSG" | grep -E "^(Merge|Revert|fixup!|squash!)" > /dev/null; then
944    exit 0
945fi
946
947# Find repository root and check if Cascade is initialized
948REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")
949if [ ! -d "$REPO_ROOT/.cascade" ]; then
950    exit 0
951fi
952
953# Basic commit message validation
954if [ ${#COMMIT_MSG} -lt 10 ]; then
955    echo "❌ Commit message too short (minimum 10 characters)"
956    echo "💡 Write a descriptive commit message for better stack management"
957    exit 1
958fi
959
960if [ ${#COMMIT_MSG} -gt 72 ]; then
961    echo "⚠️ Warning: Commit message longer than 72 characters"
962    echo "💡 Consider keeping the first line short for better readability"
963fi
964
965# Check for conventional commit format (optional)
966if ! echo "$COMMIT_MSG" | grep -E "^(feat|fix|docs|style|refactor|test|chore|perf|ci|build)(\(.+\))?: .+" > /dev/null; then
967    echo "💡 Consider using conventional commit format:"
968    echo "   feat: add new feature"
969    echo "   fix: resolve bug"
970    echo "   docs: update documentation"
971    echo "   etc."
972fi
973
974echo "✅ Commit message validation passed"
975"#.to_string()
976        }
977    }
978
979    #[allow(clippy::uninlined_format_args)]
980    fn generate_pre_commit_hook(&self, cascade_cli: &str) -> String {
981        #[cfg(windows)]
982        {
983            format!(
984                "@echo off\n\
985                 rem Cascade CLI Hook - Pre Commit\n\
986                 rem Smart edit mode guidance for better UX\n\n\
987                 rem Check if Cascade is initialized\n\
988                 for /f \\\"tokens=*\\\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
989                 if \\\"%REPO_ROOT%\\\"==\\\"\\\" set REPO_ROOT=.\n\
990                 if not exist \\\"%REPO_ROOT%\\.cascade\\\" exit /b 0\n\n\
991                 rem Check if we're in edit mode\n\
992                 \\\"{0}\\\" entry status --quiet >nul 2>&1\n\
993                 if %ERRORLEVEL% equ 0 (\n\
994                     echo ⚠  You're in EDIT MODE for a stack entry!\n\
995                     echo.\n\
996                    echo Choose your action:\n\
997                    echo   [A] Amend: Modify the current entry ^(default^)\n\
998                    echo   [N] New:   Create new entry on top\n\
999                    echo   [C] Cancel: Stop and think about it\n\
1000                    echo.\n\
1001                    set /p choice=\\\"Your choice (A/n/c): \\\"\n\
1002                    if \\\"%choice%\\\"==\\\"\\\" set choice=A\n\
1003                    \n\
1004                    if /i \\\"%choice%\\\"==\\\"A\\\" (\n\
1005                        echo Amending current entry...\n\
1006                        rem Stage all changes first\n\
1007                        git add -A\n\
1008                        rem Use ca entry amend to properly update entry + working branch\n\
1009                        \\\"{0}\\\" entry amend --all\n\
1010                        exit /b %ERRORLEVEL%\n\
1011                    ) else if /i \\\"%choice%\\\"==\\\"N\\\" (\n\
1012                        echo Creating new stack entry...\n\
1013                        rem Let the commit proceed normally\n\
1014                        exit /b 0\n\
1015                    ) else if /i \\\"%choice%\\\"==\\\"C\\\" (\n\
1016                        echo Commit cancelled\n\
1017                        exit /b 1\n\
1018                    ) else (\n\
1019                        echo Invalid choice. Please choose A, n, or c\n\
1020                        exit /b 1\n\
1021                    )\n\
1022                 )\n\n\
1023                 rem Not in edit mode, proceed normally\n\
1024                 exit /b 0\n",
1025                cascade_cli
1026            )
1027        }
1028
1029        #[cfg(not(windows))]
1030        {
1031            // Use string building to avoid escaping issues with format! macros
1032            // Check the OUTPUT of entry status, not just exit code
1033            let status_check = format!(
1034                "EDIT_STATUS=$(\"{}\" entry status --quiet 2>/dev/null || echo \"inactive\")",
1035                cascade_cli
1036            );
1037            let amend_line = format!("           \"{}\" entry amend --all", cascade_cli);
1038
1039            vec![
1040                "#!/bin/sh".to_string(),
1041                "# Cascade CLI Hook - Pre Commit".to_string(),
1042                "# Smart edit mode guidance for better UX".to_string(),
1043                "".to_string(),
1044                "set -e".to_string(),
1045                "".to_string(),
1046                "# Check if Cascade is initialized".to_string(),
1047                r#"REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")"#.to_string(),
1048                r#"if [ ! -d "$REPO_ROOT/.cascade" ]; then"#.to_string(),
1049                "    exit 0".to_string(),
1050                "fi".to_string(),
1051                "".to_string(),
1052                "# Check if we're on an entry branch (even without edit mode set)".to_string(),
1053                r#"CURRENT_BRANCH=$(git branch --show-current 2>/dev/null)"#.to_string(),
1054                r#"IS_ENTRY_BRANCH=$(echo "$CURRENT_BRANCH" | grep -qE '\-entry\-[0-9]+$' && echo "yes" || echo "no")"#.to_string(),
1055                "".to_string(),
1056                "# If on entry branch, check if edit mode is properly set".to_string(),
1057                r#"if [ "$IS_ENTRY_BRANCH" = "yes" ]; then"#.to_string(),
1058                "    ".to_string(),
1059                status_check,
1060                "    ".to_string(),
1061                "    # Check if edit mode is active".to_string(),
1062                r#"    if echo "$EDIT_STATUS" | grep -q "^active:"; then"#.to_string(),
1063                "        # Proper edit mode - show options".to_string(),
1064                r#"        echo "WARNING: You're in EDIT MODE for a stack entry""#.to_string(),
1065                r#"        echo """#.to_string(),
1066                "        ".to_string(),
1067                "        # Check if running interactively (stdin is a terminal)".to_string(),
1068                "        if [ -t 0 ]; then".to_string(),
1069                "            # Interactive mode - prompt user".to_string(),
1070                r#"            echo "Choose your action:""#.to_string(),
1071                r#"            echo "  [A] Amend: Modify the current entry (default)""#.to_string(),
1072                r#"            echo "  [N] New:   Create new entry on top""#.to_string(),
1073                r#"            echo "  [C] Cancel: Stop and think about it""#.to_string(),
1074                r#"            echo """#.to_string(),
1075                "       ".to_string(),
1076                "       # Read user choice with default to amend".to_string(),
1077                r#"       read -p "Your choice (A/n/c): " choice"#.to_string(),
1078                "       choice=${choice:-A}".to_string(),
1079                "        else".to_string(),
1080                "            # Non-interactive (e.g., git commit -m) - block and provide guidance".to_string(),
1081                r#"            echo """#.to_string(),
1082                r#"            echo "ERROR: Cannot use 'git commit -m' while in edit mode""#.to_string(),
1083                r#"            echo """#.to_string(),
1084                r#"            echo "Choose one of these instead:""#.to_string(),
1085                r#"            echo "  - git commit              (interactive: choose Amend/New)""#.to_string(),
1086                format!("            echo \"  - {} entry amend -m 'msg'  (amend with message)\"", cascade_cli),
1087                format!("            echo \"  - {} entry amend          (amend, edit message in editor)\"", cascade_cli),
1088                r#"            echo "  - git checkout <branch>   (exit edit mode first)""#.to_string(),
1089                r#"            echo """#.to_string(),
1090                "            exit 1".to_string(),
1091                "        fi".to_string(),
1092                "   ".to_string(),
1093                "   ".to_string(),
1094                r#"   case "$choice" in"#.to_string(),
1095                "       [Aa])".to_string(),
1096                r#"           echo "Amending current entry...""#.to_string(),
1097                "           # Stage all changes first (like git commit -a)".to_string(),
1098                "           git add -A".to_string(),
1099                "           # Use ca entry amend to properly update entry + working branch"
1100                    .to_string(),
1101                amend_line,
1102                "           exit $?".to_string(),
1103                "           ;;".to_string(),
1104                "       [Nn])".to_string(),
1105                r#"           echo "Creating new stack entry...""#.to_string(),
1106                "           # Let the commit proceed normally (will create new commit)".to_string(),
1107                "           exit 0".to_string(),
1108                "           ;;".to_string(),
1109                "       [Cc])".to_string(),
1110                r#"           echo "Commit cancelled""#.to_string(),
1111                "           exit 1".to_string(),
1112                "           ;;".to_string(),
1113                "       *)".to_string(),
1114                r#"           echo "Invalid choice. Please choose A, n, or c""#.to_string(),
1115                "           exit 1".to_string(),
1116                "           ;;".to_string(),
1117                "   esac".to_string(),
1118                "    else".to_string(),
1119                "        # On entry branch but NOT in edit mode - someone bypassed ca entry checkout!".to_string(),
1120                r#"        echo """#.to_string(),
1121                r#"        echo "WARNING: You're on a stack entry branch""#.to_string(),
1122                r#"        echo """#.to_string(),
1123                r#"        echo "Current branch: $CURRENT_BRANCH""#.to_string(),
1124                r#"        echo """#.to_string(),
1125                r#"        echo "ERROR: Cannot commit directly to entry branches""#.to_string(),
1126                r#"        echo """#.to_string(),
1127                r#"        echo "Did you mean to:""#.to_string(),
1128                format!("        echo \"  - {} entry checkout <N>  (enter proper edit mode)\"", cascade_cli),
1129                r#"        echo "  - git checkout <working-branch>  (switch to working branch)""#.to_string(),
1130                format!("        echo \"  - {} stack list            (see your stacks)\"", cascade_cli),
1131                r#"        echo """#.to_string(),
1132                "        exit 1".to_string(),
1133                "    fi".to_string(),
1134                "fi".to_string(),
1135                "".to_string(),
1136                "# Not on entry branch, proceed normally".to_string(),
1137                "exit 0".to_string(),
1138            ]
1139            .join("\n")
1140        }
1141    }
1142
1143    fn generate_prepare_commit_msg_hook(&self, cascade_cli: &str) -> String {
1144        #[cfg(windows)]
1145        {
1146            format!(
1147                "@echo off\n\
1148                 rem Cascade CLI Hook - Prepare Commit Message\n\
1149                 rem Adds stack context to commit messages\n\n\
1150                 set COMMIT_MSG_FILE=%1\n\
1151                 set COMMIT_SOURCE=%2\n\
1152                 set COMMIT_SHA=%3\n\n\
1153                 rem Only modify message if it's a regular commit (not merge, template, etc.)\n\
1154                 if not \"%COMMIT_SOURCE%\"==\"\" if not \"%COMMIT_SOURCE%\"==\"message\" exit /b 0\n\n\
1155                 rem Find repository root and check if Cascade is initialized\n\
1156                 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
1157                 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
1158                 if not exist \"%REPO_ROOT%\\.cascade\" exit /b 0\n\n\
1159                 rem Check if in edit mode first\n\
1160                 for /f \"tokens=*\" %%i in ('\"{cascade_cli}\" entry status --quiet 2^>nul') do set EDIT_STATUS=%%i\n\
1161                 if \"%EDIT_STATUS%\"==\"\" set EDIT_STATUS=inactive\n\n\
1162                 if not \"%EDIT_STATUS%\"==\"inactive\" (\n\
1163                     rem In edit mode - provide smart guidance\n\
1164                     set /p CURRENT_MSG=<%COMMIT_MSG_FILE%\n\n\
1165                     rem Skip if message already has edit guidance\n\
1166                     echo !CURRENT_MSG! | findstr \"[EDIT MODE]\" >nul\n\
1167                     if %ERRORLEVEL% equ 0 exit /b 0\n\n\
1168                     rem Add edit mode guidance to commit message\n\
1169                     echo.\n\
1170                     echo # [EDIT MODE] You're editing a stack entry\n\
1171                     echo #\n\
1172                     echo # Choose your action:\n\
1173                     echo #   🔄 AMEND: To modify the current entry, use:\n\
1174                     echo #       git commit --amend\n\
1175                     echo #\n\
1176                     echo #   ➕ NEW: To create a new entry on top, use:\n\
1177                     echo #       git commit    ^(this command^)\n\
1178                     echo #\n\
1179                     echo # 💡 After committing, run 'ca sync' to update PRs\n\
1180                     echo.\n\
1181                     type \"%COMMIT_MSG_FILE%\"\n\
1182                 ) > \"%COMMIT_MSG_FILE%.tmp\" && (\n\
1183                     move \"%COMMIT_MSG_FILE%.tmp\" \"%COMMIT_MSG_FILE%\"\n\
1184                 ) else (\n\
1185                     rem Regular stack mode - check for active stack\n\
1186                     for /f \"tokens=*\" %%i in ('\"{cascade_cli}\" stack list --active --format=name 2^>nul') do set ACTIVE_STACK=%%i\n\n\
1187                     if not \"%ACTIVE_STACK%\"==\"\" (\n\
1188                         rem Get current commit message\n\
1189                         set /p CURRENT_MSG=<%COMMIT_MSG_FILE%\n\n\
1190                         rem Skip if message already has stack context\n\
1191                         echo !CURRENT_MSG! | findstr \"[stack:\" >nul\n\
1192                         if %ERRORLEVEL% equ 0 exit /b 0\n\n\
1193                         rem Add stack context to commit message\n\
1194                         echo.\n\
1195                         echo # Stack: %ACTIVE_STACK%\n\
1196                         echo # This commit will be added to the active stack automatically.\n\
1197                         echo # Use 'ca stack status' to see the current stack state.\n\
1198                         type \"%COMMIT_MSG_FILE%\"\n\
1199                     ) > \"%COMMIT_MSG_FILE%.tmp\"\n\
1200                     move \"%COMMIT_MSG_FILE%.tmp\" \"%COMMIT_MSG_FILE%\"\n\
1201                 )\n"
1202            )
1203        }
1204
1205        #[cfg(not(windows))]
1206        {
1207            format!(
1208                "#!/bin/sh\n\
1209                 # Cascade CLI Hook - Prepare Commit Message\n\
1210                 # Adds stack context to commit messages\n\n\
1211                 set -e\n\n\
1212                 COMMIT_MSG_FILE=\"$1\"\n\
1213                 COMMIT_SOURCE=\"$2\"\n\
1214                 COMMIT_SHA=\"$3\"\n\n\
1215                 # Only modify message if it's a regular commit (not merge, template, etc.)\n\
1216                 if [ \"$COMMIT_SOURCE\" != \"\" ] && [ \"$COMMIT_SOURCE\" != \"message\" ]; then\n\
1217                     exit 0\n\
1218                 fi\n\n\
1219                 # Find repository root and check if Cascade is initialized\n\
1220                 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
1221                 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
1222                     exit 0\n\
1223                 fi\n\n\
1224                 # Check if in edit mode first\n\
1225                 EDIT_STATUS=$(\"{cascade_cli}\" entry status --quiet 2>/dev/null || echo \"inactive\")\n\
1226                 \n\
1227                 if [ \"$EDIT_STATUS\" != \"inactive\" ]; then\n\
1228                     # In edit mode - provide smart guidance\n\
1229                     CURRENT_MSG=$(cat \"$COMMIT_MSG_FILE\")\n\
1230                     \n\
1231                     # Skip if message already has edit guidance\n\
1232                     if echo \"$CURRENT_MSG\" | grep -q \"\\[EDIT MODE\\]\"; then\n\
1233                         exit 0\n\
1234                     fi\n\
1235                     \n\
1236                     echo \"\n\
1237                 # [EDIT MODE] You're editing a stack entry\n\
1238                 #\n\
1239                 # Choose your action:\n\
1240                 #   🔄 AMEND: To modify the current entry, use:\n\
1241                 #       git commit --amend\n\
1242                 #\n\
1243                 #   ➕ NEW: To create a new entry on top, use:\n\
1244                 #       git commit    (this command)\n\
1245                 #\n\
1246                 # 💡 After committing, run 'ca sync' to update PRs\n\
1247                 \n\
1248                 $CURRENT_MSG\" > \"$COMMIT_MSG_FILE\"\n\
1249                 else\n\
1250                     # Regular stack mode - check for active stack\n\
1251                     ACTIVE_STACK=$(\"{cascade_cli}\" stack list --active --format=name 2>/dev/null || echo \"\")\n\
1252                     \n\
1253                     if [ -n \"$ACTIVE_STACK\" ]; then\n\
1254                         # Get current commit message\n\
1255                         CURRENT_MSG=$(cat \"$COMMIT_MSG_FILE\")\n\
1256                         \n\
1257                         # Skip if message already has stack context\n\
1258                         if echo \"$CURRENT_MSG\" | grep -q \"\\[stack:\"; then\n\
1259                             exit 0\n\
1260                         fi\n\
1261                         \n\
1262                         # Add stack context to commit message\n\
1263                         echo \"\n\
1264                     # Stack: $ACTIVE_STACK\n\
1265                     # This commit will be added to the active stack automatically.\n\
1266                     # Use 'ca stack status' to see the current stack state.\n\
1267                     $CURRENT_MSG\" > \"$COMMIT_MSG_FILE\"\n\
1268                     fi\n\
1269                 fi\n"
1270            )
1271        }
1272    }
1273
1274    /// Detect repository type from remote URLs
1275    pub fn detect_repository_type(&self) -> Result<RepositoryType> {
1276        let output = Command::new("git")
1277            .args(["remote", "get-url", "origin"])
1278            .current_dir(&self.repo_path)
1279            .output()
1280            .map_err(|e| CascadeError::config(format!("Failed to get remote URL: {e}")))?;
1281
1282        if !output.status.success() {
1283            return Ok(RepositoryType::Unknown);
1284        }
1285
1286        let remote_url = String::from_utf8_lossy(&output.stdout)
1287            .trim()
1288            .to_lowercase();
1289
1290        if remote_url.contains("github.com") {
1291            Ok(RepositoryType::GitHub)
1292        } else if remote_url.contains("gitlab.com") || remote_url.contains("gitlab") {
1293            Ok(RepositoryType::GitLab)
1294        } else if remote_url.contains("dev.azure.com") || remote_url.contains("visualstudio.com") {
1295            Ok(RepositoryType::AzureDevOps)
1296        } else if remote_url.contains("bitbucket") {
1297            Ok(RepositoryType::Bitbucket)
1298        } else {
1299            Ok(RepositoryType::Unknown)
1300        }
1301    }
1302
1303    /// Detect current branch type
1304    pub fn detect_branch_type(&self) -> Result<BranchType> {
1305        let output = Command::new("git")
1306            .args(["branch", "--show-current"])
1307            .current_dir(&self.repo_path)
1308            .output()
1309            .map_err(|e| CascadeError::config(format!("Failed to get current branch: {e}")))?;
1310
1311        if !output.status.success() {
1312            return Ok(BranchType::Unknown);
1313        }
1314
1315        let branch_name = String::from_utf8_lossy(&output.stdout)
1316            .trim()
1317            .to_lowercase();
1318
1319        if branch_name == "main" || branch_name == "master" || branch_name == "develop" {
1320            Ok(BranchType::Main)
1321        } else if !branch_name.is_empty() {
1322            Ok(BranchType::Feature)
1323        } else {
1324            Ok(BranchType::Unknown)
1325        }
1326    }
1327
1328    /// Validate prerequisites for hook installation
1329    pub fn validate_prerequisites(&self) -> Result<()> {
1330        Output::check_start("Checking prerequisites for Cascade hooks");
1331
1332        // 1. Check repository type
1333        let repo_type = self.detect_repository_type()?;
1334        match repo_type {
1335            RepositoryType::Bitbucket => {
1336                Output::success("Bitbucket repository detected");
1337                Output::tip("Hooks will work great with 'ca submit' and 'ca autoland' for Bitbucket integration");
1338            }
1339            RepositoryType::GitHub => {
1340                Output::success("GitHub repository detected");
1341                Output::tip("Consider setting up GitHub Actions for CI/CD integration");
1342            }
1343            RepositoryType::GitLab => {
1344                Output::success("GitLab repository detected");
1345                Output::tip("GitLab CI integration works well with Cascade stacks");
1346            }
1347            RepositoryType::AzureDevOps => {
1348                Output::success("Azure DevOps repository detected");
1349                Output::tip("Azure Pipelines can be configured to work with Cascade workflows");
1350            }
1351            RepositoryType::Unknown => {
1352                Output::info(
1353                    "Unknown repository type - hooks will still work for local Git operations",
1354                );
1355            }
1356        }
1357
1358        // 2. Check Cascade configuration
1359        let config_dir = crate::config::get_repo_config_dir(&self.repo_path)?;
1360        let config_path = config_dir.join("config.json");
1361        if !config_path.exists() {
1362            return Err(CascadeError::config(
1363                "🚫 Cascade not initialized!\n\n\
1364                Please run 'ca init' or 'ca setup' first to configure Cascade CLI.\n\
1365                Hooks require proper Bitbucket Server configuration.\n\n\
1366                Use --force to install anyway (not recommended)."
1367                    .to_string(),
1368            ));
1369        }
1370
1371        // 3. Validate Bitbucket configuration
1372        let config = Settings::load_from_file(&config_path)?;
1373
1374        if config.bitbucket.url == "https://bitbucket.example.com"
1375            || config.bitbucket.url.contains("example.com")
1376        {
1377            return Err(CascadeError::config(
1378                "🚫 Invalid Bitbucket configuration!\n\n\
1379                Your Bitbucket URL appears to be a placeholder.\n\
1380                Please run 'ca setup' to configure a real Bitbucket Server.\n\n\
1381                Use --force to install anyway (not recommended)."
1382                    .to_string(),
1383            ));
1384        }
1385
1386        if config.bitbucket.project == "PROJECT" || config.bitbucket.repo == "repo" {
1387            return Err(CascadeError::config(
1388                "🚫 Incomplete Bitbucket configuration!\n\n\
1389                Your project/repository settings appear to be placeholders.\n\
1390                Please run 'ca setup' to complete configuration.\n\n\
1391                Use --force to install anyway (not recommended)."
1392                    .to_string(),
1393            ));
1394        }
1395
1396        Output::success("Prerequisites validation passed");
1397        Ok(())
1398    }
1399
1400    /// Validate branch suitability for hooks
1401    pub fn validate_branch_suitability(&self) -> Result<()> {
1402        let branch_type = self.detect_branch_type()?;
1403
1404        match branch_type {
1405            BranchType::Main => {
1406                return Err(CascadeError::config(
1407                    "🚫 Currently on main/master branch!\n\n\
1408                    Cascade hooks are designed for feature branch development.\n\
1409                    Working directly on main/master with stacked diffs can:\n\
1410                    • Complicate the commit history\n\
1411                    • Interfere with team collaboration\n\
1412                    • Break CI/CD workflows\n\n\
1413                    💡 Recommended workflow:\n\
1414                    1. Create a feature branch: git checkout -b feature/my-feature\n\
1415                    2. Install hooks: ca hooks install\n\
1416                    3. Develop with stacked commits (auto-added with hooks)\n\
1417                    4. Push & submit: ca push && ca submit (all by default)\n\
1418                    5. Auto-land when ready: ca autoland\n\n\
1419                    Use --force to install anyway (not recommended)."
1420                        .to_string(),
1421                ));
1422            }
1423            BranchType::Feature => {
1424                Output::success("Feature branch detected - suitable for stacked development");
1425            }
1426            BranchType::Unknown => {
1427                Output::warning("Unknown branch type - proceeding with caution");
1428            }
1429        }
1430
1431        Ok(())
1432    }
1433
1434    /// Confirm installation with user
1435    pub fn confirm_installation(&self) -> Result<()> {
1436        Output::section("Hook Installation Summary");
1437
1438        let hooks = vec![
1439            HookType::PostCommit,
1440            HookType::PrePush,
1441            HookType::CommitMsg,
1442            HookType::PrepareCommitMsg,
1443        ];
1444
1445        for hook in &hooks {
1446            Output::sub_item(format!("{}: {}", hook.filename(), hook.description()));
1447        }
1448
1449        println!();
1450        Output::section("These hooks will automatically");
1451        Output::bullet("Add commits to your active stack");
1452        Output::bullet("Validate commit messages");
1453        Output::bullet("Prevent force pushes that break stack integrity");
1454        Output::bullet("Add stack context to commit messages");
1455
1456        println!();
1457        Output::section("With hooks + new defaults, your workflow becomes");
1458        Output::sub_item("git commit       → Auto-added to stack");
1459        Output::sub_item("ca push          → Pushes all by default");
1460        Output::sub_item("ca submit        → Submits all by default");
1461        Output::sub_item("ca autoland      → Auto-merges when ready");
1462
1463        // Interactive confirmation to proceed with installation
1464        let should_install = Confirm::with_theme(&ColorfulTheme::default())
1465            .with_prompt("Install Cascade hooks?")
1466            .default(true)
1467            .interact()
1468            .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
1469
1470        if should_install {
1471            Output::success("Proceeding with installation");
1472            Ok(())
1473        } else {
1474            Err(CascadeError::config(
1475                "Installation cancelled by user".to_string(),
1476            ))
1477        }
1478    }
1479}
1480
1481/// Run hooks management commands
1482pub async fn install() -> Result<()> {
1483    install_with_options(false, false, false, false).await
1484}
1485
1486pub async fn install_essential() -> Result<()> {
1487    let current_dir = env::current_dir()
1488        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1489
1490    let repo_root = find_repository_root(&current_dir)
1491        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1492
1493    let hooks_manager = HooksManager::new(&repo_root)?;
1494    hooks_manager.install_essential()
1495}
1496
1497pub async fn install_with_options(
1498    skip_checks: bool,
1499    allow_main_branch: bool,
1500    yes: bool,
1501    force: bool,
1502) -> Result<()> {
1503    let current_dir = env::current_dir()
1504        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1505
1506    let repo_root = find_repository_root(&current_dir)
1507        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1508
1509    let hooks_manager = HooksManager::new(&repo_root)?;
1510
1511    let options = InstallOptions {
1512        check_prerequisites: !skip_checks,
1513        feature_branches_only: !allow_main_branch,
1514        confirm: !yes,
1515        force,
1516    };
1517
1518    hooks_manager.install_with_options(&options)
1519}
1520
1521pub async fn uninstall() -> Result<()> {
1522    let current_dir = env::current_dir()
1523        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1524
1525    let repo_root = find_repository_root(&current_dir)
1526        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1527
1528    let hooks_manager = HooksManager::new(&repo_root)?;
1529    hooks_manager.uninstall_all()
1530}
1531
1532pub async fn status() -> Result<()> {
1533    let current_dir = env::current_dir()
1534        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1535
1536    let repo_root = find_repository_root(&current_dir)
1537        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1538
1539    let hooks_manager = HooksManager::new(&repo_root)?;
1540    hooks_manager.list_installed_hooks()
1541}
1542
1543pub async fn install_hook(hook_name: &str) -> Result<()> {
1544    install_hook_with_options(hook_name, false, false).await
1545}
1546
1547pub async fn install_hook_with_options(
1548    hook_name: &str,
1549    skip_checks: bool,
1550    force: bool,
1551) -> Result<()> {
1552    let current_dir = env::current_dir()
1553        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1554
1555    let repo_root = find_repository_root(&current_dir)
1556        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1557
1558    let hooks_manager = HooksManager::new(&repo_root)?;
1559
1560    let hook_type = match hook_name {
1561        "post-commit" => HookType::PostCommit,
1562        "pre-push" => HookType::PrePush,
1563        "commit-msg" => HookType::CommitMsg,
1564        "pre-commit" => HookType::PreCommit,
1565        "prepare-commit-msg" => HookType::PrepareCommitMsg,
1566        _ => {
1567            return Err(CascadeError::config(format!(
1568                "Unknown hook type: {hook_name}"
1569            )))
1570        }
1571    };
1572
1573    // Run basic validation if not skipped
1574    if !skip_checks && !force {
1575        hooks_manager.validate_prerequisites()?;
1576    }
1577
1578    hooks_manager.install_hook(&hook_type)
1579}
1580
1581pub async fn uninstall_hook(hook_name: &str) -> Result<()> {
1582    let current_dir = env::current_dir()
1583        .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1584
1585    let repo_root = find_repository_root(&current_dir)
1586        .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1587
1588    let hooks_manager = HooksManager::new(&repo_root)?;
1589
1590    let hook_type = match hook_name {
1591        "post-commit" => HookType::PostCommit,
1592        "pre-push" => HookType::PrePush,
1593        "commit-msg" => HookType::CommitMsg,
1594        "pre-commit" => HookType::PreCommit,
1595        "prepare-commit-msg" => HookType::PrepareCommitMsg,
1596        _ => {
1597            return Err(CascadeError::config(format!(
1598                "Unknown hook type: {hook_name}"
1599            )))
1600        }
1601    };
1602
1603    hooks_manager.uninstall_hook(&hook_type)
1604}
1605
1606#[cfg(test)]
1607mod tests {
1608    use super::*;
1609    use std::process::Command;
1610    use tempfile::TempDir;
1611
1612    fn create_test_repo() -> (TempDir, std::path::PathBuf) {
1613        let temp_dir = TempDir::new().unwrap();
1614        let repo_path = temp_dir.path().to_path_buf();
1615
1616        // Initialize git repository
1617        Command::new("git")
1618            .args(["init"])
1619            .current_dir(&repo_path)
1620            .output()
1621            .unwrap();
1622        Command::new("git")
1623            .args(["config", "user.name", "Test"])
1624            .current_dir(&repo_path)
1625            .output()
1626            .unwrap();
1627        Command::new("git")
1628            .args(["config", "user.email", "test@test.com"])
1629            .current_dir(&repo_path)
1630            .output()
1631            .unwrap();
1632
1633        // Create initial commit
1634        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1635        Command::new("git")
1636            .args(["add", "."])
1637            .current_dir(&repo_path)
1638            .output()
1639            .unwrap();
1640        Command::new("git")
1641            .args(["commit", "-m", "Initial"])
1642            .current_dir(&repo_path)
1643            .output()
1644            .unwrap();
1645
1646        // Initialize cascade
1647        crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
1648            .unwrap();
1649
1650        (temp_dir, repo_path)
1651    }
1652
1653    #[test]
1654    fn test_hooks_manager_creation() {
1655        let (_temp_dir, repo_path) = create_test_repo();
1656        let _manager = HooksManager::new(&repo_path).unwrap();
1657
1658        assert_eq!(_manager.repo_path, repo_path);
1659        // Should create a HooksManager successfully
1660        assert!(!_manager.repo_id.is_empty());
1661    }
1662
1663    #[test]
1664    fn test_hooks_manager_custom_hooks_path() {
1665        let (_temp_dir, repo_path) = create_test_repo();
1666
1667        // Set custom hooks path
1668        Command::new("git")
1669            .args(["config", "core.hooksPath", "custom-hooks"])
1670            .current_dir(&repo_path)
1671            .output()
1672            .unwrap();
1673
1674        // Create the custom hooks directory
1675        let custom_hooks_dir = repo_path.join("custom-hooks");
1676        std::fs::create_dir_all(&custom_hooks_dir).unwrap();
1677
1678        let _manager = HooksManager::new(&repo_path).unwrap();
1679
1680        assert_eq!(_manager.repo_path, repo_path);
1681        // Should create a HooksManager successfully
1682        assert!(!_manager.repo_id.is_empty());
1683    }
1684
1685    #[test]
1686    fn test_hook_chaining_with_existing_hooks() {
1687        let (_temp_dir, repo_path) = create_test_repo();
1688        let manager = HooksManager::new(&repo_path).unwrap();
1689
1690        let hook_type = HookType::PreCommit;
1691        let hook_path = repo_path.join(".git/hooks").join(hook_type.filename());
1692
1693        // Create an existing project hook
1694        let existing_hook_content = "#!/bin/bash\n# Project pre-commit hook\n./scripts/lint.sh\n";
1695        std::fs::write(&hook_path, existing_hook_content).unwrap();
1696        crate::utils::platform::make_executable(&hook_path).unwrap();
1697
1698        // Install cascade hook (uses core.hooksPath, doesn't modify original)
1699        let result = manager.install_hook(&hook_type);
1700        assert!(result.is_ok());
1701
1702        // Original hook should remain unchanged
1703        let original_content = std::fs::read_to_string(&hook_path).unwrap();
1704        assert!(original_content.contains("# Project pre-commit hook"));
1705        assert!(original_content.contains("./scripts/lint.sh"));
1706
1707        // Cascade hook should exist in cascade directory
1708        let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
1709        let cascade_hook_path = cascade_hooks_dir.join(hook_type.filename());
1710        assert!(cascade_hook_path.exists());
1711
1712        // Test uninstall removes cascade hooks but leaves original
1713        let uninstall_result = manager.uninstall_hook(&hook_type);
1714        assert!(uninstall_result.is_ok());
1715
1716        // Original hook should still exist and be unchanged
1717        let after_uninstall = std::fs::read_to_string(&hook_path).unwrap();
1718        assert!(after_uninstall.contains("# Project pre-commit hook"));
1719        assert!(after_uninstall.contains("./scripts/lint.sh"));
1720
1721        // Cascade hook should be removed
1722        assert!(!cascade_hook_path.exists());
1723    }
1724
1725    #[test]
1726    fn test_hook_installation() {
1727        let (_temp_dir, repo_path) = create_test_repo();
1728        let manager = HooksManager::new(&repo_path).unwrap();
1729
1730        // Test installing post-commit hook
1731        let hook_type = HookType::PostCommit;
1732        let result = manager.install_hook(&hook_type);
1733        assert!(result.is_ok());
1734
1735        // Verify hook file exists in cascade hooks directory
1736        let hook_filename = hook_type.filename();
1737        let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
1738        let hook_path = cascade_hooks_dir.join(&hook_filename);
1739        assert!(hook_path.exists());
1740
1741        // Verify hook is executable (platform-specific)
1742        #[cfg(unix)]
1743        {
1744            use std::os::unix::fs::PermissionsExt;
1745            let metadata = std::fs::metadata(&hook_path).unwrap();
1746            let permissions = metadata.permissions();
1747            assert!(permissions.mode() & 0o111 != 0); // Check executable bit
1748        }
1749
1750        #[cfg(windows)]
1751        {
1752            // On Windows, verify it has .bat extension and file exists
1753            assert!(hook_filename.ends_with(".bat"));
1754            assert!(hook_path.exists());
1755        }
1756    }
1757
1758    #[test]
1759    fn test_hook_detection() {
1760        let (_temp_dir, repo_path) = create_test_repo();
1761        let _manager = HooksManager::new(&repo_path).unwrap();
1762
1763        // Check if hook files exist with platform-appropriate filenames
1764        let post_commit_path = repo_path
1765            .join(".git/hooks")
1766            .join(HookType::PostCommit.filename());
1767        let pre_push_path = repo_path
1768            .join(".git/hooks")
1769            .join(HookType::PrePush.filename());
1770        let commit_msg_path = repo_path
1771            .join(".git/hooks")
1772            .join(HookType::CommitMsg.filename());
1773
1774        // Initially no hooks should be installed
1775        assert!(!post_commit_path.exists());
1776        assert!(!pre_push_path.exists());
1777        assert!(!commit_msg_path.exists());
1778    }
1779
1780    #[test]
1781    fn test_hook_validation() {
1782        let (_temp_dir, repo_path) = create_test_repo();
1783        let manager = HooksManager::new(&repo_path).unwrap();
1784
1785        // Test validation - may fail in CI due to missing dependencies
1786        let validation = manager.validate_prerequisites();
1787        // In CI environment, validation might fail due to missing configuration
1788        // Just ensure it doesn't panic
1789        let _ = validation; // Don't assert ok/err, just ensure no panic
1790
1791        // Test branch validation - should work regardless of environment
1792        let branch_validation = manager.validate_branch_suitability();
1793        // Branch validation should work in most cases, but be tolerant
1794        let _ = branch_validation; // Don't assert ok/err, just ensure no panic
1795    }
1796
1797    #[test]
1798    fn test_hook_uninstallation() {
1799        let (_temp_dir, repo_path) = create_test_repo();
1800        let manager = HooksManager::new(&repo_path).unwrap();
1801
1802        // Install then uninstall hook
1803        let hook_type = HookType::PostCommit;
1804        manager.install_hook(&hook_type).unwrap();
1805
1806        let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
1807        let hook_path = cascade_hooks_dir.join(hook_type.filename());
1808        assert!(hook_path.exists());
1809
1810        let result = manager.uninstall_hook(&hook_type);
1811        assert!(result.is_ok());
1812        assert!(!hook_path.exists());
1813    }
1814
1815    #[test]
1816    fn test_hook_content_generation() {
1817        let (_temp_dir, repo_path) = create_test_repo();
1818        let manager = HooksManager::new(&repo_path).unwrap();
1819
1820        // Use a known binary name for testing
1821        let binary_name = "cascade-cli";
1822
1823        // Test post-commit hook generation
1824        let post_commit_content = manager.generate_post_commit_hook(binary_name);
1825        #[cfg(windows)]
1826        {
1827            assert!(post_commit_content.contains("@echo off"));
1828            assert!(post_commit_content.contains("rem Cascade CLI Hook"));
1829        }
1830        #[cfg(not(windows))]
1831        {
1832            assert!(post_commit_content.contains("#!/bin/sh"));
1833            assert!(post_commit_content.contains("# Cascade CLI Hook"));
1834        }
1835        assert!(post_commit_content.contains(binary_name));
1836
1837        // Test pre-push hook generation
1838        let pre_push_content = manager.generate_pre_push_hook(binary_name);
1839        #[cfg(windows)]
1840        {
1841            assert!(pre_push_content.contains("@echo off"));
1842            assert!(pre_push_content.contains("rem Cascade CLI Hook"));
1843        }
1844        #[cfg(not(windows))]
1845        {
1846            assert!(pre_push_content.contains("#!/bin/sh"));
1847            assert!(pre_push_content.contains("# Cascade CLI Hook"));
1848        }
1849        assert!(pre_push_content.contains(binary_name));
1850
1851        // Test commit-msg hook generation (doesn't use binary, just validates)
1852        let commit_msg_content = manager.generate_commit_msg_hook(binary_name);
1853        #[cfg(windows)]
1854        {
1855            assert!(commit_msg_content.contains("@echo off"));
1856            assert!(commit_msg_content.contains("rem Cascade CLI Hook"));
1857        }
1858        #[cfg(not(windows))]
1859        {
1860            assert!(commit_msg_content.contains("#!/bin/sh"));
1861            assert!(commit_msg_content.contains("# Cascade CLI Hook"));
1862        }
1863
1864        // Test prepare-commit-msg hook generation (does use binary)
1865        let prepare_commit_content = manager.generate_prepare_commit_msg_hook(binary_name);
1866        #[cfg(windows)]
1867        {
1868            assert!(prepare_commit_content.contains("@echo off"));
1869            assert!(prepare_commit_content.contains("rem Cascade CLI Hook"));
1870        }
1871        #[cfg(not(windows))]
1872        {
1873            assert!(prepare_commit_content.contains("#!/bin/sh"));
1874            assert!(prepare_commit_content.contains("# Cascade CLI Hook"));
1875        }
1876        assert!(prepare_commit_content.contains(binary_name));
1877    }
1878
1879    #[test]
1880    fn test_hook_status_reporting() {
1881        let (_temp_dir, repo_path) = create_test_repo();
1882        let manager = HooksManager::new(&repo_path).unwrap();
1883
1884        // Check repository type detection - should work with our test setup
1885        let repo_type = manager.detect_repository_type().unwrap();
1886        // In CI environment, this might be Unknown if remote detection fails
1887        assert!(matches!(
1888            repo_type,
1889            RepositoryType::Bitbucket | RepositoryType::Unknown
1890        ));
1891
1892        // Check branch type detection
1893        let branch_type = manager.detect_branch_type().unwrap();
1894        // Should be on main/master branch, but allow for different default branch names
1895        assert!(matches!(
1896            branch_type,
1897            BranchType::Main | BranchType::Unknown
1898        ));
1899    }
1900
1901    #[test]
1902    fn test_force_installation() {
1903        let (_temp_dir, repo_path) = create_test_repo();
1904        let manager = HooksManager::new(&repo_path).unwrap();
1905
1906        // Create a fake existing hook with platform-appropriate content
1907        let hook_filename = HookType::PostCommit.filename();
1908        let hook_path = repo_path.join(".git/hooks").join(&hook_filename);
1909
1910        #[cfg(windows)]
1911        let existing_content = "@echo off\necho existing hook";
1912        #[cfg(not(windows))]
1913        let existing_content = "#!/bin/sh\necho 'existing hook'";
1914
1915        std::fs::write(&hook_path, existing_content).unwrap();
1916
1917        // Install cascade hook (uses core.hooksPath, doesn't modify original)
1918        let hook_type = HookType::PostCommit;
1919        let result = manager.install_hook(&hook_type);
1920        assert!(result.is_ok());
1921
1922        // Verify cascade hook exists in cascade directory
1923        let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
1924        let cascade_hook_path = cascade_hooks_dir.join(&hook_filename);
1925        assert!(cascade_hook_path.exists());
1926
1927        // Original hook should remain unchanged
1928        let original_content = std::fs::read_to_string(&hook_path).unwrap();
1929        assert!(original_content.contains("existing hook"));
1930
1931        // Cascade hook should contain cascade logic
1932        let cascade_content = std::fs::read_to_string(&cascade_hook_path).unwrap();
1933        assert!(cascade_content.contains("cascade-cli") || cascade_content.contains("ca"));
1934    }
1935}