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 println!();
492 Output::sub_item("To install Cascade hooks:");
493 Output::command_example("ca hooks install # recommended: 4 essential hooks");
494 Output::command_example(
495 "ca hooks install --all # all 5 hooks + post-commit auto-add",
496 );
497 println!();
498 Output::sub_item("Both options preserve existing hooks by chaining to them");
499 println!();
500 }
501
502 for hook in hooks {
503 let cascade_hook_path = cascade_hooks_dir.join(hook.filename());
504
505 if using_cascade_hooks && cascade_hook_path.exists() {
506 Output::success(format!("{}: {} ✓", hook.filename(), hook.description()));
507 } else {
508 let default_hook_path = self
510 .repo_path
511 .join(".git")
512 .join("hooks")
513 .join(hook.filename());
514 if default_hook_path.exists() {
515 Output::warning(format!(
516 "{}: {} (In .git/hooks, not managed by Cascade)",
517 hook.filename(),
518 hook.description()
519 ));
520 } else {
521 Output::error(format!(
522 "{}: {} (Not installed)",
523 hook.filename(),
524 hook.description()
525 ));
526 }
527 }
528 }
529
530 Ok(())
531 }
532
533 fn get_current_hooks_path(&self) -> Result<Option<String>> {
535 use std::process::Command;
536
537 let output = Command::new("git")
538 .args(["config", "--get", "core.hooksPath"])
539 .current_dir(&self.repo_path)
540 .output()
541 .map_err(|e| CascadeError::config(format!("Failed to check git config: {e}")))?;
542
543 if output.status.success() {
544 let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
545 if path.is_empty() {
546 Ok(None)
547 } else {
548 Ok(Some(path))
549 }
550 } else {
551 Ok(None)
552 }
553 }
554
555 pub fn generate_hook_script(&self, hook_type: &HookType) -> Result<String> {
557 let cascade_cli = env::current_exe()
558 .map_err(|e| {
559 CascadeError::config(format!("Failed to get current executable path: {e}"))
560 })?
561 .to_string_lossy()
562 .to_string();
563
564 let script = match hook_type {
565 HookType::PostCommit => self.generate_post_commit_hook(&cascade_cli),
566 HookType::PrePush => self.generate_pre_push_hook(&cascade_cli),
567 HookType::CommitMsg => self.generate_commit_msg_hook(&cascade_cli),
568 HookType::PreCommit => self.generate_pre_commit_hook(&cascade_cli),
569 HookType::PrepareCommitMsg => self.generate_prepare_commit_msg_hook(&cascade_cli),
570 };
571
572 Ok(script)
573 }
574
575 pub fn generate_chaining_hook_script(&self, hook_type: &HookType) -> Result<String> {
577 let cascade_cli = env::current_exe()
578 .map_err(|e| {
579 CascadeError::config(format!("Failed to get current executable path: {e}"))
580 })?
581 .to_string_lossy()
582 .to_string();
583
584 let config_dir = self.get_cascade_config_dir()?;
585 let hook_name = match hook_type {
586 HookType::PostCommit => "post-commit",
587 HookType::PrePush => "pre-push",
588 HookType::CommitMsg => "commit-msg",
589 HookType::PreCommit => "pre-commit",
590 HookType::PrepareCommitMsg => "prepare-commit-msg",
591 };
592
593 let cascade_logic = match hook_type {
595 HookType::PostCommit => self.generate_post_commit_hook(&cascade_cli),
596 HookType::PrePush => self.generate_pre_push_hook(&cascade_cli),
597 HookType::CommitMsg => self.generate_commit_msg_hook(&cascade_cli),
598 HookType::PreCommit => self.generate_pre_commit_hook(&cascade_cli),
599 HookType::PrepareCommitMsg => self.generate_prepare_commit_msg_hook(&cascade_cli),
600 };
601
602 #[cfg(windows)]
604 return Ok(format!(
605 "@echo off\n\
606 rem Cascade CLI Hook Wrapper - {}\n\
607 rem This hook runs Cascade logic first, then chains to original hooks\n\n\
608 rem Run Cascade logic first\n\
609 call :cascade_logic %*\n\
610 set CASCADE_RESULT=%ERRORLEVEL%\n\
611 if %CASCADE_RESULT% neq 0 exit /b %CASCADE_RESULT%\n\n\
612 rem Check for original hook\n\
613 set ORIGINAL_HOOKS_PATH=\n\
614 if exist \"{}\\original-hooks-path\" (\n\
615 set /p ORIGINAL_HOOKS_PATH=<\"{}\\original-hooks-path\"\n\
616 )\n\n\
617 if \"%ORIGINAL_HOOKS_PATH%\"==\"\" (\n\
618 rem Default location\n\
619 for /f \"tokens=*\" %%i in ('git rev-parse --git-dir 2^>nul') do set GIT_DIR=%%i\n\
620 if exist \"%GIT_DIR%\\hooks\\{}\" (\n\
621 call \"%GIT_DIR%\\hooks\\{}\" %*\n\
622 exit /b %ERRORLEVEL%\n\
623 )\n\
624 ) else (\n\
625 rem Custom hooks path\n\
626 if exist \"%ORIGINAL_HOOKS_PATH%\\{}\" (\n\
627 call \"%ORIGINAL_HOOKS_PATH%\\{}\" %*\n\
628 exit /b %ERRORLEVEL%\n\
629 )\n\
630 )\n\n\
631 exit /b 0\n\n\
632 :cascade_logic\n\
633 {}\n\
634 exit /b %ERRORLEVEL%\n",
635 hook_name,
636 config_dir.to_string_lossy(),
637 config_dir.to_string_lossy(),
638 hook_name,
639 hook_name,
640 hook_name,
641 hook_name,
642 cascade_logic
643 ));
644
645 #[cfg(not(windows))]
646 Ok(format!(
647 "#!/bin/sh\n\
648 # Cascade CLI Hook Wrapper - {}\n\
649 # This hook runs Cascade logic first, then chains to original hooks\n\n\
650 set -e\n\n\
651 # Function to run Cascade logic\n\
652 cascade_logic() {{\n\
653 {}\n\
654 }}\n\n\
655 # Run Cascade logic first\n\
656 cascade_logic \"$@\"\n\
657 CASCADE_RESULT=$?\n\
658 if [ $CASCADE_RESULT -ne 0 ]; then\n\
659 exit $CASCADE_RESULT\n\
660 fi\n\n\
661 # Check for original hook\n\
662 ORIGINAL_HOOKS_PATH=\"\"\n\
663 if [ -f \"{}/original-hooks-path\" ]; then\n\
664 ORIGINAL_HOOKS_PATH=$(cat \"{}/original-hooks-path\" 2>/dev/null || echo \"\")\n\
665 fi\n\n\
666 if [ -z \"$ORIGINAL_HOOKS_PATH\" ]; then\n\
667 # Default location\n\
668 GIT_DIR=$(git rev-parse --git-dir 2>/dev/null || echo \".git\")\n\
669 ORIGINAL_HOOK=\"$GIT_DIR/hooks/{}\"\n\
670 else\n\
671 # Custom hooks path\n\
672 ORIGINAL_HOOK=\"$ORIGINAL_HOOKS_PATH/{}\"\n\
673 fi\n\n\
674 # Run original hook if it exists and is executable\n\
675 if [ -x \"$ORIGINAL_HOOK\" ]; then\n\
676 \"$ORIGINAL_HOOK\" \"$@\"\n\
677 exit $?\n\
678 fi\n\n\
679 exit 0\n",
680 hook_name,
681 cascade_logic.trim_start_matches("#!/bin/sh\n").trim_start_matches("set -e\n"),
682 config_dir.to_string_lossy(),
683 config_dir.to_string_lossy(),
684 hook_name,
685 hook_name
686 ))
687 }
688
689 fn generate_post_commit_hook(&self, cascade_cli: &str) -> String {
690 #[cfg(windows)]
691 {
692 format!(
693 "@echo off\n\
694 rem Cascade CLI Hook - Post Commit\n\
695 rem Automatically adds new commits to the active stack\n\n\
696 rem Get the commit hash and message\n\
697 for /f \"tokens=*\" %%i in ('git rev-parse HEAD') do set COMMIT_HASH=%%i\n\
698 for /f \"tokens=*\" %%i in ('git log --format=%%s -n 1 HEAD') do set COMMIT_MSG=%%i\n\n\
699 rem Find repository root and check if Cascade is initialized\n\
700 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
701 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
702 if not exist \"%REPO_ROOT%\\.cascade\" (\n\
703 echo ℹ️ Cascade not initialized, skipping stack management\n\
704 echo 💡 Run 'ca init' to start using stacked diffs\n\
705 exit /b 0\n\
706 )\n\n\
707 rem Check if there's an active stack\n\
708 \"{cascade_cli}\" stack list --active >nul 2>&1\n\
709 if %ERRORLEVEL% neq 0 (\n\
710 echo ℹ️ No active stack found, commit will not be added to any stack\n\
711 echo 💡 Use 'ca stack create ^<name^>' to create a stack for this commit\n\
712 exit /b 0\n\
713 )\n\n\
714 rem Add commit to active stack\n\
715 echo 🪝 Adding commit to active stack...\n\
716 echo 📝 Commit: %COMMIT_MSG%\n\
717 \"{cascade_cli}\" stack push --commit \"%COMMIT_HASH%\" --message \"%COMMIT_MSG%\"\n\
718 if %ERRORLEVEL% equ 0 (\n\
719 echo ✅ Commit added to stack successfully\n\
720 echo 💡 Next: 'ca submit' to create PRs when ready\n\
721 ) else (\n\
722 echo ⚠️ Failed to add commit to stack\n\
723 echo 💡 You can manually add it with: ca push --commit %COMMIT_HASH%\n\
724 )\n"
725 )
726 }
727
728 #[cfg(not(windows))]
729 {
730 format!(
731 "#!/bin/sh\n\
732 # Cascade CLI Hook - Post Commit\n\
733 # Automatically adds new commits to the active stack\n\n\
734 set -e\n\n\
735 # Get the commit hash and message\n\
736 COMMIT_HASH=$(git rev-parse HEAD)\n\
737 COMMIT_MSG=$(git log --format=%s -n 1 HEAD)\n\n\
738 # Find repository root and check if Cascade is initialized\n\
739 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
740 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
741 echo \"ℹ️ Cascade not initialized, skipping stack management\"\n\
742 echo \"💡 Run 'ca init' to start using stacked diffs\"\n\
743 exit 0\n\
744 fi\n\n\
745 # Check if there's an active stack\n\
746 if ! \"{cascade_cli}\" stack list --active > /dev/null 2>&1; then\n\
747 echo \"ℹ️ No active stack found, commit will not be added to any stack\"\n\
748 echo \"💡 Use 'ca stack create <name>' to create a stack for this commit\"\n\
749 exit 0\n\
750 fi\n\n\
751 # Add commit to active stack (using specific commit targeting)\n\
752 echo \"🪝 Adding commit to active stack...\"\n\
753 echo \"📝 Commit: $COMMIT_MSG\"\n\
754 if \"{cascade_cli}\" stack push --commit \"$COMMIT_HASH\" --message \"$COMMIT_MSG\"; then\n\
755 echo \"✅ Commit added to stack successfully\"\n\
756 echo \"💡 Next: 'ca submit' to create PRs when ready\"\n\
757 else\n\
758 echo \"⚠️ Failed to add commit to stack\"\n\
759 echo \"💡 You can manually add it with: ca push --commit $COMMIT_HASH\"\n\
760 fi\n"
761 )
762 }
763 }
764
765 fn generate_pre_push_hook(&self, cascade_cli: &str) -> String {
766 #[cfg(windows)]
767 {
768 format!(
769 "@echo off\n\
770 rem Cascade CLI Hook - Pre Push\n\
771 rem Prevents force pushes and validates stack state\n\n\
772 rem Check for force push\n\
773 echo %* | findstr /C:\"--force\" /C:\"--force-with-lease\" /C:\"-f\" >nul\n\
774 if %ERRORLEVEL% equ 0 (\n\
775 echo ❌ Force push detected!\n\
776 echo 🌊 Cascade CLI uses stacked diffs - force pushes can break stack integrity\n\
777 echo.\n\
778 echo 💡 Instead of force pushing, try these streamlined commands:\n\
779 echo • ca sync - Sync with remote changes ^(handles rebasing^)\n\
780 echo • ca push - Push all unpushed commits ^(new default^)\n\
781 echo • ca submit - Submit all entries for review ^(new default^)\n\
782 echo • ca autoland - Auto-merge when approved + builds pass\n\
783 echo.\n\
784 echo 🚨 If you really need to force push, run:\n\
785 echo git push --force-with-lease [remote] [branch]\n\
786 echo ^(But consider if this will affect other stack entries^)\n\
787 exit /b 1\n\
788 )\n\n\
789 rem Find repository root and check if Cascade is initialized\n\
790 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
791 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
792 if not exist \"%REPO_ROOT%\\.cascade\" (\n\
793 echo ℹ️ Cascade not initialized, allowing push\n\
794 exit /b 0\n\
795 )\n\n\
796 rem Validate stack state\n\
797 echo 🪝 Validating stack state before push...\n\
798 \"{cascade_cli}\" stack validate\n\
799 if %ERRORLEVEL% equ 0 (\n\
800 echo ✅ Stack validation passed\n\
801 ) else (\n\
802 echo ❌ Stack validation failed\n\
803 echo 💡 Fix validation errors before pushing:\n\
804 echo • ca doctor - Check overall health\n\
805 echo • ca status - Check current stack status\n\
806 echo • ca sync - Sync with remote and rebase if needed\n\
807 exit /b 1\n\
808 )\n\n\
809 echo ✅ Pre-push validation complete\n"
810 )
811 }
812
813 #[cfg(not(windows))]
814 {
815 format!(
816 "#!/bin/sh\n\
817 # Cascade CLI Hook - Pre Push\n\
818 # Prevents force pushes and validates stack state\n\n\
819 set -e\n\n\
820 # Check for force push\n\
821 if echo \"$*\" | grep -q -- \"--force\\|--force-with-lease\\|-f\"; then\n\
822 echo \"❌ Force push detected!\"\n\
823 echo \"🌊 Cascade CLI uses stacked diffs - force pushes can break stack integrity\"\n\
824 echo \"\"\n\
825 echo \"💡 Instead of force pushing, try these streamlined commands:\"\n\
826 echo \" • ca sync - Sync with remote changes (handles rebasing)\"\n\
827 echo \" • ca push - Push all unpushed commits (new default)\"\n\
828 echo \" • ca submit - Submit all entries for review (new default)\"\n\
829 echo \" • ca autoland - Auto-merge when approved + builds pass\"\n\
830 echo \"\"\n\
831 echo \"🚨 If you really need to force push, run:\"\n\
832 echo \" git push --force-with-lease [remote] [branch]\"\n\
833 echo \" (But consider if this will affect other stack entries)\"\n\
834 exit 1\n\
835 fi\n\n\
836 # Find repository root and check if Cascade is initialized\n\
837 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
838 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
839 echo \"ℹ️ Cascade not initialized, allowing push\"\n\
840 exit 0\n\
841 fi\n\n\
842 # Validate stack state\n\
843 echo \"🪝 Validating stack state before push...\"\n\
844 if \"{cascade_cli}\" stack validate; then\n\
845 echo \"✅ Stack validation passed\"\n\
846 else\n\
847 echo \"❌ Stack validation failed\"\n\
848 echo \"💡 Fix validation errors before pushing:\"\n\
849 echo \" • ca doctor - Check overall health\"\n\
850 echo \" • ca status - Check current stack status\"\n\
851 echo \" • ca sync - Sync with remote and rebase if needed\"\n\
852 exit 1\n\
853 fi\n\n\
854 echo \"✅ Pre-push validation complete\"\n"
855 )
856 }
857 }
858
859 fn generate_commit_msg_hook(&self, _cascade_cli: &str) -> String {
860 #[cfg(windows)]
861 {
862 r#"@echo off
863rem Cascade CLI Hook - Commit Message
864rem Validates commit message format
865
866set COMMIT_MSG_FILE=%1
867if "%COMMIT_MSG_FILE%"=="" (
868 echo ❌ No commit message file provided
869 exit /b 1
870)
871
872rem Read commit message (Windows batch is limited, but this covers basic cases)
873for /f "delims=" %%i in ('type "%COMMIT_MSG_FILE%"') do set COMMIT_MSG=%%i
874
875rem Skip validation for merge commits, fixup commits, etc.
876echo %COMMIT_MSG% | findstr /B /C:"Merge" /C:"Revert" /C:"fixup!" /C:"squash!" >nul
877if %ERRORLEVEL% equ 0 exit /b 0
878
879rem Find repository root and check if Cascade is initialized
880for /f "tokens=*" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i
881if "%REPO_ROOT%"=="" set REPO_ROOT=.
882if not exist "%REPO_ROOT%\.cascade" exit /b 0
883
884rem Basic commit message validation
885echo %COMMIT_MSG% | findstr /R "^..........*" >nul
886if %ERRORLEVEL% neq 0 (
887 echo ❌ Commit message too short (minimum 10 characters)
888 echo 💡 Write a descriptive commit message for better stack management
889 exit /b 1
890)
891
892rem Check for very long messages (approximate check in batch)
893echo %COMMIT_MSG% | findstr /R "^..................................................................................*" >nul
894if %ERRORLEVEL% equ 0 (
895 echo ⚠️ Warning: Commit message longer than 72 characters
896 echo 💡 Consider keeping the first line short for better readability
897)
898
899rem Check for conventional commit format (optional)
900echo %COMMIT_MSG% | findstr /R "^(feat|fix|docs|style|refactor|test|chore|perf|ci|build)" >nul
901if %ERRORLEVEL% neq 0 (
902 echo 💡 Consider using conventional commit format:
903 echo feat: add new feature
904 echo fix: resolve bug
905 echo docs: update documentation
906 echo etc.
907)
908
909echo ✅ Commit message validation passed
910"#.to_string()
911 }
912
913 #[cfg(not(windows))]
914 {
915 r#"#!/bin/sh
916# Cascade CLI Hook - Commit Message
917# Validates commit message format
918
919set -e
920
921COMMIT_MSG_FILE="$1"
922COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")
923
924# Skip validation for merge commits, fixup commits, etc.
925if echo "$COMMIT_MSG" | grep -E "^(Merge|Revert|fixup!|squash!)" > /dev/null; then
926 exit 0
927fi
928
929# Find repository root and check if Cascade is initialized
930REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")
931if [ ! -d "$REPO_ROOT/.cascade" ]; then
932 exit 0
933fi
934
935# Basic commit message validation
936if [ ${#COMMIT_MSG} -lt 10 ]; then
937 echo "❌ Commit message too short (minimum 10 characters)"
938 echo "💡 Write a descriptive commit message for better stack management"
939 exit 1
940fi
941
942if [ ${#COMMIT_MSG} -gt 72 ]; then
943 echo "⚠️ Warning: Commit message longer than 72 characters"
944 echo "💡 Consider keeping the first line short for better readability"
945fi
946
947# Check for conventional commit format (optional)
948if ! echo "$COMMIT_MSG" | grep -E "^(feat|fix|docs|style|refactor|test|chore|perf|ci|build)(\(.+\))?: .+" > /dev/null; then
949 echo "💡 Consider using conventional commit format:"
950 echo " feat: add new feature"
951 echo " fix: resolve bug"
952 echo " docs: update documentation"
953 echo " etc."
954fi
955
956echo "✅ Commit message validation passed"
957"#.to_string()
958 }
959 }
960
961 #[allow(clippy::uninlined_format_args)]
962 fn generate_pre_commit_hook(&self, cascade_cli: &str) -> String {
963 #[cfg(windows)]
964 {
965 format!(
966 "@echo off\n\
967 rem Cascade CLI Hook - Pre Commit\n\
968 rem Smart edit mode guidance for better UX\n\n\
969 rem Check if Cascade is initialized\n\
970 for /f \\\"tokens=*\\\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
971 if \\\"%REPO_ROOT%\\\"==\\\"\\\" set REPO_ROOT=.\n\
972 if not exist \\\"%REPO_ROOT%\\.cascade\\\" exit /b 0\n\n\
973 rem Check if we're in edit mode\n\
974 \\\"{0}\\\" entry status --quiet >nul 2>&1\n\
975 if %ERRORLEVEL% equ 0 (\n\
976 echo ⚠ You're in EDIT MODE for a stack entry!\n\
977 echo.\n\
978 echo Choose your action:\n\
979 echo [A] Amend: Modify the current entry ^(default^)\n\
980 echo [N] New: Create new entry on top\n\
981 echo [C] Cancel: Stop and think about it\n\
982 echo.\n\
983 set /p choice=\\\"Your choice (A/n/c): \\\"\n\
984 if \\\"%choice%\\\"==\\\"\\\" set choice=A\n\
985 \n\
986 if /i \\\"%choice%\\\"==\\\"A\\\" (\n\
987 echo Amending current entry...\n\
988 rem Stage all changes first\n\
989 git add -A\n\
990 rem Use ca entry amend to properly update entry + working branch\n\
991 \\\"{0}\\\" entry amend --all\n\
992 exit /b %ERRORLEVEL%\n\
993 ) else if /i \\\"%choice%\\\"==\\\"N\\\" (\n\
994 echo Creating new stack entry...\n\
995 rem Let the commit proceed normally\n\
996 exit /b 0\n\
997 ) else if /i \\\"%choice%\\\"==\\\"C\\\" (\n\
998 echo Commit cancelled\n\
999 exit /b 1\n\
1000 ) else (\n\
1001 echo Invalid choice. Please choose A, n, or c\n\
1002 exit /b 1\n\
1003 )\n\
1004 )\n\n\
1005 rem Not in edit mode, proceed normally\n\
1006 exit /b 0\n",
1007 cascade_cli
1008 )
1009 }
1010
1011 #[cfg(not(windows))]
1012 {
1013 format!(
1014 "#!/bin/sh\n\
1015 # Cascade CLI Hook - Pre Commit\n\
1016 # Smart edit mode guidance for better UX\n\n\
1017 set -e\n\n\
1018 # Check if Cascade is initialized\n\
1019 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
1020 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
1021 exit 0\n\
1022 fi\n\n\
1023 # Check if we're in edit mode\n\
1024 if \"{0}\" entry status --quiet >/dev/null 2>&1; then\n\
1025 echo \"⚠ You're in EDIT MODE for a stack entry!\"\n\
1026 echo \"\"\n\
1027 echo \"Choose your action:\"\n\
1028 echo \" [A] Amend: Modify the current entry (default)\"\n\
1029 echo \" [N] New: Create new entry on top\"\n\
1030 echo \" [C] Cancel: Stop and think about it\"\n\
1031 echo \"\"\n\
1032 \n\
1033 # Read user choice with default to amend\n\
1034 read -p \"Your choice (A/n/c): \" choice\n\
1035 choice=${{choice:-A}}\n\
1036 \n\
1037 case \"$choice\" in\n\
1038 [Aa])\n\
1039 echo \"Amending current entry...\"\n\
1040 # Stage all changes first (like git commit -a)\n\
1041 git add -A\n\
1042 # Use ca entry amend to properly update entry + working branch\n\
1043 \"{0}\" entry amend --all\n\
1044 exit $?\n\
1045 ;;\n\
1046 [Nn])\n\
1047 echo \"Creating new stack entry...\"\n\
1048 # Let the commit proceed normally (will create new commit)\n\
1049 exit 0\n\
1050 ;;\n\
1051 [Cc])\n\
1052 echo \"Commit cancelled\"\n\
1053 exit 1\n\
1054 ;;\n\
1055 *)\n\
1056 echo \"Invalid choice. Please choose A, n, or c\"\n\
1057 exit 1\n\
1058 ;;\n\
1059 esac\n\
1060 fi\n\n\
1061 # Not in edit mode, proceed normally\n\
1062 exit 0\n",
1063 cascade_cli
1064 )
1065 }
1066 }
1067
1068 fn generate_prepare_commit_msg_hook(&self, cascade_cli: &str) -> String {
1069 #[cfg(windows)]
1070 {
1071 format!(
1072 "@echo off\n\
1073 rem Cascade CLI Hook - Prepare Commit Message\n\
1074 rem Adds stack context to commit messages\n\n\
1075 set COMMIT_MSG_FILE=%1\n\
1076 set COMMIT_SOURCE=%2\n\
1077 set COMMIT_SHA=%3\n\n\
1078 rem Only modify message if it's a regular commit (not merge, template, etc.)\n\
1079 if not \"%COMMIT_SOURCE%\"==\"\" if not \"%COMMIT_SOURCE%\"==\"message\" exit /b 0\n\n\
1080 rem Find repository root and check if Cascade is initialized\n\
1081 for /f \"tokens=*\" %%i in ('git rev-parse --show-toplevel 2^>nul') do set REPO_ROOT=%%i\n\
1082 if \"%REPO_ROOT%\"==\"\" set REPO_ROOT=.\n\
1083 if not exist \"%REPO_ROOT%\\.cascade\" exit /b 0\n\n\
1084 rem Check if in edit mode first\n\
1085 for /f \"tokens=*\" %%i in ('\"{cascade_cli}\" entry status --quiet 2^>nul') do set EDIT_STATUS=%%i\n\
1086 if \"%EDIT_STATUS%\"==\"\" set EDIT_STATUS=inactive\n\n\
1087 if not \"%EDIT_STATUS%\"==\"inactive\" (\n\
1088 rem In edit mode - provide smart guidance\n\
1089 set /p CURRENT_MSG=<%COMMIT_MSG_FILE%\n\n\
1090 rem Skip if message already has edit guidance\n\
1091 echo !CURRENT_MSG! | findstr \"[EDIT MODE]\" >nul\n\
1092 if %ERRORLEVEL% equ 0 exit /b 0\n\n\
1093 rem Add edit mode guidance to commit message\n\
1094 echo.\n\
1095 echo # [EDIT MODE] You're editing a stack entry\n\
1096 echo #\n\
1097 echo # Choose your action:\n\
1098 echo # 🔄 AMEND: To modify the current entry, use:\n\
1099 echo # git commit --amend\n\
1100 echo #\n\
1101 echo # ➕ NEW: To create a new entry on top, use:\n\
1102 echo # git commit ^(this command^)\n\
1103 echo #\n\
1104 echo # 💡 After committing, run 'ca sync' to update PRs\n\
1105 echo.\n\
1106 type \"%COMMIT_MSG_FILE%\"\n\
1107 ) > \"%COMMIT_MSG_FILE%.tmp\" && (\n\
1108 move \"%COMMIT_MSG_FILE%.tmp\" \"%COMMIT_MSG_FILE%\"\n\
1109 ) else (\n\
1110 rem Regular stack mode - check for active stack\n\
1111 for /f \"tokens=*\" %%i in ('\"{cascade_cli}\" stack list --active --format=name 2^>nul') do set ACTIVE_STACK=%%i\n\n\
1112 if not \"%ACTIVE_STACK%\"==\"\" (\n\
1113 rem Get current commit message\n\
1114 set /p CURRENT_MSG=<%COMMIT_MSG_FILE%\n\n\
1115 rem Skip if message already has stack context\n\
1116 echo !CURRENT_MSG! | findstr \"[stack:\" >nul\n\
1117 if %ERRORLEVEL% equ 0 exit /b 0\n\n\
1118 rem Add stack context to commit message\n\
1119 echo.\n\
1120 echo # Stack: %ACTIVE_STACK%\n\
1121 echo # This commit will be added to the active stack automatically.\n\
1122 echo # Use 'ca stack status' to see the current stack state.\n\
1123 type \"%COMMIT_MSG_FILE%\"\n\
1124 ) > \"%COMMIT_MSG_FILE%.tmp\"\n\
1125 move \"%COMMIT_MSG_FILE%.tmp\" \"%COMMIT_MSG_FILE%\"\n\
1126 )\n"
1127 )
1128 }
1129
1130 #[cfg(not(windows))]
1131 {
1132 format!(
1133 "#!/bin/sh\n\
1134 # Cascade CLI Hook - Prepare Commit Message\n\
1135 # Adds stack context to commit messages\n\n\
1136 set -e\n\n\
1137 COMMIT_MSG_FILE=\"$1\"\n\
1138 COMMIT_SOURCE=\"$2\"\n\
1139 COMMIT_SHA=\"$3\"\n\n\
1140 # Only modify message if it's a regular commit (not merge, template, etc.)\n\
1141 if [ \"$COMMIT_SOURCE\" != \"\" ] && [ \"$COMMIT_SOURCE\" != \"message\" ]; then\n\
1142 exit 0\n\
1143 fi\n\n\
1144 # Find repository root and check if Cascade is initialized\n\
1145 REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo \".\")\n\
1146 if [ ! -d \"$REPO_ROOT/.cascade\" ]; then\n\
1147 exit 0\n\
1148 fi\n\n\
1149 # Check if in edit mode first\n\
1150 EDIT_STATUS=$(\"{cascade_cli}\" entry status --quiet 2>/dev/null || echo \"inactive\")\n\
1151 \n\
1152 if [ \"$EDIT_STATUS\" != \"inactive\" ]; then\n\
1153 # In edit mode - provide smart guidance\n\
1154 CURRENT_MSG=$(cat \"$COMMIT_MSG_FILE\")\n\
1155 \n\
1156 # Skip if message already has edit guidance\n\
1157 if echo \"$CURRENT_MSG\" | grep -q \"\\[EDIT MODE\\]\"; then\n\
1158 exit 0\n\
1159 fi\n\
1160 \n\
1161 echo \"\n\
1162 # [EDIT MODE] You're editing a stack entry\n\
1163 #\n\
1164 # Choose your action:\n\
1165 # 🔄 AMEND: To modify the current entry, use:\n\
1166 # git commit --amend\n\
1167 #\n\
1168 # ➕ NEW: To create a new entry on top, use:\n\
1169 # git commit (this command)\n\
1170 #\n\
1171 # 💡 After committing, run 'ca sync' to update PRs\n\
1172 \n\
1173 $CURRENT_MSG\" > \"$COMMIT_MSG_FILE\"\n\
1174 else\n\
1175 # Regular stack mode - check for active stack\n\
1176 ACTIVE_STACK=$(\"{cascade_cli}\" stack list --active --format=name 2>/dev/null || echo \"\")\n\
1177 \n\
1178 if [ -n \"$ACTIVE_STACK\" ]; then\n\
1179 # Get current commit message\n\
1180 CURRENT_MSG=$(cat \"$COMMIT_MSG_FILE\")\n\
1181 \n\
1182 # Skip if message already has stack context\n\
1183 if echo \"$CURRENT_MSG\" | grep -q \"\\[stack:\"; then\n\
1184 exit 0\n\
1185 fi\n\
1186 \n\
1187 # Add stack context to commit message\n\
1188 echo \"\n\
1189 # Stack: $ACTIVE_STACK\n\
1190 # This commit will be added to the active stack automatically.\n\
1191 # Use 'ca stack status' to see the current stack state.\n\
1192 $CURRENT_MSG\" > \"$COMMIT_MSG_FILE\"\n\
1193 fi\n\
1194 fi\n"
1195 )
1196 }
1197 }
1198
1199 pub fn detect_repository_type(&self) -> Result<RepositoryType> {
1201 let output = Command::new("git")
1202 .args(["remote", "get-url", "origin"])
1203 .current_dir(&self.repo_path)
1204 .output()
1205 .map_err(|e| CascadeError::config(format!("Failed to get remote URL: {e}")))?;
1206
1207 if !output.status.success() {
1208 return Ok(RepositoryType::Unknown);
1209 }
1210
1211 let remote_url = String::from_utf8_lossy(&output.stdout)
1212 .trim()
1213 .to_lowercase();
1214
1215 if remote_url.contains("github.com") {
1216 Ok(RepositoryType::GitHub)
1217 } else if remote_url.contains("gitlab.com") || remote_url.contains("gitlab") {
1218 Ok(RepositoryType::GitLab)
1219 } else if remote_url.contains("dev.azure.com") || remote_url.contains("visualstudio.com") {
1220 Ok(RepositoryType::AzureDevOps)
1221 } else if remote_url.contains("bitbucket") {
1222 Ok(RepositoryType::Bitbucket)
1223 } else {
1224 Ok(RepositoryType::Unknown)
1225 }
1226 }
1227
1228 pub fn detect_branch_type(&self) -> Result<BranchType> {
1230 let output = Command::new("git")
1231 .args(["branch", "--show-current"])
1232 .current_dir(&self.repo_path)
1233 .output()
1234 .map_err(|e| CascadeError::config(format!("Failed to get current branch: {e}")))?;
1235
1236 if !output.status.success() {
1237 return Ok(BranchType::Unknown);
1238 }
1239
1240 let branch_name = String::from_utf8_lossy(&output.stdout)
1241 .trim()
1242 .to_lowercase();
1243
1244 if branch_name == "main" || branch_name == "master" || branch_name == "develop" {
1245 Ok(BranchType::Main)
1246 } else if !branch_name.is_empty() {
1247 Ok(BranchType::Feature)
1248 } else {
1249 Ok(BranchType::Unknown)
1250 }
1251 }
1252
1253 pub fn validate_prerequisites(&self) -> Result<()> {
1255 Output::check_start("Checking prerequisites for Cascade hooks");
1256
1257 let repo_type = self.detect_repository_type()?;
1259 match repo_type {
1260 RepositoryType::Bitbucket => {
1261 Output::success("Bitbucket repository detected");
1262 Output::tip("Hooks will work great with 'ca submit' and 'ca autoland' for Bitbucket integration");
1263 }
1264 RepositoryType::GitHub => {
1265 Output::success("GitHub repository detected");
1266 Output::tip("Consider setting up GitHub Actions for CI/CD integration");
1267 }
1268 RepositoryType::GitLab => {
1269 Output::success("GitLab repository detected");
1270 Output::tip("GitLab CI integration works well with Cascade stacks");
1271 }
1272 RepositoryType::AzureDevOps => {
1273 Output::success("Azure DevOps repository detected");
1274 Output::tip("Azure Pipelines can be configured to work with Cascade workflows");
1275 }
1276 RepositoryType::Unknown => {
1277 Output::info(
1278 "Unknown repository type - hooks will still work for local Git operations",
1279 );
1280 }
1281 }
1282
1283 let config_dir = crate::config::get_repo_config_dir(&self.repo_path)?;
1285 let config_path = config_dir.join("config.json");
1286 if !config_path.exists() {
1287 return Err(CascadeError::config(
1288 "🚫 Cascade not initialized!\n\n\
1289 Please run 'ca init' or 'ca setup' first to configure Cascade CLI.\n\
1290 Hooks require proper Bitbucket Server configuration.\n\n\
1291 Use --force to install anyway (not recommended)."
1292 .to_string(),
1293 ));
1294 }
1295
1296 let config = Settings::load_from_file(&config_path)?;
1298
1299 if config.bitbucket.url == "https://bitbucket.example.com"
1300 || config.bitbucket.url.contains("example.com")
1301 {
1302 return Err(CascadeError::config(
1303 "🚫 Invalid Bitbucket configuration!\n\n\
1304 Your Bitbucket URL appears to be a placeholder.\n\
1305 Please run 'ca setup' to configure a real Bitbucket Server.\n\n\
1306 Use --force to install anyway (not recommended)."
1307 .to_string(),
1308 ));
1309 }
1310
1311 if config.bitbucket.project == "PROJECT" || config.bitbucket.repo == "repo" {
1312 return Err(CascadeError::config(
1313 "🚫 Incomplete Bitbucket configuration!\n\n\
1314 Your project/repository settings appear to be placeholders.\n\
1315 Please run 'ca setup' to complete configuration.\n\n\
1316 Use --force to install anyway (not recommended)."
1317 .to_string(),
1318 ));
1319 }
1320
1321 Output::success("Prerequisites validation passed");
1322 Ok(())
1323 }
1324
1325 pub fn validate_branch_suitability(&self) -> Result<()> {
1327 let branch_type = self.detect_branch_type()?;
1328
1329 match branch_type {
1330 BranchType::Main => {
1331 return Err(CascadeError::config(
1332 "🚫 Currently on main/master branch!\n\n\
1333 Cascade hooks are designed for feature branch development.\n\
1334 Working directly on main/master with stacked diffs can:\n\
1335 • Complicate the commit history\n\
1336 • Interfere with team collaboration\n\
1337 • Break CI/CD workflows\n\n\
1338 💡 Recommended workflow:\n\
1339 1. Create a feature branch: git checkout -b feature/my-feature\n\
1340 2. Install hooks: ca hooks install\n\
1341 3. Develop with stacked commits (auto-added with hooks)\n\
1342 4. Push & submit: ca push && ca submit (all by default)\n\
1343 5. Auto-land when ready: ca autoland\n\n\
1344 Use --force to install anyway (not recommended)."
1345 .to_string(),
1346 ));
1347 }
1348 BranchType::Feature => {
1349 Output::success("Feature branch detected - suitable for stacked development");
1350 }
1351 BranchType::Unknown => {
1352 Output::warning("Unknown branch type - proceeding with caution");
1353 }
1354 }
1355
1356 Ok(())
1357 }
1358
1359 pub fn confirm_installation(&self) -> Result<()> {
1361 Output::section("Hook Installation Summary");
1362
1363 let hooks = vec![
1364 HookType::PostCommit,
1365 HookType::PrePush,
1366 HookType::CommitMsg,
1367 HookType::PrepareCommitMsg,
1368 ];
1369
1370 for hook in &hooks {
1371 Output::sub_item(format!("{}: {}", hook.filename(), hook.description()));
1372 }
1373
1374 println!();
1375 Output::section("These hooks will automatically");
1376 Output::bullet("Add commits to your active stack");
1377 Output::bullet("Validate commit messages");
1378 Output::bullet("Prevent force pushes that break stack integrity");
1379 Output::bullet("Add stack context to commit messages");
1380
1381 println!();
1382 Output::section("With hooks + new defaults, your workflow becomes");
1383 Output::sub_item("git commit → Auto-added to stack");
1384 Output::sub_item("ca push → Pushes all by default");
1385 Output::sub_item("ca submit → Submits all by default");
1386 Output::sub_item("ca autoland → Auto-merges when ready");
1387
1388 let should_install = Confirm::with_theme(&ColorfulTheme::default())
1390 .with_prompt("Install Cascade hooks?")
1391 .default(true)
1392 .interact()
1393 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
1394
1395 if should_install {
1396 Output::success("Proceeding with installation");
1397 Ok(())
1398 } else {
1399 Err(CascadeError::config(
1400 "Installation cancelled by user".to_string(),
1401 ))
1402 }
1403 }
1404}
1405
1406pub async fn install() -> Result<()> {
1408 install_with_options(false, false, false, false).await
1409}
1410
1411pub async fn install_essential() -> Result<()> {
1412 let current_dir = env::current_dir()
1413 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1414
1415 let repo_root = find_repository_root(¤t_dir)
1416 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1417
1418 let hooks_manager = HooksManager::new(&repo_root)?;
1419 hooks_manager.install_essential()
1420}
1421
1422pub async fn install_with_options(
1423 skip_checks: bool,
1424 allow_main_branch: bool,
1425 yes: bool,
1426 force: bool,
1427) -> Result<()> {
1428 let current_dir = env::current_dir()
1429 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1430
1431 let repo_root = find_repository_root(¤t_dir)
1432 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1433
1434 let hooks_manager = HooksManager::new(&repo_root)?;
1435
1436 let options = InstallOptions {
1437 check_prerequisites: !skip_checks,
1438 feature_branches_only: !allow_main_branch,
1439 confirm: !yes,
1440 force,
1441 };
1442
1443 hooks_manager.install_with_options(&options)
1444}
1445
1446pub async fn uninstall() -> Result<()> {
1447 let current_dir = env::current_dir()
1448 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1449
1450 let repo_root = find_repository_root(¤t_dir)
1451 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1452
1453 let hooks_manager = HooksManager::new(&repo_root)?;
1454 hooks_manager.uninstall_all()
1455}
1456
1457pub async fn status() -> 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 hooks_manager.list_installed_hooks()
1466}
1467
1468pub async fn install_hook(hook_name: &str) -> Result<()> {
1469 install_hook_with_options(hook_name, false, false).await
1470}
1471
1472pub async fn install_hook_with_options(
1473 hook_name: &str,
1474 skip_checks: bool,
1475 force: bool,
1476) -> 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
1485 let hook_type = match hook_name {
1486 "post-commit" => HookType::PostCommit,
1487 "pre-push" => HookType::PrePush,
1488 "commit-msg" => HookType::CommitMsg,
1489 "pre-commit" => HookType::PreCommit,
1490 "prepare-commit-msg" => HookType::PrepareCommitMsg,
1491 _ => {
1492 return Err(CascadeError::config(format!(
1493 "Unknown hook type: {hook_name}"
1494 )))
1495 }
1496 };
1497
1498 if !skip_checks && !force {
1500 hooks_manager.validate_prerequisites()?;
1501 }
1502
1503 hooks_manager.install_hook(&hook_type)
1504}
1505
1506pub async fn uninstall_hook(hook_name: &str) -> 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 hooks_manager.uninstall_hook(&hook_type)
1529}
1530
1531#[cfg(test)]
1532mod tests {
1533 use super::*;
1534 use std::process::Command;
1535 use tempfile::TempDir;
1536
1537 fn create_test_repo() -> (TempDir, std::path::PathBuf) {
1538 let temp_dir = TempDir::new().unwrap();
1539 let repo_path = temp_dir.path().to_path_buf();
1540
1541 Command::new("git")
1543 .args(["init"])
1544 .current_dir(&repo_path)
1545 .output()
1546 .unwrap();
1547 Command::new("git")
1548 .args(["config", "user.name", "Test"])
1549 .current_dir(&repo_path)
1550 .output()
1551 .unwrap();
1552 Command::new("git")
1553 .args(["config", "user.email", "test@test.com"])
1554 .current_dir(&repo_path)
1555 .output()
1556 .unwrap();
1557
1558 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1560 Command::new("git")
1561 .args(["add", "."])
1562 .current_dir(&repo_path)
1563 .output()
1564 .unwrap();
1565 Command::new("git")
1566 .args(["commit", "-m", "Initial"])
1567 .current_dir(&repo_path)
1568 .output()
1569 .unwrap();
1570
1571 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
1573 .unwrap();
1574
1575 (temp_dir, repo_path)
1576 }
1577
1578 #[test]
1579 fn test_hooks_manager_creation() {
1580 let (_temp_dir, repo_path) = create_test_repo();
1581 let _manager = HooksManager::new(&repo_path).unwrap();
1582
1583 assert_eq!(_manager.repo_path, repo_path);
1584 assert!(!_manager.repo_id.is_empty());
1586 }
1587
1588 #[test]
1589 fn test_hooks_manager_custom_hooks_path() {
1590 let (_temp_dir, repo_path) = create_test_repo();
1591
1592 Command::new("git")
1594 .args(["config", "core.hooksPath", "custom-hooks"])
1595 .current_dir(&repo_path)
1596 .output()
1597 .unwrap();
1598
1599 let custom_hooks_dir = repo_path.join("custom-hooks");
1601 std::fs::create_dir_all(&custom_hooks_dir).unwrap();
1602
1603 let _manager = HooksManager::new(&repo_path).unwrap();
1604
1605 assert_eq!(_manager.repo_path, repo_path);
1606 assert!(!_manager.repo_id.is_empty());
1608 }
1609
1610 #[test]
1611 fn test_hook_chaining_with_existing_hooks() {
1612 let (_temp_dir, repo_path) = create_test_repo();
1613 let manager = HooksManager::new(&repo_path).unwrap();
1614
1615 let hook_type = HookType::PreCommit;
1616 let hook_path = repo_path.join(".git/hooks").join(hook_type.filename());
1617
1618 let existing_hook_content = "#!/bin/bash\n# Project pre-commit hook\n./scripts/lint.sh\n";
1620 std::fs::write(&hook_path, existing_hook_content).unwrap();
1621 crate::utils::platform::make_executable(&hook_path).unwrap();
1622
1623 let result = manager.install_hook(&hook_type);
1625 assert!(result.is_ok());
1626
1627 let original_content = std::fs::read_to_string(&hook_path).unwrap();
1629 assert!(original_content.contains("# Project pre-commit hook"));
1630 assert!(original_content.contains("./scripts/lint.sh"));
1631
1632 let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
1634 let cascade_hook_path = cascade_hooks_dir.join(hook_type.filename());
1635 assert!(cascade_hook_path.exists());
1636
1637 let uninstall_result = manager.uninstall_hook(&hook_type);
1639 assert!(uninstall_result.is_ok());
1640
1641 let after_uninstall = std::fs::read_to_string(&hook_path).unwrap();
1643 assert!(after_uninstall.contains("# Project pre-commit hook"));
1644 assert!(after_uninstall.contains("./scripts/lint.sh"));
1645
1646 assert!(!cascade_hook_path.exists());
1648 }
1649
1650 #[test]
1651 fn test_hook_installation() {
1652 let (_temp_dir, repo_path) = create_test_repo();
1653 let manager = HooksManager::new(&repo_path).unwrap();
1654
1655 let hook_type = HookType::PostCommit;
1657 let result = manager.install_hook(&hook_type);
1658 assert!(result.is_ok());
1659
1660 let hook_filename = hook_type.filename();
1662 let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
1663 let hook_path = cascade_hooks_dir.join(&hook_filename);
1664 assert!(hook_path.exists());
1665
1666 #[cfg(unix)]
1668 {
1669 use std::os::unix::fs::PermissionsExt;
1670 let metadata = std::fs::metadata(&hook_path).unwrap();
1671 let permissions = metadata.permissions();
1672 assert!(permissions.mode() & 0o111 != 0); }
1674
1675 #[cfg(windows)]
1676 {
1677 assert!(hook_filename.ends_with(".bat"));
1679 assert!(hook_path.exists());
1680 }
1681 }
1682
1683 #[test]
1684 fn test_hook_detection() {
1685 let (_temp_dir, repo_path) = create_test_repo();
1686 let _manager = HooksManager::new(&repo_path).unwrap();
1687
1688 let post_commit_path = repo_path
1690 .join(".git/hooks")
1691 .join(HookType::PostCommit.filename());
1692 let pre_push_path = repo_path
1693 .join(".git/hooks")
1694 .join(HookType::PrePush.filename());
1695 let commit_msg_path = repo_path
1696 .join(".git/hooks")
1697 .join(HookType::CommitMsg.filename());
1698
1699 assert!(!post_commit_path.exists());
1701 assert!(!pre_push_path.exists());
1702 assert!(!commit_msg_path.exists());
1703 }
1704
1705 #[test]
1706 fn test_hook_validation() {
1707 let (_temp_dir, repo_path) = create_test_repo();
1708 let manager = HooksManager::new(&repo_path).unwrap();
1709
1710 let validation = manager.validate_prerequisites();
1712 let _ = validation; let branch_validation = manager.validate_branch_suitability();
1718 let _ = branch_validation; }
1721
1722 #[test]
1723 fn test_hook_uninstallation() {
1724 let (_temp_dir, repo_path) = create_test_repo();
1725 let manager = HooksManager::new(&repo_path).unwrap();
1726
1727 let hook_type = HookType::PostCommit;
1729 manager.install_hook(&hook_type).unwrap();
1730
1731 let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
1732 let hook_path = cascade_hooks_dir.join(hook_type.filename());
1733 assert!(hook_path.exists());
1734
1735 let result = manager.uninstall_hook(&hook_type);
1736 assert!(result.is_ok());
1737 assert!(!hook_path.exists());
1738 }
1739
1740 #[test]
1741 fn test_hook_content_generation() {
1742 let (_temp_dir, repo_path) = create_test_repo();
1743 let manager = HooksManager::new(&repo_path).unwrap();
1744
1745 let binary_name = "cascade-cli";
1747
1748 let post_commit_content = manager.generate_post_commit_hook(binary_name);
1750 #[cfg(windows)]
1751 {
1752 assert!(post_commit_content.contains("@echo off"));
1753 assert!(post_commit_content.contains("rem Cascade CLI Hook"));
1754 }
1755 #[cfg(not(windows))]
1756 {
1757 assert!(post_commit_content.contains("#!/bin/sh"));
1758 assert!(post_commit_content.contains("# Cascade CLI Hook"));
1759 }
1760 assert!(post_commit_content.contains(binary_name));
1761
1762 let pre_push_content = manager.generate_pre_push_hook(binary_name);
1764 #[cfg(windows)]
1765 {
1766 assert!(pre_push_content.contains("@echo off"));
1767 assert!(pre_push_content.contains("rem Cascade CLI Hook"));
1768 }
1769 #[cfg(not(windows))]
1770 {
1771 assert!(pre_push_content.contains("#!/bin/sh"));
1772 assert!(pre_push_content.contains("# Cascade CLI Hook"));
1773 }
1774 assert!(pre_push_content.contains(binary_name));
1775
1776 let commit_msg_content = manager.generate_commit_msg_hook(binary_name);
1778 #[cfg(windows)]
1779 {
1780 assert!(commit_msg_content.contains("@echo off"));
1781 assert!(commit_msg_content.contains("rem Cascade CLI Hook"));
1782 }
1783 #[cfg(not(windows))]
1784 {
1785 assert!(commit_msg_content.contains("#!/bin/sh"));
1786 assert!(commit_msg_content.contains("# Cascade CLI Hook"));
1787 }
1788
1789 let prepare_commit_content = manager.generate_prepare_commit_msg_hook(binary_name);
1791 #[cfg(windows)]
1792 {
1793 assert!(prepare_commit_content.contains("@echo off"));
1794 assert!(prepare_commit_content.contains("rem Cascade CLI Hook"));
1795 }
1796 #[cfg(not(windows))]
1797 {
1798 assert!(prepare_commit_content.contains("#!/bin/sh"));
1799 assert!(prepare_commit_content.contains("# Cascade CLI Hook"));
1800 }
1801 assert!(prepare_commit_content.contains(binary_name));
1802 }
1803
1804 #[test]
1805 fn test_hook_status_reporting() {
1806 let (_temp_dir, repo_path) = create_test_repo();
1807 let manager = HooksManager::new(&repo_path).unwrap();
1808
1809 let repo_type = manager.detect_repository_type().unwrap();
1811 assert!(matches!(
1813 repo_type,
1814 RepositoryType::Bitbucket | RepositoryType::Unknown
1815 ));
1816
1817 let branch_type = manager.detect_branch_type().unwrap();
1819 assert!(matches!(
1821 branch_type,
1822 BranchType::Main | BranchType::Unknown
1823 ));
1824 }
1825
1826 #[test]
1827 fn test_force_installation() {
1828 let (_temp_dir, repo_path) = create_test_repo();
1829 let manager = HooksManager::new(&repo_path).unwrap();
1830
1831 let hook_filename = HookType::PostCommit.filename();
1833 let hook_path = repo_path.join(".git/hooks").join(&hook_filename);
1834
1835 #[cfg(windows)]
1836 let existing_content = "@echo off\necho existing hook";
1837 #[cfg(not(windows))]
1838 let existing_content = "#!/bin/sh\necho 'existing hook'";
1839
1840 std::fs::write(&hook_path, existing_content).unwrap();
1841
1842 let hook_type = HookType::PostCommit;
1844 let result = manager.install_hook(&hook_type);
1845 assert!(result.is_ok());
1846
1847 let cascade_hooks_dir = manager.get_cascade_hooks_dir().unwrap();
1849 let cascade_hook_path = cascade_hooks_dir.join(&hook_filename);
1850 assert!(cascade_hook_path.exists());
1851
1852 let original_content = std::fs::read_to_string(&hook_path).unwrap();
1854 assert!(original_content.contains("existing hook"));
1855
1856 let cascade_content = std::fs::read_to_string(&cascade_hook_path).unwrap();
1858 assert!(cascade_content.contains("cascade-cli") || cascade_content.contains("ca"));
1859 }
1860}