guardy 0.2.4

Fast, secure git hooks in Rust with secret scanning and protected file synchronization
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
use std::{
    fs,
    path::{Path, PathBuf},
    sync::{Arc, LazyLock},
};

use anyhow::Result;
use dialoguer::{Select, theme::ColorfulTheme};
use ignore::WalkBuilder;
use similar::{ChangeTag, TextDiff};
use syntect::{
    easy::HighlightLines, highlighting::ThemeSet, parsing::SyntaxSet,
    util::as_24_bit_terminal_escaped,
};

use super::SyncStatus;
use crate::{
    cli::output,
    config::{CONFIG, sync::RepoConfig},
    git::remote::RemoteOperations,
};

/// Effective list of repositories to sync (computed once and cached)
/// Combines single repo fields from CLI/ENV/file with repos array from file
/// Single repo gets prepended (higher priority) to the repos array
pub static REPOS: LazyLock<Arc<Vec<RepoConfig>>> = LazyLock::new(|| {
    let mut repos = Vec::new();

    // First, check if we have single repo fields populated
    if let (Some(repo_url), Some(version_str)) = (&CONFIG.sync.repo, &CONFIG.sync.version) {
        let single_repo = RepoConfig {
            name: "cli-repo".into(),
            repo: repo_url.as_str().into(),
            version: version_str.as_str().into(),
            source_path: CONFIG.sync.source_path.as_deref().unwrap_or(".").into(),
            dest_path: CONFIG.sync.dest_path.as_deref().unwrap_or(".").into(),
            include: CONFIG.sync.include.clone(),
            exclude: CONFIG.sync.exclude.clone(),
            protected: false, // CLI repos are not protected by default
        };
        repos.push(single_repo);
    }

    // Then add repos from the array (file config)
    repos.extend(CONFIG.sync.repolist.iter().cloned());

    Arc::new(repos)
});

pub struct SyncManager {
    cache_dir: PathBuf,
    remote_ops: RemoteOperations,
    // For interactive mode
    syntax_set: SyntaxSet,
    theme_set: ThemeSet,
}

#[derive(Debug, Clone)]
enum FileAction {
    Update,
    Skip,
    UpdateAll,
    SkipAll,
    Quit,
}

impl SyncManager {
    pub fn new() -> Result<Self> {
        let cache_dir = PathBuf::from(".guardy/cache");
        std::fs::create_dir_all(&cache_dir)?;

        // Create .gitignore in .guardy directory to ignore all contents
        let guardy_gitignore = PathBuf::from(".guardy/.gitignore");
        if !guardy_gitignore.exists() {
            std::fs::write(&guardy_gitignore, "*\n")?;
        }

        let remote_ops = RemoteOperations::new(cache_dir.clone());

        Ok(Self {
            cache_dir,
            remote_ops,
            syntax_set: SyntaxSet::load_defaults_newlines(),
            theme_set: ThemeSet::load_defaults(),
        })
    }

    /// Get files matching patterns using ignore crate
    fn get_files(&self, source: &Path, repo: &RepoConfig) -> Result<Vec<PathBuf>> {
        let mut builder = WalkBuilder::new(source);

        // Disable automatic ignore file discovery - only use our custom patterns
        builder.standard_filters(false);

        // Create syncignore file in .guardy/ directory for patterns
        let syncignore_file = if !repo.exclude.is_empty() {
            let ignore_file = self.cache_dir.join(".syncignore");
            fs::write(&ignore_file, repo.exclude.join("\n"))?;
            // Copy the syncignore file to the source directory temporarily
            let source_ignore = source.join(".syncignore");
            fs::copy(&ignore_file, &source_ignore)?;
            builder.add_custom_ignore_filename(".syncignore");
            Some((ignore_file, source_ignore))
        } else {
            None
        };

        let result = builder
            .build()
            .filter_map(|entry| entry.ok())
            .filter(|entry| entry.path().is_file())
            .filter_map(|entry| {
                entry
                    .path()
                    .strip_prefix(source)
                    .ok()
                    .map(|p| p.to_path_buf())
            })
            .filter(|path| path.file_name() != Some(".syncignore".as_ref())) // Filter out temp file
            .collect();

        // Cleanup syncignore files
        if let Some((ignore_file, source_ignore)) = syncignore_file {
            let _ = fs::remove_file(ignore_file);
            let _ = fs::remove_file(source_ignore);
        }

        Ok(result)
    }

