Skip to main content

fafind/
lib.rs

1//! Fast parallel filesystem search by filename.
2//!
3//! This crate is the implementation behind the `faf` command line tool.
4//! It walks a directory tree on every core, matches raw filename bytes
5//! against a query, and streams the matching paths to stdout.
6//!
7//! The crate exposes a single entry point, [`run`], which parses the
8//! process arguments and runs the search. The binary is a one-line wrapper
9//! around it.
10//!
11//! ```no_run
12//! fafind::run();
13//! ```
14//!
15//! Unix only. The build fails on other platforms by design.
16
17#![forbid(unsafe_code)]
18
19#[cfg(not(unix))]
20compile_error!("faf only supports Unix");
21
22mod cli;
23mod config;
24mod exclude;
25mod matcher;
26mod util;
27mod walker;
28mod worker;
29
30use clap::Parser;
31use std::fs::File;
32use std::io::{IsTerminal, Write};
33use std::path::PathBuf;
34use std::sync::{Arc, Mutex};
35use std::time::Instant;
36
37use cli::{Cli, ColorMode, rewrite_args};
38use config::{EntryType, MatchMode, WalkConfig};
39use exclude::ExcludeSet;
40use matcher::MatchTarget;
41use walker::walk_parallel;
42use worker::Totals;
43
44/// Parses the process arguments, runs the search, and exits.
45///
46/// Matches go to stdout and a summary line goes to stderr. The process
47/// exits with `0` when at least one match was found, `1` when none was,
48/// and `2` on invalid usage. This function never returns.
49pub fn run() -> ! {
50    let prog = "faf";
51    let args = match rewrite_args(std::env::args_os()) {
52        Ok(args) => args,
53        Err(msg) => {
54            eprintln!("{prog}: {msg}");
55            std::process::exit(2);
56        }
57    };
58    let mut cli = Cli::parse_from(args);
59
60    if cli.substr && cli.precise {
61        eprintln!("error: cannot use -s and -p together");
62        std::process::exit(2);
63    }
64
65    let mode = if cli.substr {
66        MatchMode::Substr
67    } else if cli.precise {
68        MatchMode::Precise
69    } else {
70        MatchMode::Standard
71    };
72
73    // -f / -d are shorthands for --type f / --type d.
74    if cli.file && cli.dir {
75        eprintln!("{prog}: cannot use -f and -d together");
76        std::process::exit(2);
77    }
78    let short_type = if cli.file {
79        Some(EntryType::File)
80    } else if cli.dir {
81        Some(EntryType::Dir)
82    } else {
83        None
84    };
85    let flag_type = match cli.entry_type.as_deref() {
86        None => None,
87        Some("f") => Some(EntryType::File),
88        Some("d") => Some(EntryType::Dir),
89        Some("a") => Some(EntryType::Any),
90        Some(other) => {
91            eprintln!("{prog}: unknown --type '{}' (use f, d, or a)", other);
92            std::process::exit(2);
93        }
94    };
95    let entry_type = match (short_type, flag_type) {
96        (Some(s), Some(f)) if s != f => {
97            let flag = if cli.file { "-f" } else { "-d" };
98            eprintln!(
99                "{prog}: {flag} conflicts with --type {}",
100                cli.entry_type.as_deref().unwrap()
101            );
102            std::process::exit(2);
103        }
104        (Some(t), _) | (_, Some(t)) => t,
105        (None, None) => EntryType::Any,
106    };
107
108    let root = cli.root.take().unwrap_or_else(|| PathBuf::from("/"));
109
110    let color = !cli.null
111        && match cli.color {
112            ColorMode::Never => false,
113            ColorMode::Always => true,
114            ColorMode::Auto => std::io::stdout().is_terminal(),
115        };
116
117    let home = std::env::var_os("HOME");
118    let exclude = ExcludeSet::build(
119        cli.exclude_specs(),
120        &root,
121        home.as_deref(),
122        cli.ignore_case,
123        cli.verbose,
124    );
125    for note in &exclude.notes {
126        eprintln!("{note}");
127    }
128
129    let config = Arc::new(WalkConfig {
130        target: MatchTarget::new(&cli.target, mode, cli.ignore_case),
131        max_depth: cli.max_depth,
132        exclude,
133        entry_type,
134        null_terminate: cli.null,
135        gitignore: cli.gitignore,
136        verbose: cli.verbose,
137        color,
138    });
139
140    let cache_writer = last_cache_path().and_then(CacheWriter::open);
141
142    let start = Instant::now();
143    let totals = Totals::new();
144
145    walk_parallel(
146        &root,
147        Arc::clone(&config),
148        Arc::clone(&totals),
149        cache_writer.clone(),
150    );
151
152    if let Some(writer) = cache_writer {
153        writer.finish();
154    }
155
156    let elapsed = start.elapsed();
157    let secs = elapsed.as_secs_f64();
158    let (scanned, found) = totals.snapshot();
159
160    let files_per_sec = if secs > 0.0 {
161        scanned as f64 / secs
162    } else {
163        f64::INFINITY
164    };
165
166    if !cli.quiet {
167        eprintln!(
168            "{prog}: scanned {} files in {:.2}s ({:.0} files/sec), found {} matches",
169            scanned, secs, files_per_sec, found
170        );
171    }
172
173    std::process::exit(if found > 0 { 0 } else { 1 });
174}
175
176/// Mirrors delfaf's cache path resolution so `faf ...` followed by a bare
177/// `delfaf` finds the same file.
178fn last_cache_path() -> Option<PathBuf> {
179    if let Some(p) = std::env::var_os("FAF_LAST") {
180        return Some(PathBuf::from(p));
181    }
182    if let Some(xdg) = std::env::var_os("XDG_CACHE_HOME") {
183        return Some(PathBuf::from(xdg).join("faf").join("last"));
184    }
185    std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache/faf/last"))
186}
187
188/// Streams matches to a temp file next to the cache path, then atomically
189/// renames it into place once the walk finishes. Workers write in bounded
190/// batches instead of holding every match in memory for the whole walk.
191/// A failed cache write never affects faf's own exit code.
192pub(crate) struct CacheWriter {
193    tmp_path: PathBuf,
194    final_path: PathBuf,
195    file: Mutex<File>,
196}
197
198impl CacheWriter {
199    fn open(final_path: PathBuf) -> Option<Arc<Self>> {
200        if let Some(parent) = final_path.parent() {
201            let _ = std::fs::create_dir_all(parent);
202        }
203        let mut tmp_name = final_path.file_name()?.to_os_string();
204        tmp_name.push(format!(".tmp.{}", std::process::id()));
205        let tmp_path = final_path.with_file_name(tmp_name);
206        let file = File::create(&tmp_path).ok()?;
207        Some(Arc::new(Self {
208            tmp_path,
209            final_path,
210            file: Mutex::new(file),
211        }))
212    }
213
214    pub(crate) fn write(&self, bytes: &[u8]) {
215        if !bytes.is_empty() {
216            let _ = self.file.lock().unwrap().write_all(bytes);
217        }
218    }
219
220    fn finish(self: Arc<Self>) {
221        let Ok(this) = Arc::try_unwrap(self) else {
222            return;
223        };
224        drop(this.file);
225        if std::fs::rename(&this.tmp_path, &this.final_path).is_err() {
226            // Stray leftover directory at the cache path; clear it and retry once.
227            let _ = std::fs::remove_dir_all(&this.final_path);
228            let _ = std::fs::rename(&this.tmp_path, &this.final_path);
229        }
230    }
231}