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