    /// Check which files differ between source and destination
    fn files_differ(&self, files: &[PathBuf], src: &Path, dst: &Path) -> Vec<PathBuf> {
        let mut changed = Vec::new();

        for f in files {
            let src_file = src.join(f);
            let dst_file = dst.join(f);

            tracing::trace!("Checking file: {:?}", f);
            tracing::trace!("  Source: {:?}", src_file);
            tracing::trace!("  Dest: {:?}", dst_file);

            if !dst_file.exists() {
                tracing::debug!("File {:?} doesn't exist in destination", f);
                changed.push(f.clone());
                continue;
            }

            let src_meta = match fs::metadata(&src_file) {
                Ok(m) => m,
                Err(e) => {
                    tracing::warn!("Failed to get metadata for source {:?}: {}", src_file, e);
                    continue;
                }
            };

            let dst_meta = match fs::metadata(&dst_file) {
                Ok(m) => m,
                Err(e) => {
                    tracing::warn!("Failed to get metadata for dest {:?}: {}", dst_file, e);
                    continue;
                }
            };

            let src_len = src_meta.len();
            let dst_len = dst_meta.len();

            if src_len != dst_len {
                tracing::debug!(
                    "File {:?} size differs: src={}, dst={}",
                    f,
                    src_len,
                    dst_len
                );
                changed.push(f.clone());
            } else {
                tracing::trace!("File {:?} unchanged (size={})", f, src_len);
            }
        }

        changed
    }

    /// Update cache from remote repository using git pull
    fn update_cache(&self, repo: &RepoConfig) -> Result<PathBuf> {
        let repo_name = self.extract_repo_name(&repo.repo);
        let repo_path = self.cache_dir.join(&repo_name);

        if !repo_path.exists() {
            // Clone if doesn't exist - pass the version we actually want
            self.remote_ops
                .clone_repository(&repo.repo, &repo_name, &repo.version)?;
        } else {
            // Only fetch and reset if repo already exists
            self.remote_ops.fetch_and_reset(&repo_name, &repo.version)?;
        }

        Ok(repo_path)
    }

    /// Copy a single file from source to destination
    fn copy_file(&self, file: &Path, src: &Path, dst: &Path) -> Result<PathBuf> {
        let src_file = src.join(file);
        let dst_file = dst.join(file);
        if let Some(parent) = dst_file.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::copy(&src_file, &dst_file)?;
        Ok(dst_file)
    }

    /// Check sync status of all repositories
    pub fn check_sync_status(&self) -> Result<SyncStatus> {
        if REPOS.is_empty() {
            return Ok(SyncStatus::NotConfigured);
        }

        let mut changed_files = Vec::new();
        for repo in REPOS.iter() {
            let repo_path = self.cache_dir.join(self.extract_repo_name(&repo.repo));
            if repo_path.exists() {
                let src = repo_path.join(repo.source_path.as_ref());
                let dst = Path::new(repo.dest_path.as_ref());
                let files = self.get_files(&src, repo)?;
                let different = self.files_differ(&files, &src, dst);
                // Convert to absolute paths for display
                changed_files.extend(different.iter().map(|f| dst.join(f)));
            }
        }

        if changed_files.is_empty() {
            Ok(SyncStatus::InSync)
        } else {
            Ok(SyncStatus::OutOfSync { changed_files })
        }
    }

