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