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