solarboat 0.8.9

A CLI tool for intelligent Terraform operations management with automatic dependency detection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::process::Command;
use crate::utils::logger;
use crate::utils::error::{SolarboatError, SafeOperations};

#[derive(Debug, Default)]
pub struct Module {
    depends_on: Vec<String>,
    used_by: Vec<String>,
    is_stateful: bool,
}

/// Cleaner version of get_changed_modules with better output
pub fn get_changed_modules_clean(root_dir: &str, all: bool, default_branch: &str, recent_commits: u32) -> Result<Vec<String>, String> {
    let mut modules = HashMap::new();

    // Always discover modules from the root directory
    logger::dependency_graph_progress("Discovering modules...");
    discover_modules(root_dir, &mut modules)?;
    
    logger::dependency_graph_progress("Building dependency graph...");
    build_dependency_graph(&mut modules)?;

    if all {
        // If all is true, return all stateful modules
        let stateful_modules: Vec<String> = modules
            .iter()
            .filter(|(_, module)| module.is_stateful)
            .map(|(path, _)| path.clone())
            .collect();
        return Ok(stateful_modules);
    }

    // Check if we're on the main branch and handle accordingly
    let current_branch = get_current_branch(root_dir)?;
    let is_on_main = current_branch == default_branch;
    
    if is_on_main {
        logger::environment_detection("branch", &format!("Currently on {} branch - using enhanced change detection", current_branch));
        
        if let Ok(pr_number) = std::env::var("SOLARBOAT_PR_NUMBER") {
            if !pr_number.is_empty() {
                logger::environment_detection("pipeline", &format!("Detected CD pipeline environment (PR #{})", pr_number));
                let changed_files = get_cd_pipeline_changes(root_dir, &pr_number, default_branch)?;
                let affected_modules = process_changed_modules(&changed_files, &mut modules)?;
                
                if affected_modules.is_empty() {
                    logger::info(&format!("No changes detected in PR #{}", pr_number));
                }
                
                return Ok(affected_modules);
            }
        }

        logger::environment_detection("local", &format!("Running in local environment - checking last {} commits", recent_commits));
        let changed_files = get_main_branch_changes_local_clean(root_dir, recent_commits)?;
        let affected_modules = process_changed_modules(&changed_files, &mut modules)?;
        
        // Show git analysis summary with actual affected modules count
        logger::git_analysis_summary(recent_commits as usize, changed_files.len(), affected_modules.len());
        
        // If no changes detected on main, provide helpful message
        if affected_modules.is_empty() {
            logger::info("No changes detected on main branch. This could mean:");
            logger::info("  • No recent commits with .tf changes");
            logger::info("  • Changes were already applied");
            logger::info("  • Use --all flag to process all modules");
        }
        
        return Ok(affected_modules);
    }

    let changed_files = get_git_changed_files(".", default_branch)?;
    let affected_modules = process_changed_modules(&changed_files, &mut modules)?;

    if root_dir != "." {
        logger::info(&format!("Filtering modules with path: {}", root_dir));
        
        let filtered_modules: Vec<String> = affected_modules
            .into_iter()
            .filter(|path| {
                // Check if the path contains the root_dir
                let contains_path = path.contains(&format!("/{}/", root_dir)) || 
                                   path.ends_with(&format!("/{}", root_dir));
                
                contains_path
            })
            .collect();
            
        return Ok(filtered_modules);
    }
    
    Ok(affected_modules)
}

pub fn discover_modules(root_dir: &str, modules: &mut HashMap<String, Module>) -> Result<(), String> {
    for entry in fs::read_dir(root_dir).map_err(|e| e.to_string())? {
        let entry = entry.map_err(|e| e.to_string())?;
        let path = entry.path();

        if path.is_dir() {
            discover_modules(path.to_str().ok_or("Invalid path")?, modules)?;

            let tf_files: Vec<_> = fs::read_dir(&path)
                .map_err(|e| e.to_string())?
                .filter_map(|e| e.ok())
                .filter(|e| e.path().extension().map_or(false, |ext| ext == "tf"))
                .collect();

            if !tf_files.is_empty() {
                let abs_path = fs::canonicalize(&path).map_err(|e| e.to_string())?;
                let abs_path_str = abs_path.to_str().ok_or("Invalid path")?.to_string();

                modules.entry(abs_path_str.clone()).or_insert(Module {
                    is_stateful: has_backend_config(&tf_files),
                    ..Default::default()
                });
            }
        }
    }
    Ok(())
}

