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