    /// Main update function that handles both interactive and force modes
    pub async fn update_all_repos(&mut self, interactive: bool) -> Result<Vec<PathBuf>> {
        let mut all_updated_files = Vec::new();
        let mut all_skipped_files = Vec::new();
        let mut update_all_remaining = false;
        let mut skip_all_remaining = false;

        output::styled!("<chart> Analyzing sync status...");

        // First check if there are any changes at all
        let mut has_any_changes = false;

        for repo in REPOS.iter() {
            tracing::info!("Processing repository: {}", repo.name);

            // Update cache from remote
            let repo_path = self.update_cache(repo)?;

            // Get changed files
            let src = repo_path.join(repo.source_path.as_ref());
            let dst = Path::new(repo.dest_path.as_ref());
            let files = self.get_files(&src, repo)?;
            tracing::debug!("Found {} files in source", files.len());
            let changed_files = self.files_differ(&files, &src, dst);
            tracing::debug!("Found {} changed files", changed_files.len());

            if changed_files.is_empty() {
                tracing::info!("No changes detected for repository: {}", repo.name);
                continue;
            }

            has_any_changes = true;

            // Show repository info
            output::styled!(
                "\n{} Repository: {} ({} files changed)",
                ("🔗", "info_symbol"),
                (repo.name.as_ref(), "property"),
                (changed_files.len().to_string(), "property")
            );

            // Process each changed file
            for (i, file) in changed_files.iter().enumerate() {
                let dst_file = dst.join(file);

                // If we're in "update all" or "skip all" mode, handle accordingly
                if skip_all_remaining {
                    output::styled!(
                        "{} Skipped {}",
                        ("⏭️", "info_symbol"),
                        (dst_file.display().to_string(), "property")
                    );
                    all_skipped_files.push(dst_file.clone());
                    continue;
                }

                if update_all_remaining || !interactive {
                    // In force mode or "update all" mode, just update
                    self.copy_file(file, &src, dst)?;
                    all_updated_files.push(dst_file.clone());
                    if interactive {
                        output::styled!(
                            "{} Updated {}",
                            ("", "success_symbol"),
                            (dst_file.display().to_string(), "property")
                        );
                    }
                    continue;
                }

                // Interactive mode: show diff and ask
                println!();
                output::styled!("{}", ("".repeat(60), "muted"));
                output::styled!(
                    "File {}/{}: {}",
                    ((i + 1).to_string(), "muted"),
                    (changed_files.len().to_string(), "muted"),
                    (dst_file.display().to_string(), "property")
                );

                // Show diff
                self.show_diff(&dst_file, &src.join(file))?;

                // Ask user what to do
                match self.prompt_file_action()? {
                    FileAction::Update => {
                        self.copy_file(file, &src, dst)?;
                        all_updated_files.push(dst_file.clone());
                        output::styled!(
                            "{} Updated {}",
                            ("", "success_symbol"),
                            (dst_file.display().to_string(), "property")
                        );
                    }
                    FileAction::Skip => {
                        output::styled!(
                            "{} Skipped {}",
                            ("⏭️", "info_symbol"),
                            (dst_file.display().to_string(), "property")
                        );
                        all_skipped_files.push(dst_file.clone());
                    }
                    FileAction::UpdateAll => {
                        self.copy_file(file, &src, dst)?;
                        all_updated_files.push(dst_file.clone());
                        output::styled!(
                            "{} Updated {}",
                            ("", "success_symbol"),
                            (dst_file.display().to_string(), "property")
                        );
                        update_all_remaining = true;
                    }
                    FileAction::SkipAll => {
                        output::styled!(
                            "{} Skipped {}",
                            ("⏭️", "info_symbol"),
                            (dst_file.display().to_string(), "property")
                        );
                        all_skipped_files.push(dst_file.clone());
                        skip_all_remaining = true;
                    }
                    FileAction::Quit => {
                        output::styled!("{} Update cancelled by user", ("ℹ️", "info_symbol"));
                        return Ok(all_updated_files);
                    }
                }
            }
        }

        // If no changes at all, show message early
        if !has_any_changes {
            if interactive {
                println!();
                output::styled!("{}", ("".repeat(60), "muted"));
                output::styled!("{} Everything is up to date", ("", "success_symbol"));
            }
            return Ok(all_updated_files);
        }

        // Show summary
        if interactive {
            println!();
            output::styled!("{}", ("".repeat(60), "muted"));

            if all_updated_files.is_empty() && all_skipped_files.is_empty() {
                // Nothing was changed and nothing was skipped = truly up to date
                output::styled!("{} Everything is up to date", ("", "success_symbol"));
            } else if all_updated_files.is_empty() && !all_skipped_files.is_empty() {
                // Nothing updated but files were skipped = files remain out of sync
                output::styled!(
                    "{}  {} files remain out of sync (skipped by user)",
                    ("⚠️", "warning_symbol"),
                    (all_skipped_files.len().to_string(), "property")
                );
            } else if !all_updated_files.is_empty() && all_skipped_files.is_empty() {
                // Files updated and nothing skipped = all changes applied
                output::styled!(
                    "{}  {} files updated",
                    ("", "success_symbol"),
                    (all_updated_files.len().to_string(), "property")
                );
            } else {
                // Both updated and skipped files
                output::styled!(
                    "{}  {} files updated, {} files remain out of sync (skipped)",
                    ("⚠️", "warning_symbol"),
                    (all_updated_files.len().to_string(), "property"),
                    (all_skipped_files.len().to_string(), "property")
                );
            }
        }

        Ok(all_updated_files)
    }