pub fn build_dependency_graph(modules: &mut HashMap<String, Module>) -> Result<(), String> {
    let dependencies = collect_dependencies(modules)?;

    for (path, dep) in dependencies {
        if let Some(module) = modules.get_mut(&path) {
            module.depends_on.push(dep.clone());
        }
        if let Some(dep_module) = modules.get_mut(&dep) {
            dep_module.used_by.push(path.clone());
        }
    }

    logger::info(&format!("Found {} modules repo-wide", modules.len()));
    Ok(())
}

pub fn collect_dependencies(modules: &HashMap<String, Module>) -> Result<Vec<(String, String)>, String> {
    let mut dependencies = Vec::new();

    for (path, _module) in modules {
        let tf_files: Vec<_> = fs::read_dir(path)
            .map_err(|e| e.to_string())?
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().map_or(false, |ext| ext == "tf"))
            .collect();

        for file in tf_files {
            let content = fs::read_to_string(file.path()).map_err(|e| e.to_string())?;
            let deps = find_module_dependencies(&content, path);

            for dep in deps {
                dependencies.push((path.clone(), dep));
            }
        }
    }

    Ok(dependencies)
}

pub fn find_module_dependencies(content: &str, current_dir: &str) -> Vec<String> {
    let mut deps = Vec::new();
    let lines: Vec<&str> = content.lines().collect();
    let mut in_module_block = false;

    for line in lines {
        let trimmed_line = line.trim();

        if trimmed_line.starts_with("module") && trimmed_line.contains("{") {
            in_module_block = true;
            continue;
        }

        if in_module_block {
            if trimmed_line.contains("source") {
                let parts: Vec<&str> = trimmed_line.split('=').collect();
                if parts.len() == 2 {
                    let source = parts[1].trim().trim_matches(|c| c == '"' || c == '\'');
                    let module_path = Path::new(current_dir).join(source);
                    if let Ok(abs_path) = fs::canonicalize(module_path) {
                        if let Some(abs_path_str) = abs_path.to_str() {
                            deps.push(abs_path_str.to_string());
                        }
                    }
                }
            }
            if trimmed_line.contains("}") {
                in_module_block = false;
            }
        }
    }
    deps
}

pub fn has_backend_config(tf_files: &[fs::DirEntry]) -> bool {
    let has_module_blocks = tf_files.iter().any(|file| {
        if let Ok(content) = fs::read_to_string(file.path()) {
            let lines: Vec<&str> = content.lines().collect();
            for line in lines {
                let trimmed_line = line.trim();
                if trimmed_line.starts_with("module") && trimmed_line.contains("{") {
                    return true;
                }
            }
        }
        false
    });
    
    if has_module_blocks {
        return true;
    }
    
    for file in tf_files {
        if let Ok(content) = fs::read_to_string(file.path()) {
            let lines: Vec<&str> = content.lines().collect();
            let mut in_terraform_block = false;
            let mut brace_count = 0;
            
            for line in lines {
                let trimmed_line = line.trim();
                
                if trimmed_line.is_empty() || trimmed_line.starts_with('#') || trimmed_line.starts_with("//") {
                    continue;
                }
                
                if trimmed_line.starts_with("terraform") && trimmed_line.contains("{") {
                    in_terraform_block = true;
                    brace_count += 1;
                    continue;
                }
                
                if in_terraform_block && trimmed_line.starts_with("backend") && trimmed_line.contains("\"") {
                    return true;
                }
                
                if trimmed_line.contains("{") {
                    brace_count += 1;
                }
                if trimmed_line.contains("}") {
                    brace_count -= 1;
                    if brace_count == 0 {
                        in_terraform_block = false;
                    }
                }
            }
        }
    }
    
    if let Some(first_file) = tf_files.first() {
        if let Some(dir_path) = first_file.path().parent() {
            if let Ok(entries) = fs::read_dir(dir_path) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let path = entry.path();
                    if path.is_file() && path.extension().map_or(false, |ext| ext == "tfstate") {
                        return true;
                    }
                }
            }
        }
    }
    
    false
}

