Skip to main content

asimeow/
explorer.rs

1use crate::config::Rule;
2use anyhow::Result;
3use glob::Pattern;
4use std::collections::{HashMap, HashSet};
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8use std::string::ToString;
9use std::sync::{Arc, OnceLock, RwLock};
10use std::thread;
11
12pub struct State {
13    pub folder_queue: RwLock<Vec<PathBuf>>,
14    pub exclusion_found: RwLock<i32>,
15    pub processed_paths: RwLock<i32>,
16    pub active_tasks: RwLock<usize>,
17    pub processing_complete: RwLock<bool>,
18    pub newly_excluded: RwLock<i32>,
19    // Tracks exclusion paths we already attempted this run to avoid repeated tmutil calls
20    pub seen_exclusion_paths: RwLock<HashSet<String>>,
21    // Optional memoization for exclusion status checks (path -> is_excluded)
22    pub exclusion_status_cache: RwLock<HashMap<String, bool>>,
23}
24
25static THIS_FOLDER: OnceLock<String> = OnceLock::new();
26static PARENT_FOLDER: OnceLock<String> = OnceLock::new();
27
28impl Default for State {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34impl State {
35    pub fn new() -> Self {
36        State {
37            folder_queue: RwLock::new(Vec::new()),
38            exclusion_found: RwLock::new(0),
39            processed_paths: RwLock::new(0),
40            active_tasks: RwLock::new(0),
41            processing_complete: RwLock::new(false),
42            newly_excluded: RwLock::new(0),
43            seen_exclusion_paths: RwLock::new(HashSet::new()),
44            exclusion_status_cache: RwLock::new(HashMap::new()),
45        }
46    }
47}
48
49/// Checks if a path is excluded from Time Machine backups on macOS.
50/// Returns true if the path is excluded, false otherwise.
51pub fn is_excluded_from_timemachine(path: &Path) -> bool {
52    let check_output = Command::new("tmutil")
53        .args(["isexcluded", path.to_str().unwrap_or_default()])
54        .output();
55
56    match check_output {
57        Ok(output) => {
58            let output_str = String::from_utf8_lossy(&output.stdout);
59            output_str.contains("[Excluded]")
60        }
61        Err(_) => false, // Failed to run tmutil
62    }
63}
64
65/// Excludes a path from Time Machine backups on macOS.
66/// Returns true if the path was successfully excluded or false if it was already excluded.
67pub fn exclude_from_timemachine(path: &Path) -> bool {
68    // Check if the path is already excluded
69    if is_excluded_from_timemachine(path) {
70        return false; // Already excluded
71    }
72
73    // Exclude the path
74    let exclude_result = Command::new("tmutil")
75        .args(["addexclusion", path.to_str().unwrap_or_default()])
76        .status();
77
78    match exclude_result {
79        Ok(status) => status.success(),
80        Err(_) => false,
81    }
82}
83
84/// Removes a path from Time Machine exclusions on macOS.
85/// Returns true if the path was successfully included or false if it was already included.
86pub fn include_in_timemachine(path: &Path) -> bool {
87    // Check if the path is already included (not excluded)
88    if !is_excluded_from_timemachine(path) {
89        return false; // Already included
90    }
91
92    // Include the path (remove exclusion)
93    let include_result = Command::new("tmutil")
94        .args(["removeexclusion", path.to_str().unwrap_or_default()])
95        .status();
96
97    match include_result {
98        Ok(status) => status.success(),
99        Err(_) => false,
100    }
101}
102
103fn process_exclusion(path: &Path, rule: &Rule, state: &Arc<State>, verbose: bool) {
104    // Print in the requested format: /path/to/excluded/dir - rule-name
105    for exclusion in &rule.exclusions {
106        let exclusion_path = path.join(exclusion);
107        if exclusion_path.exists() {
108            // Skip if we already processed this exact exclusion path in this run
109            let exclusion_str = exclusion_path.display().to_string();
110            {
111                let seen = state.seen_exclusion_paths.read().unwrap();
112                if seen.contains(&exclusion_str) {
113                    continue;
114                }
115            }
116
117            // Try to exclude from Time Machine
118            let excluded = exclude_from_timemachine(&exclusion_path);
119
120            if excluded {
121                // Green tick for newly excluded paths
122                println!("✅ {} - {}", exclusion_path.display(), rule.name);
123
124                // Increment the newly_excluded counter
125                let mut newly_excluded = state.newly_excluded.write().unwrap();
126                *newly_excluded += 1;
127
128                if verbose {
129                    println!(
130                        "  → Excluded from Time Machine: {}",
131                        exclusion_path.display()
132                    );
133                }
134            } else {
135                // Yellow circle for already excluded paths
136                println!("🟡 {} - {}", exclusion_path.display(), rule.name);
137
138                if verbose {
139                    println!("  → Already excluded from Time Machine");
140                }
141            }
142
143            // Increment the exclusion_found counter
144            let mut counter = state.exclusion_found.write().unwrap();
145            *counter += 1;
146
147            // Mark as seen to avoid repeated tmutil calls on the same path
148            let mut seen = state.seen_exclusion_paths.write().unwrap();
149            seen.insert(exclusion_str);
150        }
151    }
152}
153
154pub fn process_path(
155    path: &Path,
156    state: Arc<State>,
157    rules: &[Rule],
158    verbose: bool,
159    ignore_patterns: &[String],
160) -> Result<()> {
161    // Skip if path doesn't exist or is not a directory
162    if !path.exists() {
163        if verbose {
164            eprintln!("Error: Path does not exist: {}", path.display());
165        }
166        return Ok(());
167    }
168
169    if !path.is_dir() {
170        if verbose {
171            eprintln!("Error: Not a directory: {}", path.display());
172        }
173        return Ok(());
174    }
175
176    // Check if this directory should be ignored based on its name
177    if let Some(dir_name) = path.file_name() {
178        let dir_name_str = dir_name.to_string_lossy().to_string();
179        for pattern in ignore_patterns {
180            // Use glob pattern matching for ignore patterns
181            let glob_pattern = match Pattern::new(pattern) {
182                Ok(p) => p,
183                Err(_) => {
184                    if verbose {
185                        eprintln!(
186                            "Warning: Invalid ignore pattern '{}', using literal match",
187                            pattern
188                        );
189                    }
190                    Pattern::new(&glob::Pattern::escape(pattern)).unwrap()
191                }
192            };
193
194            if glob_pattern.matches(&dir_name_str) {
195                if verbose {
196                    println!("Skipping ignored directory: {}", path.display());
197                }
198                return Ok(());
199            }
200        }
201    }
202
203    // Increment the processed_paths counter
204    {
205        let mut counter = state.processed_paths.write().unwrap();
206        *counter += 1;
207    }
208
209    if verbose {
210        println!("Processing path: {}", path.display());
211    }
212
213    // Read all entries once
214    let read_dir_iter = match fs::read_dir(path) {
215        Ok(entries) => entries,
216        Err(e) => {
217            eprintln!("Failed to read directory {}: {}", path.display(), e);
218            return Ok(());
219        }
220    };
221
222    // Collect entries into memory to ensure deterministic two-phase processing
223    let mut entries: Vec<fs::DirEntry> = Vec::new();
224    for entry_result in read_dir_iter {
225        match entry_result {
226            Ok(entry) => entries.push(entry),
227            Err(err) => {
228                if verbose {
229                    eprintln!("Error accessing entry: {}", err);
230                }
231            }
232        }
233    }
234
235    // Phase 1: evaluate rule matches and compute directories to ignore
236    let mut directory_to_ignore: Vec<String> = Vec::new();
237    for entry in &entries {
238        let entry_path = entry.path();
239        let file_name_lc = entry_path
240            .file_name()
241            .unwrap_or_default()
242            .to_string_lossy()
243            .to_lowercase();
244
245        for rule in rules {
246            let pattern = match Pattern::new(&rule.file_match.to_lowercase()) {
247                Ok(p) => p,
248                Err(_) => {
249                    if verbose {
250                        eprintln!(
251                            "Warning: Invalid pattern '{}' in rule '{}', using literal match",
252                            rule.file_match, rule.name
253                        );
254                    }
255                    Pattern::new(&glob::Pattern::escape(&rule.file_match.to_lowercase())).unwrap()
256                }
257            };
258
259            if pattern.matches(&file_name_lc) {
260                if verbose {
261                    println!(
262                        "Found match for rule '{}' at: {}",
263                        rule.name,
264                        entry_path.display()
265                    );
266                }
267                process_exclusion(path, rule, &state, verbose);
268
269                // If special entries are present, do not descend further from current folder
270                if rule
271                    .exclusions
272                    .contains(THIS_FOLDER.get_or_init(|| ".".to_string()))
273                    || rule
274                        .exclusions
275                        .contains(PARENT_FOLDER.get_or_init(|| "..".to_string()))
276                {
277                    return Ok(());
278                }
279
280                for exclusion in &rule.exclusions {
281                    directory_to_ignore.push(exclusion.clone());
282                }
283
284                break; // no need to check other rules for this same entry
285            }
286        }
287    }
288
289    // Phase 2: enqueue subdirectories excluding those we just excluded
290    if !entries.is_empty() {
291        let mut queue = state.folder_queue.write().unwrap();
292        for entry in entries {
293            let entry_path = entry.path();
294            if entry_path.is_dir() {
295                let name = entry_path
296                    .file_name()
297                    .unwrap_or_default()
298                    .to_string_lossy()
299                    .to_string();
300                if directory_to_ignore.iter().any(|n| n == &name) {
301                    continue;
302                }
303
304                queue.push(entry_path);
305            }
306        }
307    }
308
309    Ok(())
310}
311
312pub fn run_workers(
313    state: Arc<State>,
314    rules: Arc<Vec<Rule>>,
315    thread_count: usize,
316    verbose: bool,
317    ignore_patterns: Arc<Vec<String>>,
318) -> Result<()> {
319    // Spawn worker threads to process the queue
320    for _ in 0..thread_count {
321        let state_clone = Arc::clone(&state);
322        let rules_clone = Arc::clone(&rules);
323        let ignore_patterns_clone = Arc::clone(&ignore_patterns);
324        let verbose_clone = verbose;
325
326        thread::spawn(move || {
327            loop {
328                // Check if processing is complete
329                if *state_clone.processing_complete.read().unwrap() {
330                    break;
331                }
332
333                // Try to get a path from the queue
334                let next_path_option = {
335                    let mut queue = state_clone.folder_queue.write().unwrap();
336                    if !queue.is_empty() {
337                        // Increment active tasks counter
338                        let mut active = state_clone.active_tasks.write().unwrap();
339                        *active += 1;
340
341                        Some(queue.remove(0))
342                    } else {
343                        None
344                    }
345                };
346
347                if let Some(next_path) = next_path_option {
348                    // Process the path
349                    if let Err(e) = process_path(
350                        &next_path,
351                        Arc::clone(&state_clone),
352                        &rules_clone,
353                        verbose_clone,
354                        &ignore_patterns_clone,
355                    ) {
356                        eprintln!("Error processing path {}: {}", next_path.display(), e);
357                    }
358
359                    // Decrement active tasks counter
360                    let mut active = state_clone.active_tasks.write().unwrap();
361                    *active -= 1;
362                } else {
363                    // No paths in queue, check if we're done
364                    let active_count = *state_clone.active_tasks.read().unwrap();
365                    let queue_empty = state_clone.folder_queue.read().unwrap().is_empty();
366
367                    if queue_empty && active_count == 0 {
368                        // No more work to do, mark processing as complete
369                        let mut complete = state_clone.processing_complete.write().unwrap();
370                        *complete = true;
371                        break;
372                    }
373
374                    // No work available right now, wait a bit
375                    thread::sleep(std::time::Duration::from_millis(10));
376                }
377            }
378        });
379    }
380
381    // Wait for all processing to complete
382    loop {
383        let processing_done = *state.processing_complete.read().unwrap();
384        if processing_done {
385            break;
386        }
387        thread::sleep(std::time::Duration::from_millis(100));
388    }
389
390    Ok(())
391}
392
393/// Lists the exclusion status of files and directories in a given path
394pub fn list_exclusions(path_str: Option<&str>) -> Result<()> {
395    // If no path is provided, use the current directory
396    let path = if let Some(p) = path_str {
397        crate::config::expand_tilde(p)?
398    } else {
399        std::env::current_dir()?
400    };
401
402    if !path.exists() {
403        return Err(anyhow::anyhow!("Path does not exist: {}", path.display()));
404    }
405
406    // Check if we're listing a directory with all contents or just a single file/directory
407    let is_directory_listing = path.is_dir() && path_str.is_none_or(|p| p.ends_with('/'));
408
409    if is_directory_listing {
410        // List all entries in the directory
411        println!("Listing contents of: {}", path.display());
412        println!("------------------------------------");
413
414        let entries = match fs::read_dir(&path) {
415            Ok(entries) => entries,
416            Err(e) => return Err(anyhow::anyhow!("Failed to read directory: {}", e)),
417        };
418
419        let mut has_entries = false;
420        for entry_result in entries {
421            has_entries = true;
422            let entry = match entry_result {
423                Ok(entry) => entry,
424                Err(e) => {
425                    eprintln!("Error accessing entry: {}", e);
426                    continue;
427                }
428            };
429
430            let entry_path = entry.path();
431            let is_excluded = is_excluded_from_timemachine(&entry_path);
432
433            // Format the output with appropriate indicators
434            let indicator = if is_excluded { "🟡" } else { "  " };
435            let type_indicator = if entry_path.is_dir() { "/" } else { "" };
436
437            println!(
438                "{} {}{}",
439                indicator,
440                entry_path.file_name().unwrap_or_default().to_string_lossy(),
441                type_indicator
442            );
443        }
444
445        if !has_entries {
446            println!("  (empty directory)");
447        }
448
449        // Add a legend
450        println!("\nLegend:");
451        println!("🟡 - Excluded from Time Machine");
452        println!("  - Included in Time Machine");
453        println!("/ - Directory");
454    } else {
455        // Just check the status of the specific path but format it like the directory listing
456        let item_type = if path.is_dir() { "directory" } else { "file" };
457        println!("Status of {}: {}", item_type, path.display());
458        println!("------------------------------------");
459
460        let is_excluded = is_excluded_from_timemachine(&path);
461        let indicator = if is_excluded { "🟡" } else { "  " };
462        let type_indicator = if path.is_dir() { "/" } else { "" };
463
464        // Use the filename if available, otherwise use the full path
465        let display_name = path
466            .file_name()
467            .map(|name| name.to_string_lossy().to_string())
468            .unwrap_or_else(|| path.display().to_string());
469
470        println!("{} {}{}", indicator, display_name, type_indicator);
471
472        // Add a legend
473        println!("\nLegend:");
474        println!("🟡 - Excluded from Time Machine");
475        println!("  - Included in Time Machine");
476        if path.is_dir() {
477            println!("/ - Directory");
478        }
479    }
480
481    Ok(())
482}
483
484/// Explicitly excludes a single file or folder from Time Machine backups
485pub fn exclude_path(path_str: &str, verbose: bool) -> Result<()> {
486    // Expand the path if it contains a tilde
487    let path = crate::config::expand_tilde(path_str)?;
488
489    if !path.exists() {
490        return Err(anyhow::anyhow!("Path does not exist: {}", path.display()));
491    }
492
493    let item_type = if path.is_dir() { "directory" } else { "file" };
494
495    if verbose {
496        println!(
497            "Excluding {} from Time Machine: {}",
498            item_type,
499            path.display()
500        );
501    }
502
503    let excluded = exclude_from_timemachine(&path);
504
505    if excluded {
506        println!("✅ Successfully excluded: {}", path.display());
507    } else {
508        println!("🟡 Already excluded: {}", path.display());
509    }
510
511    Ok(())
512}
513
514/// Explicitly includes a single file or folder in Time Machine backups (removes exclusion)
515pub fn include_path(path_str: &str, verbose: bool) -> Result<()> {
516    // Expand the path if it contains a tilde
517    let path = crate::config::expand_tilde(path_str)?;
518
519    if !path.exists() {
520        return Err(anyhow::anyhow!("Path does not exist: {}", path.display()));
521    }
522
523    let item_type = if path.is_dir() { "directory" } else { "file" };
524
525    if verbose {
526        println!(
527            "Including {} in Time Machine: {}",
528            item_type,
529            path.display()
530        );
531    }
532
533    let included = include_in_timemachine(&path);
534
535    if included {
536        println!("✅ Successfully included: {}", path.display());
537    } else {
538        println!("  Already included: {}", path.display());
539    }
540
541    Ok(())
542}
543
544pub fn run_explorer(
545    config: crate::config::Config,
546    thread_count: usize,
547    verbose: bool,
548) -> Result<()> {
549    let _ = run_explorer_with_stats(config, thread_count, verbose)?;
550    Ok(())
551}
552
553pub struct ExplorerStats {
554    pub processed_paths: i32,
555    pub exclusions_found: i32,
556    pub newly_excluded: i32,
557}
558
559/// Same as run_explorer but returns stats for testing/inspection
560pub fn run_explorer_with_stats(
561    config: crate::config::Config,
562    thread_count: usize,
563    verbose: bool,
564) -> Result<ExplorerStats> {
565    // Create shared state
566    let state = Arc::new(State::new());
567
568    // Process each root path and add to initial queue
569    for root in &config.roots {
570        let expanded_path = crate::config::expand_tilde(&root.path)?;
571
572        // Add root paths to the queue
573        let mut queue = state.folder_queue.write().unwrap();
574        queue.push(expanded_path);
575    }
576
577    // Create Arc-wrapped rules and ignore patterns for sharing
578    let rules = Arc::new(config.rules);
579    let ignore_patterns = Arc::new(config.ignore);
580
581    // Run worker threads
582    run_workers(state.clone(), rules, thread_count, verbose, ignore_patterns)?;
583
584    // Gather stats
585    let exclusions_count = *state.exclusion_found.read().unwrap();
586    let processed_count = *state.processed_paths.read().unwrap();
587    let newly_excluded_count = *state.newly_excluded.read().unwrap();
588
589    if verbose || exclusions_count > 0 {
590        println!("\nTotal paths processed: {}", processed_count);
591        println!("Total exclusions found: {}", exclusions_count);
592        println!("Newly excluded from Time Machine: {}", newly_excluded_count);
593    }
594
595    Ok(ExplorerStats {
596        processed_paths: processed_count,
597        exclusions_found: exclusions_count,
598        newly_excluded: newly_excluded_count,
599    })
600}