    /// Show diff between source and destination files
    fn show_diff(&self, dest_file: &Path, source_file: &Path) -> Result<()> {
        let dest_content = fs::read_to_string(dest_file).unwrap_or_default();
        let source_content = fs::read_to_string(source_file)?;

        println!();
        output::styled!("{}", ("".repeat(60), "muted"));

        let diff = TextDiff::from_lines(&dest_content, &source_content);

        // Set up syntax highlighting
        let syntax = self
            .syntax_set
            .find_syntax_for_file(dest_file)?
            .unwrap_or_else(|| self.syntax_set.find_syntax_plain_text());
        let theme = &self.theme_set.themes["Solarized (dark)"];

        for group in diff.grouped_ops(3) {
            for op in group {
                for change in diff.iter_changes(&op) {
                    let line_content = change.value().trim_end_matches('\n');
                    let mut highlighter = HighlightLines::new(syntax, theme);

                    match change.tag() {
                        ChangeTag::Delete => {
                            // For deletions, use the old line number
                            let line_number = change.old_index().unwrap_or(0);
                            print!("\x1b[48;2;100;40;40;97m{line_number:>8} -  ");
                            if let Ok(ranges) =
                                highlighter.highlight_line(line_content, &self.syntax_set)
                            {
                                let escaped = as_24_bit_terminal_escaped(&ranges[..], false);
                                println!("{escaped}\x1b[0m");
                            } else {
                                println!("{line_content}\x1b[0m");
                            }
                        }
                        ChangeTag::Insert => {
                            // For insertions, use the new line number
                            let line_number = change.new_index().unwrap_or(0);
                            print!("\x1b[48;2;50;120;50;97m{line_number:>8} +  ");
                            if let Ok(ranges) =
                                highlighter.highlight_line(line_content, &self.syntax_set)
                            {
                                let escaped = as_24_bit_terminal_escaped(&ranges[..], false);
                                println!("{escaped}\x1b[0m");
                            } else {
                                println!("{line_content}\x1b[0m");
                            }
                        }
                        ChangeTag::Equal => {
                            // Context lines - show the new line number (destination)
                            let line_number = change.new_index().unwrap_or(0);
                            print!("{line_number:>8}    ");
                            if let Ok(ranges) =
                                highlighter.highlight_line(line_content, &self.syntax_set)
                            {
                                let escaped = as_24_bit_terminal_escaped(&ranges[..], false);
                                println!("{escaped}");
                            } else {
                                println!("{line_content}");
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Prompt user for action on a file
    fn prompt_file_action(&self) -> Result<FileAction> {
        let options = vec![
            "Yes - Update this file",
            "No - Skip this file",
            "Yes to all remaining files",
            "Skip all remaining files",
            "Quit - Stop processing",
        ];

        println!(); // Add newline before prompt

        // Create a theme without the prompt prefix to avoid the extra "?"
        let theme = ColorfulTheme {
            prompt_prefix: dialoguer::console::style("".to_string()),
            ..Default::default()
        };

        let selection = Select::with_theme(&theme)
            .with_prompt("What would you like to do?")
            .items(&options)
            .default(0)
            .interact()?;

        Ok(match selection {
            0 => FileAction::Update,
            1 => FileAction::Skip,
            2 => FileAction::UpdateAll,
            3 => FileAction::SkipAll,
            4 => FileAction::Quit,
            _ => unreachable!(),
        })
    }

    /// Show all diffs without any interactive prompts (read-only view)
    pub async fn show_all_diffs(&mut self) -> Result<()> {
        output::styled!("<chart> Analyzing sync status...");

        let mut has_any_changes = false;

        for repo in REPOS.iter() {
            tracing::info!("Processing repository: {}", repo.name);

            // Update cache from remote
            let repo_path = self.update_cache(repo)?;

            // Get changed files
            let src = repo_path.join(repo.source_path.as_ref());
            let dst = Path::new(repo.dest_path.as_ref());
            let files = self.get_files(&src, repo)?;
            tracing::debug!("Found {} files in source", files.len());
            let changed_files = self.files_differ(&files, &src, dst);
            tracing::debug!("Found {} changed files", changed_files.len());

            if changed_files.is_empty() {
                tracing::info!("No changes detected for repository: {}", repo.name);
                continue;
            }

            has_any_changes = true;

            // Show repository info
            output::styled!(
                "\n{} Repository: {} ({} files changed)",
                ("🔗", "info_symbol"),
                (repo.name.as_ref(), "property"),
                (changed_files.len().to_string(), "property")
            );

            // Show diff for each changed file (no prompts)
            for (i, file) in changed_files.iter().enumerate() {
                let dst_file = dst.join(file);

                println!();
                output::styled!("{}", ("".repeat(60), "muted"));
                output::styled!(
                    "File {}/{}: {}",
                    ((i + 1).to_string(), "muted"),
                    (changed_files.len().to_string(), "muted"),
                    (dst_file.display().to_string(), "property")
                );

                // Show diff (no prompts)
                self.show_diff(&dst_file, &src.join(file))?;
            }
        }

        // Show summary
        if !has_any_changes {
            println!();
            output::styled!("{}", ("".repeat(60), "muted"));
            output::styled!("{} Everything is up to date", ("", "success_symbol"));
        } else {
            println!();
            output::styled!("{}", ("".repeat(60), "muted"));
            output::styled!(
                "{} Showing diffs for {} repositories",
                ("📝", "info_symbol"),
                (REPOS.len().to_string(), "property")
            );
        }

        Ok(())
    }

    /// Get the cache directory
    pub fn get_cache_dir(&self) -> &PathBuf {
        &self.cache_dir
    }

    /// Extract repository name from URL
    pub fn extract_repo_name(&self, repo_url: &str) -> String {
        repo_url
            .trim_end_matches('/')
            .trim_end_matches(".git")
            .split('/')
            .next_back()
            .unwrap_or("unknown")
            .to_string()
    }
}