/// Get the current branch name
fn get_current_branch(root_dir: &str) -> Result<String, String> {
    // Try to get from environment first (for CI/CD)
    if let Ok(branch) = std::env::var("GITHUB_REF_NAME") {
        return Ok(branch);
    }
    
    // Fallback to git command
    let output = Command::new("git")
        .args(&["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;
        
    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        Err("Failed to get current branch".to_string())
    }
}

/// Get changes specifically for main branch scenarios (local environment) - clean version
fn get_main_branch_changes_local_clean(root_dir: &str, recent_commits: u32) -> Result<Vec<String>, String> {
    let mut total_changes = Vec::new();
    
    // Strategy 1: Check recent commits (configurable count)
    let recent_changes = get_recent_commit_changes_clean(root_dir, recent_commits as usize)?;
    total_changes.extend(recent_changes);
    
    if !total_changes.is_empty() {
        logger::info("Found changes in recent commits");
        return Ok(total_changes);
    }
    
    // Strategy 2: Check if there are any staged or unstaged changes
    let uncommitted_changes = get_uncommitted_changes(root_dir)?;
    if !uncommitted_changes.is_empty() {
        logger::info("Found uncommitted changes");
        total_changes.extend(uncommitted_changes);
        return Ok(total_changes);
    }
    
    // Strategy 3: Compare with a reference point (e.g., last tag or specific commit)
    let reference_changes = get_reference_changes(root_dir)?;
    if !reference_changes.is_empty() {
        logger::info("Found changes compared to reference point");
        total_changes.extend(reference_changes);
        return Ok(total_changes);
    }
    
    logger::info("No changes detected using any strategy");
    Ok(Vec::new())
}

/// Get changes specifically for main branch scenarios (local environment) - original version
#[allow(dead_code)]
fn get_main_branch_changes_local(root_dir: &str, recent_commits: u32) -> Result<Vec<String>, String> {
    // Strategy 1: Check recent commits (configurable count)
    let recent_changes = get_recent_commit_changes(root_dir, recent_commits as usize)?;
    if !recent_changes.is_empty() {
        logger::info("Found changes in recent commits");
        return Ok(recent_changes);
    }
    
    // Strategy 2: Check if there are any staged or unstaged changes
    let uncommitted_changes = get_uncommitted_changes(root_dir)?;
    if !uncommitted_changes.is_empty() {
        logger::info("Found uncommitted changes");
        return Ok(uncommitted_changes);
    }
    
    // Strategy 3: Compare with a reference point (e.g., last tag or specific commit)
    let reference_changes = get_reference_changes(root_dir)?;
    if !reference_changes.is_empty() {
        logger::info("Found changes compared to reference point");
        return Ok(reference_changes);
    }
    
    logger::info("No changes detected using any strategy");
    Ok(Vec::new())
}

/// Get changes for CD pipeline environment (Pipeline-supplied commits)
fn get_cd_pipeline_changes(root_dir: &str, pr_number: &str, default_branch: &str) -> Result<Vec<String>, String> {
    logger::info(&format!("Analyzing changes for PR #{} against {}", pr_number, default_branch));
    
    // Strategy 1: Use pipeline-supplied commit information (PRIORITY)
    let pipeline_changes = get_pipeline_supplied_changes(root_dir, pr_number);
    match pipeline_changes {
        Ok(changes) if !changes.is_empty() => {
            logger::info("Found changes using pipeline-supplied commits");
            return Ok(changes);
        }
        Ok(_) => {
            logger::info("Pipeline-supplied commits found but no changes detected");
            return Ok(Vec::new());
        }
        Err(_) => {
            logger::info("No pipeline-supplied commits available, using fallback strategies");
        }
    }
    
    // Strategy 2: Fallback to merge base detection (legacy)
    if let Ok(changes) = get_pr_changes(root_dir, pr_number, default_branch) {
        if !changes.is_empty() {
            logger::info("Found changes using merge base detection (fallback)");
            return Ok(changes);
        }
    }
    
    // Strategy 3: Fallback to recent commits in the PR
    let recent_changes = get_recent_commit_changes(root_dir, 10)?;
    if !recent_changes.is_empty() {
        logger::info("Found changes in recent commits (fallback)");
        return Ok(recent_changes);
    }
    
    // Strategy 4: Check for uncommitted changes
    let uncommitted_changes = get_uncommitted_changes(root_dir)?;
    if !uncommitted_changes.is_empty() {
        logger::info("Found uncommitted changes");
        return Ok(uncommitted_changes);
    }
    
    logger::info(&format!("No changes detected for PR #{}", pr_number));
    Ok(Vec::new())
}

/// Get changes using pipeline-supplied commit information
fn get_pipeline_supplied_changes(root_dir: &str, _pr_number: &str) -> Result<Vec<String>, String> {
    // Check for pipeline-supplied commit information
    let base_commit = std::env::var("SOLARBOAT_BASE_COMMIT").ok();
    let head_commit = std::env::var("SOLARBOAT_HEAD_COMMIT").ok();
    let base_branch = std::env::var("SOLARBOAT_BASE_BRANCH").ok();
    let head_branch = std::env::var("SOLARBOAT_HEAD_BRANCH").ok();
    
    // If we have both base and head commits, use them directly
    if let (Some(base), Some(head)) = (base_commit.clone(), head_commit.clone()) {
        logger::info("Using pipeline-supplied commits:");
        logger::info(&format!("   • Base commit: {}", base));
        logger::info(&format!("   • Head commit: {}", head));
        if let Some(base_branch) = base_branch.clone() {
            logger::info(&format!("   • Base branch: {}", base_branch));
        }
        if let Some(head_branch) = head_branch.clone() {
            logger::info(&format!("   • Head branch: {}", head_branch));
        }
        
        return get_changes_between_commits(root_dir, &base, &head);
    }
    
    // If we only have base commit, compare with HEAD
    if let Some(base) = base_commit {
        logger::info(&format!("Using pipeline-supplied base commit: {}", base));
        return get_changes_between_commits(root_dir, &base, "HEAD");
    }
    
    // If we only have head commit, compare with default branch
    if let Some(head) = head_commit {
        logger::info(&format!("Using pipeline-supplied head commit: {}", head));
        // This is less ideal, but we can compare with the default branch
        return get_changes_between_commits(root_dir, "main", &head);
    }
    
    // No pipeline-supplied commits available
    logger::info("No pipeline-supplied commits found, falling back to merge base detection");
    Ok(Vec::new()) // Return empty list instead of error
}

/// Get changes between PR branch and default branch
fn get_pr_changes(root_dir: &str, pr_number: &str, default_branch: &str) -> Result<Vec<String>, String> {
    // Try to get the merge base between the current branch and the default branch
    let merge_base_output = Command::new("git")
        .args(&["merge-base", default_branch, "HEAD"])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;
    
    if merge_base_output.status.success() {
        let merge_base = String::from_utf8_lossy(&merge_base_output.stdout).trim().to_string();
        logger::info(&format!("Using merge base: {}", merge_base));
        return get_changes_between_commits(root_dir, &merge_base, "HEAD");
    }
    
    // Fallback: try to get changes between origin/default_branch and HEAD
    let origin_merge_base_output = Command::new("git")
        .args(&["merge-base", &format!("origin/{}", default_branch), "HEAD"])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;
    
    if origin_merge_base_output.status.success() {
        let merge_base = String::from_utf8_lossy(&origin_merge_base_output.stdout).trim().to_string();
        logger::info(&format!("Using origin merge base: {}", merge_base));
        return get_changes_between_commits(root_dir, &merge_base, "HEAD");
    }
    
    // If we can't find a merge base, return empty list
    logger::warn(&format!("Could not determine merge base for PR #{}", pr_number));
    Ok(Vec::new())
}

/// Get changes from recent commits (clean version)
fn get_recent_commit_changes_clean(root_dir: &str, commit_count: usize) -> Result<Vec<String>, String> {
    let mut changed_files = Vec::new();

    logger::info(&format!("Getting changes from last {} commits", commit_count));
    
    // Get the list of recent commits
    let log_output = Command::new("git")
        .args(&["log", "--oneline", "-n", &commit_count.to_string()])
        .current_dir(root_dir)
        .output()
        .map_err(|e| format!("Failed to execute git log: {}", e))?;

    if log_output.status.success() {
        let output_str = String::from_utf8_lossy(&log_output.stdout);
        let commits: Vec<&str> = output_str
            .lines()
            .filter_map(|line| line.split_whitespace().next())
            .collect();

        if commits.len() >= 2 {
            // Get changes between the first and last commit in the range
            let from_commit = commits.last().unwrap();
            let to_commit = commits.first().unwrap();
            
            changed_files = get_changes_between_commits_clean(root_dir, from_commit, to_commit)
                .map_err(|e| format!("Failed to get changes between commits: {}", e))?;
        }
    }

    // Use the new logger method for cleaner output
    logger::git_changes_progress(&format!("last {} commits", commit_count), changed_files.len(), &changed_files);

    Ok(changed_files)
}

/// Get changes from recent commits (original version)
fn get_recent_commit_changes(root_dir: &str, commit_count: usize) -> Result<Vec<String>, String> {
    let mut changed_files = Vec::new();
    
    // Get the last N commits
    let log_output = Command::new("git")
        .args(&["log", "--oneline", "-n", &commit_count.to_string()])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;
        
    if !log_output.status.success() {
        return Ok(Vec::new());
    }
    
    let log_output_str = String::from_utf8_lossy(&log_output.stdout);
    let commits: Vec<&str> = log_output_str
        .lines()
        .filter_map(|line| line.split_whitespace().next())
        .collect();
    
    // Check changes in each commit
    for commit in commits {
        let changes = get_changes_between_commits(root_dir, &format!("{}~1", commit), commit)?;
        changed_files.extend(changes);
    }
    
    // Remove duplicates
    changed_files.sort();
    changed_files.dedup();
    
    Ok(changed_files)
}

/// Get uncommitted changes (staged and unstaged)
fn get_uncommitted_changes(root_dir: &str) -> Result<Vec<String>, String> {
    let mut changed_files = Vec::new();
    
    // Get staged changes
    let staged_output = Command::new("git")
        .args(&["diff", "--cached", "--name-only"])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;
        
    if staged_output.status.success() {
        changed_files.extend(
            String::from_utf8_lossy(&staged_output.stdout)
                .lines()
                .filter(|line| line.ends_with(".tf"))
                .map(|line| Path::new(root_dir).join(line).to_string_lossy().to_string())
        );
    }
    
    // Get unstaged changes
    let unstaged_output = Command::new("git")
        .args(&["diff", "--name-only"])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;
        
    if unstaged_output.status.success() {
        changed_files.extend(
            String::from_utf8_lossy(&unstaged_output.stdout)
                .lines()
                .filter(|line| line.ends_with(".tf"))
                .map(|line| Path::new(root_dir).join(line).to_string_lossy().to_string())
        );
    }
    
    // Remove duplicates
    changed_files.sort();
    changed_files.dedup();
    
    Ok(changed_files)
}

/// Get changes compared to a reference point (last tag or specific commit)
fn get_reference_changes(root_dir: &str) -> Result<Vec<String>, String> {
    // Try to find the last tag
    let tag_output = Command::new("git")
        .args(&["describe", "--tags", "--abbrev=0"])
        .current_dir(root_dir)
        .output();
        
    if let Ok(output) = tag_output {
        if output.status.success() {
            let tag = String::from_utf8_lossy(&output.stdout).trim().to_string();
            logger::info(&format!("Comparing with last tag: {}", tag));
            return get_changes_between_commits(root_dir, &tag, "HEAD");
        }
    }
    
    // Fallback: compare with a commit from 1 day ago
    let date_output = Command::new("git")
        .args(&["rev-list", "-n", "1", "--before=1 day ago", "HEAD"])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;
        
    if date_output.status.success() {
        let commit = String::from_utf8_lossy(&date_output.stdout).trim().to_string();
        if !commit.is_empty() {
            logger::info(&format!("Comparing with commit from 1 day ago: {}", commit));
            return get_changes_between_commits(root_dir, &commit, "HEAD");
        }
    }
    
    Ok(Vec::new())
}

/// Get changes between two specific commits (clean version)
fn get_changes_between_commits_clean(root_dir: &str, from_commit: &str, to_commit: &str) -> Result<Vec<String>, SolarboatError> {
    let mut changed_files = Vec::new();

    logger::info(&format!("Getting changes between {} and {}", from_commit, to_commit));
    
    // Get changes between the two commits
    let diff_output = Command::new("git")
        .args(&["diff", "--name-only", from_commit, to_commit])
        .current_dir(root_dir)
        .output()
        .map_err(|e| SolarboatError::Process {
            command: "git diff".to_string(),
            args: vec!["diff".to_string(), "--name-only".to_string(), from_commit.to_string(), to_commit.to_string()],
            cause: e.to_string(),
            exit_code: None,
        })?;

    if diff_output.status.success() {
        changed_files.extend(
            String::from_utf8_lossy(&diff_output.stdout)
                .lines()
                .filter(|line| line.ends_with(".tf"))
                .filter_map(|line| {
                    // Use a more robust approach to handle paths that might not exist
                    let file_path = Path::new(root_dir).join(line);
                    if file_path.exists() {
                        // If the file exists, canonicalize it
                        SafeOperations::canonicalize(&file_path)
                            .and_then(|canonical_path| SafeOperations::os_str_to_string(canonical_path.as_os_str()))
                            .ok()
                    } else {
                        // If the file doesn't exist, use the absolute path from the current directory
                        let current_dir = SafeOperations::current_dir().ok()?;
                        let path = current_dir.join(root_dir).join(line);
                        SafeOperations::os_str_to_string(path.as_os_str()).ok()
                    }
                })
        );
    }

    // Remove duplicates
    changed_files.sort();
    changed_files.dedup();

    if !changed_files.is_empty() {
        logger::info(&format!("Found {} changed .tf files", changed_files.len()));
        logger::changed_files_summary(&changed_files);
    } else {
        logger::info("No .tf files changed between the commits");
    }

    Ok(changed_files)
}

/// Get changes between two specific commits (original version for backward compatibility)
fn get_changes_between_commits(root_dir: &str, from_commit: &str, to_commit: &str) -> Result<Vec<String>, String> {
    let mut changed_files = Vec::new();

    logger::info(&format!("Getting changes between {} and {}", from_commit, to_commit));
    
    // Get changes between the two commits
    let diff_output = Command::new("git")
        .args(&["diff", "--name-only", from_commit, to_commit])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;

    if diff_output.status.success() {
        changed_files.extend(
            String::from_utf8_lossy(&diff_output.stdout)
                .lines()
                .filter(|line| line.ends_with(".tf"))
                .map(|line| {
                    // Use a more robust approach to handle paths that might not exist
                    let file_path = Path::new(root_dir).join(line);
                    if file_path.exists() {
                        // If the file exists, canonicalize it
                        fs::canonicalize(file_path)
                            .map_err(|e| e.to_string())
                            .unwrap()
                            .to_str()
                            .unwrap()
                            .to_string()
                    } else {
                        // If the file doesn't exist, use the absolute path from the current directory
                        let current_dir = std::env::current_dir().map_err(|e| e.to_string()).unwrap();
                        current_dir.join(root_dir).join(line)
                            .to_str()
                            .unwrap()
                            .to_string()
                    }
                })
        );
    }

    // Remove duplicates
    changed_files.sort();
    changed_files.dedup();

    if !changed_files.is_empty() {
        logger::info(&format!("Found {} changed .tf files", changed_files.len()));
        logger::changed_files_summary(&changed_files);
    } else {
        logger::info("No .tf files changed between the commits");
    }

    Ok(changed_files)
}

pub fn get_git_changed_files(root_dir: &str, default_branch: &str) -> Result<Vec<String>, String> {
    // First, try to get the merge-base with origin/{default_branch}
    let merge_base_output = Command::new("git")
        .args(&["merge-base", &format!("origin/{}", default_branch), "HEAD"])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;

    let merge_base = if merge_base_output.status.success() {
        String::from_utf8_lossy(&merge_base_output.stdout).trim().to_string()
    } else {
        // If origin/{default_branch} is not available, try with local {default_branch}
        let local_merge_base = Command::new("git")
            .args(&["merge-base", default_branch, "HEAD"])
            .current_dir(root_dir)
            .output()
            .map_err(|e| e.to_string())?;
            
        if !local_merge_base.status.success() {
            // If we can't find a merge base, return an empty list
            return Ok(Vec::new());
        }
        String::from_utf8_lossy(&local_merge_base.stdout).trim().to_string()
    };

    // Get both staged and unstaged changes
    let mut changed_files = Vec::new();

    // Get uncommitted changes
    let status_output = Command::new("git")
        .arg("status")
        .arg("--porcelain")
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;

    if status_output.status.success() {
        changed_files.extend(
            String::from_utf8_lossy(&status_output.stdout)
                .lines()
                .filter(|line| line.ends_with(".tf"))
                .map(|line| {
                    let file = line[3..].trim();
                    // Use a more robust approach to handle paths that might not exist
                    let file_path = Path::new(root_dir).join(file);
                    if file_path.exists() {
                        // If the file exists, canonicalize it
                        fs::canonicalize(file_path)
                            .map_err(|e| e.to_string())
                            .unwrap()
                            .to_str()
                            .unwrap()
                            .to_string()
                    } else {
                        // If the file doesn't exist, use the absolute path from the current directory
                        let current_dir = std::env::current_dir().map_err(|e| e.to_string()).unwrap();
                        current_dir.join(root_dir).join(file)
                            .to_str()
                            .unwrap()
                            .to_string()
                    }
                })
        );
    }

    // Get changes between current branch and merge-base
    let diff_output = Command::new("git")
        .args(&["diff", "--name-only", &merge_base])
        .current_dir(root_dir)
        .output()
        .map_err(|e| e.to_string())?;

    if diff_output.status.success() {
        changed_files.extend(
            String::from_utf8_lossy(&diff_output.stdout)
                .lines()
                .filter(|line| line.ends_with(".tf"))
                .map(|line| {
                    // Use a more robust approach to handle paths that might not exist
                    let file_path = Path::new(root_dir).join(line);
                    if file_path.exists() {
                        // If the file exists, canonicalize it
                        fs::canonicalize(file_path)
                            .map_err(|e| e.to_string())
                            .unwrap()
                            .to_str()
                            .unwrap()
                            .to_string()
                    } else {
                        // If the file doesn't exist, use the absolute path from the current directory
                        let current_dir = std::env::current_dir().map_err(|e| e.to_string()).unwrap();
                        current_dir.join(root_dir).join(line)
                            .to_str()
                            .unwrap()
                            .to_string()
                    }
                })
        );
    }

    // Remove duplicates
    changed_files.sort();
    changed_files.dedup();

    Ok(changed_files)
}

pub fn process_changed_modules(changed_files: &[String], modules: &mut HashMap<String, Module>) -> Result<Vec<String>, String> {
    let mut affected_modules = Vec::new();
    let mut processed = HashMap::new();

    // Collect all module paths first
    let module_paths: Vec<String> = modules.keys().cloned().collect();

    // For each changed file, find the module it belongs to
    for file in changed_files {
        let file_path = Path::new(file);
        
        // Find the module this file belongs to
        for module_path in &module_paths {
            let module_path = Path::new(module_path);
            
            // Check if the file is in this module or a subdirectory of it
            if file_path.starts_with(module_path) {
                mark_module_changed(module_path.to_str().unwrap(), modules, &mut affected_modules, &mut processed);
                break;
            }
        }
    }

    Ok(affected_modules)
}

pub fn mark_module_changed(module_path: &str, all_modules: &mut HashMap<String, Module>, affected_modules: &mut Vec<String>, processed: &mut HashMap<String, bool>) {
    if *processed.get(module_path).unwrap_or(&false) {
        return;
    }
    processed.insert(module_path.to_string(), true);

    if let Some(module) = all_modules.get(module_path) {
        if module.is_stateful {
            // Add this stateful module to affected modules if not already added
            if !affected_modules.contains(&module_path.to_string()) {
                affected_modules.push(module_path.to_string());
            }
            
            // We no longer mark dependents as changed
            // This ensures only directly changed modules are included
        } else {
            // For stateless modules, we need to check if they are used by any stateful modules
            // If so, we mark those stateful modules as changed as well
            if !module.used_by.is_empty() {
                logger::info(&format!("Stateless module with changes: {}", module_path.split('/').last().unwrap_or(module_path)));
                
                // Check all modules that use this stateless module
                for user_module_path in &module.used_by {
                    if let Some(user_module) = all_modules.get(user_module_path) {
                        if user_module.is_stateful {
                            // Mark this stateful module as affected since it uses a changed stateless module
                            // Only add and print if not already in the list
                            if !affected_modules.contains(user_module_path) {
                                logger::info(&format!("Adding stateful module that uses changed stateless module: {}", 
                                         user_module_path.split('/').last().unwrap_or(user_module_path)));
                                affected_modules.push(user_module_path.clone());
                            }
                        }
                    }
                }
            }
        }
    }
}