cascade_cli/stack/
stack.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use uuid::Uuid;
5
6/// Represents a single entry in a stack
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct StackEntry {
9    /// Unique identifier for this entry
10    pub id: Uuid,
11    /// Branch name for this entry
12    pub branch: String,
13    /// Commit hash
14    pub commit_hash: String,
15    /// Commit message
16    pub message: String,
17    /// Parent entry ID (None for base)
18    pub parent_id: Option<Uuid>,
19    /// Child entry IDs
20    pub children: Vec<Uuid>,
21    /// When this entry was created
22    pub created_at: DateTime<Utc>,
23    /// When this entry was last updated
24    pub updated_at: DateTime<Utc>,
25    /// Whether this entry has been submitted for review
26    pub is_submitted: bool,
27    /// Pull request ID if submitted
28    pub pull_request_id: Option<String>,
29    /// Whether this entry is synced with remote
30    pub is_synced: bool,
31}
32
33/// Represents the status of a stack
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
35pub enum StackStatus {
36    /// Stack is clean and ready
37    Clean,
38    /// Stack has uncommitted changes
39    Dirty,
40    /// Stack needs to be synced with remote
41    OutOfSync,
42    /// Stack has conflicts that need resolution
43    Conflicted,
44    /// Stack is being rebased
45    Rebasing,
46    /// Stack needs sync due to new commits on base branch
47    NeedsSync,
48    /// Stack has corrupted or missing commits
49    Corrupted,
50}
51
52/// Represents a complete stack of commits
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct Stack {
55    /// Unique identifier for this stack
56    pub id: Uuid,
57    /// Human-readable name for the stack
58    pub name: String,
59    /// Description of what this stack implements
60    pub description: Option<String>,
61    /// Base branch this stack is built on
62    pub base_branch: String,
63    /// All entries in this stack (ordered)
64    pub entries: Vec<StackEntry>,
65    /// Map of entry ID to entry for quick lookup
66    pub entry_map: HashMap<Uuid, StackEntry>,
67    /// Current status of the stack
68    pub status: StackStatus,
69    /// When this stack was created
70    pub created_at: DateTime<Utc>,
71    /// When this stack was last updated
72    pub updated_at: DateTime<Utc>,
73    /// Whether this stack is active (current working stack)
74    pub is_active: bool,
75}
76
77impl Stack {
78    /// Create a new empty stack
79    pub fn new(name: String, base_branch: String, description: Option<String>) -> Self {
80        let now = Utc::now();
81        Self {
82            id: Uuid::new_v4(),
83            name,
84            description,
85            base_branch,
86            entries: Vec::new(),
87            entry_map: HashMap::new(),
88            status: StackStatus::Clean,
89            created_at: now,
90            updated_at: now,
91            is_active: false,
92        }
93    }
94
95    /// Add a new entry to the top of the stack
96    pub fn push_entry(&mut self, branch: String, commit_hash: String, message: String) -> Uuid {
97        let now = Utc::now();
98        let entry_id = Uuid::new_v4();
99
100        // Find the current top entry to set as parent
101        let parent_id = self.entries.last().map(|entry| entry.id);
102
103        let entry = StackEntry {
104            id: entry_id,
105            branch,
106            commit_hash,
107            message,
108            parent_id,
109            children: Vec::new(),
110            created_at: now,
111            updated_at: now,
112            is_submitted: false,
113            pull_request_id: None,
114            is_synced: false,
115        };
116
117        // Update parent's children if exists
118        if let Some(parent_id) = parent_id {
119            if let Some(parent) = self.entry_map.get_mut(&parent_id) {
120                parent.children.push(entry_id);
121            }
122        }
123
124        // Add to collections
125        self.entries.push(entry.clone());
126        self.entry_map.insert(entry_id, entry);
127        self.updated_at = now;
128
129        entry_id
130    }
131
132    /// Remove the top entry from the stack
133    pub fn pop_entry(&mut self) -> Option<StackEntry> {
134        if let Some(entry) = self.entries.pop() {
135            let entry_id = entry.id;
136            self.entry_map.remove(&entry_id);
137
138            // Update parent's children if exists
139            if let Some(parent_id) = entry.parent_id {
140                if let Some(parent) = self.entry_map.get_mut(&parent_id) {
141                    parent.children.retain(|&id| id != entry_id);
142                }
143            }
144
145            self.updated_at = Utc::now();
146            Some(entry)
147        } else {
148            None
149        }
150    }
151
152    /// Get an entry by ID
153    pub fn get_entry(&self, id: &Uuid) -> Option<&StackEntry> {
154        self.entry_map.get(id)
155    }
156
157    /// Get a mutable entry by ID
158    pub fn get_entry_mut(&mut self, id: &Uuid) -> Option<&mut StackEntry> {
159        self.entry_map.get_mut(id)
160    }
161
162    /// Get the base (first) entry of the stack
163    pub fn get_base_entry(&self) -> Option<&StackEntry> {
164        self.entries.first()
165    }
166
167    /// Get the top (last) entry of the stack
168    pub fn get_top_entry(&self) -> Option<&StackEntry> {
169        self.entries.last()
170    }
171
172    /// Get all entries that are children of the given entry
173    pub fn get_children(&self, entry_id: &Uuid) -> Vec<&StackEntry> {
174        if let Some(entry) = self.get_entry(entry_id) {
175            entry
176                .children
177                .iter()
178                .filter_map(|id| self.get_entry(id))
179                .collect()
180        } else {
181            Vec::new()
182        }
183    }
184
185    /// Get the parent of the given entry
186    pub fn get_parent(&self, entry_id: &Uuid) -> Option<&StackEntry> {
187        if let Some(entry) = self.get_entry(entry_id) {
188            entry
189                .parent_id
190                .and_then(|parent_id| self.get_entry(&parent_id))
191        } else {
192            None
193        }
194    }
195
196    /// Check if the stack is empty
197    pub fn is_empty(&self) -> bool {
198        self.entries.is_empty()
199    }
200
201    /// Get the number of entries in the stack
202    pub fn len(&self) -> usize {
203        self.entries.len()
204    }
205
206    /// Mark an entry as submitted with a pull request ID
207    pub fn mark_entry_submitted(&mut self, entry_id: &Uuid, pull_request_id: String) -> bool {
208        if let Some(entry) = self.get_entry_mut(entry_id) {
209            entry.is_submitted = true;
210            entry.pull_request_id = Some(pull_request_id);
211            entry.updated_at = Utc::now();
212            self.updated_at = Utc::now();
213            true
214        } else {
215            false
216        }
217    }
218
219    /// Mark an entry as synced
220    pub fn mark_entry_synced(&mut self, entry_id: &Uuid) -> bool {
221        if let Some(entry) = self.get_entry_mut(entry_id) {
222            entry.is_synced = true;
223            entry.updated_at = Utc::now();
224            self.updated_at = Utc::now();
225            true
226        } else {
227            false
228        }
229    }
230
231    /// Update stack status
232    pub fn update_status(&mut self, status: StackStatus) {
233        self.status = status;
234        self.updated_at = Utc::now();
235    }
236
237    /// Set this stack as active
238    pub fn set_active(&mut self, active: bool) {
239        self.is_active = active;
240        self.updated_at = Utc::now();
241    }
242
243    /// Get all branch names in this stack
244    pub fn get_branch_names(&self) -> Vec<String> {
245        self.entries
246            .iter()
247            .map(|entry| entry.branch.clone())
248            .collect()
249    }
250
251    /// Validate the stack structure and Git state integrity
252    pub fn validate(&self) -> Result<String, String> {
253        // Validate basic structure
254        if self.entries.is_empty() {
255            return Ok("Empty stack is valid".to_string());
256        }
257
258        // Check parent-child relationships
259        for (i, entry) in self.entries.iter().enumerate() {
260            if i == 0 {
261                // First entry should have no parent
262                if entry.parent_id.is_some() {
263                    return Err(format!(
264                        "First entry {} should not have a parent",
265                        entry.short_hash()
266                    ));
267                }
268            } else {
269                // Other entries should have the previous entry as parent
270                let expected_parent = &self.entries[i - 1];
271                if entry.parent_id != Some(expected_parent.id) {
272                    return Err(format!(
273                        "Entry {} has incorrect parent relationship",
274                        entry.short_hash()
275                    ));
276                }
277            }
278
279            // Check if parent exists in map
280            if let Some(parent_id) = entry.parent_id {
281                if !self.entry_map.contains_key(&parent_id) {
282                    return Err(format!(
283                        "Entry {} references non-existent parent {}",
284                        entry.short_hash(),
285                        parent_id
286                    ));
287                }
288            }
289        }
290
291        // Check that all entries are in the map
292        for entry in &self.entries {
293            if !self.entry_map.contains_key(&entry.id) {
294                return Err(format!(
295                    "Entry {} is not in the entry map",
296                    entry.short_hash()
297                ));
298            }
299        }
300
301        // Check for duplicate IDs
302        let mut seen_ids = std::collections::HashSet::new();
303        for entry in &self.entries {
304            if !seen_ids.insert(entry.id) {
305                return Err(format!("Duplicate entry ID: {}", entry.id));
306            }
307        }
308
309        // Check for duplicate branch names
310        let mut seen_branches = std::collections::HashSet::new();
311        for entry in &self.entries {
312            if !seen_branches.insert(&entry.branch) {
313                return Err(format!("Duplicate branch name: {}", entry.branch));
314            }
315        }
316
317        Ok("Stack validation passed".to_string())
318    }
319
320    /// Validate Git state integrity (requires Git repository access)
321    /// This checks that branch HEADs match the expected commit hashes
322    pub fn validate_git_integrity(
323        &self,
324        git_repo: &crate::git::GitRepository,
325    ) -> Result<String, String> {
326        use tracing::warn;
327
328        let mut issues = Vec::new();
329        let mut warnings = Vec::new();
330
331        for entry in &self.entries {
332            // Check if branch exists
333            if !git_repo.branch_exists(&entry.branch) {
334                issues.push(format!(
335                    "Branch '{}' for entry {} does not exist",
336                    entry.branch,
337                    entry.short_hash()
338                ));
339                continue;
340            }
341
342            // Check if branch HEAD matches stored commit hash
343            match git_repo.get_branch_head(&entry.branch) {
344                Ok(branch_head) => {
345                    if branch_head != entry.commit_hash {
346                        issues.push(format!(
347                            "🚨 BRANCH MODIFICATION DETECTED: Branch '{}' has been manually modified!\n   \
348                             Expected commit: {} (from stack entry)\n   \
349                             Actual commit:   {} (current branch HEAD)\n   \
350                             💡 Someone may have checked out '{}' and added commits.\n   \
351                             This breaks stack integrity!",
352                            entry.branch,
353                            &entry.commit_hash[..8],
354                            &branch_head[..8],
355                            entry.branch
356                        ));
357                    }
358                }
359                Err(e) => {
360                    warnings.push(format!(
361                        "Could not check branch '{}' HEAD: {}",
362                        entry.branch, e
363                    ));
364                }
365            }
366
367            // Check if commit still exists
368            match git_repo.commit_exists(&entry.commit_hash) {
369                Ok(exists) => {
370                    if !exists {
371                        issues.push(format!(
372                            "Commit {} for entry {} no longer exists",
373                            entry.short_hash(),
374                            entry.id
375                        ));
376                    }
377                }
378                Err(e) => {
379                    warnings.push(format!(
380                        "Could not verify commit {} existence: {}",
381                        entry.short_hash(),
382                        e
383                    ));
384                }
385            }
386        }
387
388        // Log warnings
389        for warning in &warnings {
390            warn!("{}", warning);
391        }
392
393        if !issues.is_empty() {
394            Err(format!(
395                "Git integrity validation failed:\n{}{}",
396                issues.join("\n"),
397                if !warnings.is_empty() {
398                    format!("\n\nWarnings:\n{}", warnings.join("\n"))
399                } else {
400                    String::new()
401                }
402            ))
403        } else if !warnings.is_empty() {
404            Ok(format!(
405                "Git integrity validation passed with warnings:\n{}",
406                warnings.join("\n")
407            ))
408        } else {
409            Ok("Git integrity validation passed".to_string())
410        }
411    }
412}
413
414impl StackEntry {
415    /// Check if this entry can be safely modified
416    pub fn can_modify(&self) -> bool {
417        !self.is_submitted && !self.is_synced
418    }
419
420    /// Get a short version of the commit hash
421    pub fn short_hash(&self) -> String {
422        if self.commit_hash.len() >= 8 {
423            self.commit_hash[..8].to_string()
424        } else {
425            self.commit_hash.clone()
426        }
427    }
428
429    /// Get a short version of the commit message
430    pub fn short_message(&self, max_len: usize) -> String {
431        if self.message.len() > max_len {
432            format!("{}...", &self.message[..max_len])
433        } else {
434            self.message.clone()
435        }
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    #[test]
444    fn test_create_empty_stack() {
445        let stack = Stack::new(
446            "test-stack".to_string(),
447            "main".to_string(),
448            Some("Test stack description".to_string()),
449        );
450
451        assert_eq!(stack.name, "test-stack");
452        assert_eq!(stack.base_branch, "main");
453        assert_eq!(
454            stack.description,
455            Some("Test stack description".to_string())
456        );
457        assert!(stack.is_empty());
458        assert_eq!(stack.len(), 0);
459        assert_eq!(stack.status, StackStatus::Clean);
460        assert!(!stack.is_active);
461    }
462
463    #[test]
464    fn test_push_pop_entries() {
465        let mut stack = Stack::new("test".to_string(), "main".to_string(), None);
466
467        // Push first entry
468        let entry1_id = stack.push_entry(
469            "feature-1".to_string(),
470            "abc123".to_string(),
471            "Add feature 1".to_string(),
472        );
473
474        assert_eq!(stack.len(), 1);
475        assert!(!stack.is_empty());
476
477        let entry1 = stack.get_entry(&entry1_id).unwrap();
478        assert_eq!(entry1.branch, "feature-1");
479        assert_eq!(entry1.commit_hash, "abc123");
480        assert_eq!(entry1.message, "Add feature 1");
481        assert_eq!(entry1.parent_id, None);
482        assert!(entry1.children.is_empty());
483
484        // Push second entry
485        let entry2_id = stack.push_entry(
486            "feature-2".to_string(),
487            "def456".to_string(),
488            "Add feature 2".to_string(),
489        );
490
491        assert_eq!(stack.len(), 2);
492
493        let entry2 = stack.get_entry(&entry2_id).unwrap();
494        assert_eq!(entry2.parent_id, Some(entry1_id));
495
496        // Check parent-child relationship
497        let updated_entry1 = stack.get_entry(&entry1_id).unwrap();
498        assert_eq!(updated_entry1.children, vec![entry2_id]);
499
500        // Pop entry
501        let popped = stack.pop_entry().unwrap();
502        assert_eq!(popped.id, entry2_id);
503        assert_eq!(stack.len(), 1);
504
505        // Check parent's children were updated
506        let updated_entry1 = stack.get_entry(&entry1_id).unwrap();
507        assert!(updated_entry1.children.is_empty());
508    }
509
510    #[test]
511    fn test_stack_navigation() {
512        let mut stack = Stack::new("test".to_string(), "main".to_string(), None);
513
514        let entry1_id = stack.push_entry(
515            "branch1".to_string(),
516            "hash1".to_string(),
517            "msg1".to_string(),
518        );
519        let entry2_id = stack.push_entry(
520            "branch2".to_string(),
521            "hash2".to_string(),
522            "msg2".to_string(),
523        );
524        let entry3_id = stack.push_entry(
525            "branch3".to_string(),
526            "hash3".to_string(),
527            "msg3".to_string(),
528        );
529
530        // Test base and top
531        assert_eq!(stack.get_base_entry().unwrap().id, entry1_id);
532        assert_eq!(stack.get_top_entry().unwrap().id, entry3_id);
533
534        // Test parent/child relationships
535        assert_eq!(stack.get_parent(&entry2_id).unwrap().id, entry1_id);
536        assert_eq!(stack.get_parent(&entry3_id).unwrap().id, entry2_id);
537        assert!(stack.get_parent(&entry1_id).is_none());
538
539        let children_of_1 = stack.get_children(&entry1_id);
540        assert_eq!(children_of_1.len(), 1);
541        assert_eq!(children_of_1[0].id, entry2_id);
542    }
543
544    #[test]
545    fn test_stack_validation() {
546        let mut stack = Stack::new("test".to_string(), "main".to_string(), None);
547
548        // Empty stack should be valid
549        assert!(stack.validate().is_ok());
550
551        // Add some entries
552        stack.push_entry(
553            "branch1".to_string(),
554            "hash1".to_string(),
555            "msg1".to_string(),
556        );
557        stack.push_entry(
558            "branch2".to_string(),
559            "hash2".to_string(),
560            "msg2".to_string(),
561        );
562
563        // Valid stack should pass validation
564        let result = stack.validate();
565        assert!(result.is_ok());
566        assert!(result.unwrap().contains("validation passed"));
567    }
568
569    #[test]
570    fn test_mark_entry_submitted() {
571        let mut stack = Stack::new("test".to_string(), "main".to_string(), None);
572        let entry_id = stack.push_entry(
573            "branch1".to_string(),
574            "hash1".to_string(),
575            "msg1".to_string(),
576        );
577
578        assert!(!stack.get_entry(&entry_id).unwrap().is_submitted);
579        assert!(stack
580            .get_entry(&entry_id)
581            .unwrap()
582            .pull_request_id
583            .is_none());
584
585        assert!(stack.mark_entry_submitted(&entry_id, "PR-123".to_string()));
586
587        let entry = stack.get_entry(&entry_id).unwrap();
588        assert!(entry.is_submitted);
589        assert_eq!(entry.pull_request_id, Some("PR-123".to_string()));
590    }
591
592    #[test]
593    fn test_branch_names() {
594        let mut stack = Stack::new("test".to_string(), "main".to_string(), None);
595
596        assert!(stack.get_branch_names().is_empty());
597
598        stack.push_entry(
599            "feature-1".to_string(),
600            "hash1".to_string(),
601            "msg1".to_string(),
602        );
603        stack.push_entry(
604            "feature-2".to_string(),
605            "hash2".to_string(),
606            "msg2".to_string(),
607        );
608
609        let branches = stack.get_branch_names();
610        assert_eq!(branches, vec!["feature-1", "feature-2"]);
611    }
612}