Skip to main content

mi_simple_io/
lib.rs

1//! # mi-simple-io
2//!
3//! Small synchronous IO utilities for common file and terminal workflows.
4//!
5//! ```
6//! use mi_simple_io::{read_file, remove, write_file};
7//!
8//! # fn main() -> std::io::Result<()> {
9//! let file = std::env::temp_dir().join("mi_simple_io_doctest.txt");
10//! write_file(&file, "hello")?;
11//! assert_eq!(read_file(&file)?, "hello");
12//! remove(&file)?;
13//! # Ok(())
14//! # }
15//! ```
16
17use std::fs::{self, File, OpenOptions};
18use std::io::{self, BufRead, BufReader, Write};
19use std::path::{Path, PathBuf};
20use std::time::{SystemTime, UNIX_EPOCH};
21
22/// Read a UTF-8 text file into a string.
23pub fn read_file<P: AsRef<Path>>(path: P) -> io::Result<String> {
24    fs::read_to_string(path)
25}
26
27/// Read a file into bytes.
28pub fn read_bytes<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
29    fs::read(path)
30}
31
32/// Write text to a file, replacing existing content.
33pub fn write_file<P: AsRef<Path>>(path: P, content: &str) -> io::Result<()> {
34    fs::write(path, content)
35}
36
37/// Append text to a file, creating it when missing.
38pub fn append_file<P: AsRef<Path>>(path: P, content: &str) -> io::Result<()> {
39    let mut file = OpenOptions::new().create(true).append(true).open(path)?;
40    file.write_all(content.as_bytes())
41}
42
43/// Write text when the file is missing, otherwise append it.
44pub fn write_or_append<P: AsRef<Path>>(path: P, content: &str) -> io::Result<()> {
45    if path.as_ref().exists() {
46        append_file(path, content)
47    } else {
48        write_file(path, content)
49    }
50}
51
52/// Return file size in bytes.
53pub fn file_size<P: AsRef<Path>>(path: P) -> io::Result<u64> {
54    Ok(fs::metadata(path)?.len())
55}
56
57/// Return whether a path exists.
58pub fn exists<P: AsRef<Path>>(path: P) -> bool {
59    path.as_ref().exists()
60}
61
62/// Return whether a path is a regular file.
63pub fn is_file<P: AsRef<Path>>(path: P) -> bool {
64    path.as_ref().is_file()
65}
66
67/// Return whether a path is a directory.
68pub fn is_dir<P: AsRef<Path>>(path: P) -> bool {
69    path.as_ref().is_dir()
70}
71
72/// Create a directory and any missing parents.
73pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
74    fs::create_dir_all(path)
75}
76
77/// Remove a file or directory tree.
78pub fn remove<P: AsRef<Path>>(path: P) -> io::Result<()> {
79    let path = path.as_ref();
80    if path.is_dir() {
81        fs::remove_dir_all(path)
82    } else {
83        fs::remove_file(path)
84    }
85}
86
87/// Remove all directory contents while keeping the directory itself.
88pub fn clear_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
89    for entry in fs::read_dir(path)? {
90        let entry = entry?;
91        remove(entry.path())?;
92    }
93    Ok(())
94}
95
96/// Copy a file and return the number of bytes copied.
97pub fn copy_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
98    fs::copy(from, to)
99}
100
101/// Move or rename a file or directory.
102pub fn move_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
103    fs::rename(from, to)
104}
105
106/// Return the file stem as UTF-8 lossy text, or an empty string.
107pub fn file_stem<P: AsRef<Path>>(path: P) -> String {
108    path.as_ref()
109        .file_stem()
110        .unwrap_or_default()
111        .to_string_lossy()
112        .to_string()
113}
114
115/// Return the lowercase file extension as UTF-8 lossy text, or an empty string.
116pub fn file_extension<P: AsRef<Path>>(path: P) -> String {
117    path.as_ref()
118        .extension()
119        .unwrap_or_default()
120        .to_string_lossy()
121        .to_lowercase()
122}
123
124/// Return the current working directory.
125pub fn current_dir() -> io::Result<PathBuf> {
126    std::env::current_dir()
127}
128
129/// Return the system temporary directory.
130pub fn temp_dir() -> PathBuf {
131    std::env::temp_dir()
132}
133
134/// Read a file as a line iterator, preserving line read errors.
135pub fn read_lines<P: AsRef<Path>>(path: P) -> io::Result<impl Iterator<Item = io::Result<String>>> {
136    let file = File::open(path)?;
137    Ok(BufReader::new(file).lines())
138}
139
140/// Read all lines from a file.
141pub fn read_all_lines<P: AsRef<Path>>(path: P) -> io::Result<Vec<String>> {
142    read_lines(path)?.collect()
143}
144
145/// Read the first `n` lines from a file.
146pub fn read_first_lines<P: AsRef<Path>>(path: P, n: usize) -> io::Result<Vec<String>> {
147    read_lines(path)?.take(n).collect()
148}
149
150/// Read the last `n` lines from a file.
151pub fn read_last_lines<P: AsRef<Path>>(path: P, n: usize) -> io::Result<Vec<String>> {
152    let lines = read_all_lines(path)?;
153    let start = lines.len().saturating_sub(n);
154    Ok(lines[start..].to_vec())
155}
156
157/// Write text via a sibling temporary file before replacing the destination.
158pub fn safe_write<P: AsRef<Path>>(path: P, content: &str) -> io::Result<()> {
159    let path = path.as_ref();
160    let temp_path = path.with_extension("tmp");
161
162    if let Err(error) = write_file(&temp_path, content) {
163        let _ = fs::remove_file(&temp_path);
164        return Err(error);
165    }
166
167    if let Err(error) = fs::rename(&temp_path, path) {
168        let _ = fs::remove_file(&temp_path);
169        return Err(error);
170    }
171
172    Ok(())
173}
174
175/// Basic text file statistics.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct FileStats {
178    pub size: u64,
179    pub lines: usize,
180    pub words: usize,
181    pub chars: usize,
182}
183
184/// Read a text file and return basic statistics.
185pub fn file_stats<P: AsRef<Path>>(path: P) -> io::Result<FileStats> {
186    let content = read_file(path)?;
187    Ok(FileStats {
188        size: content.len() as u64,
189        lines: content.lines().count(),
190        words: content.split_whitespace().count(),
191        chars: content.chars().count(),
192    })
193}
194
195/// Temporary file removed when dropped.
196#[derive(Debug)]
197pub struct TempFile {
198    path: PathBuf,
199}
200
201impl TempFile {
202    /// Create a new empty temporary file with a prefix.
203    pub fn new(prefix: &str) -> io::Result<Self> {
204        for attempt in 0..100 {
205            let unique = SystemTime::now()
206                .duration_since(UNIX_EPOCH)
207                .expect("system time before unix epoch")
208                .as_nanos();
209            let path = temp_dir().join(format!(
210                "{}_{}_{}_{}",
211                prefix,
212                std::process::id(),
213                unique,
214                attempt
215            ));
216
217            match OpenOptions::new().write(true).create_new(true).open(&path) {
218                Ok(_) => return Ok(Self { path }),
219                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
220                Err(error) => return Err(error),
221            }
222        }
223
224        Err(io::Error::new(
225            io::ErrorKind::AlreadyExists,
226            "could not create a unique temporary file",
227        ))
228    }
229
230    /// Create a temporary file with content.
231    pub fn with_content(prefix: &str, content: &str) -> io::Result<Self> {
232        let temp = Self::new(prefix)?;
233        write_file(&temp.path, content)?;
234        Ok(temp)
235    }
236
237    /// Return the temporary file path.
238    pub fn path(&self) -> &Path {
239        &self.path
240    }
241
242    /// Read the temporary file as text.
243    pub fn read(&self) -> io::Result<String> {
244        read_file(&self.path)
245    }
246}
247
248impl Drop for TempFile {
249    fn drop(&mut self) {
250        let _ = fs::remove_file(&self.path);
251    }
252}
253
254/// Read a trimmed line from standard input after printing a prompt.
255pub fn read_input(prompt: &str) -> io::Result<String> {
256    print!("{prompt}");
257    io::stdout().flush()?;
258
259    let mut input = String::new();
260    io::stdin().read_line(&mut input)?;
261    Ok(input.trim().to_string())
262}
263
264/// Parse confirmation text using a default for empty or unknown input.
265pub fn parse_confirmation(input: &str, default: bool) -> bool {
266    match input.trim().to_lowercase().as_str() {
267        "y" | "yes" => true,
268        "n" | "no" => false,
269        _ => default,
270    }
271}
272
273/// Ask a yes/no question and return the selected answer.
274pub fn confirm(prompt: &str, default: bool) -> bool {
275    let default_text = if default { "Y/n" } else { "y/N" };
276    let input = read_input(&format!("{prompt} [{default_text}]: ")).unwrap_or_default();
277    parse_confirmation(&input, default)
278}
279
280/// Read a password from the terminal without echoing input.
281#[cfg(feature = "password")]
282pub fn read_password(prompt: &str) -> io::Result<String> {
283    print!("{prompt}");
284    io::stdout().flush()?;
285    rpassword::read_password()
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use std::fs;
292    use std::io;
293    use std::path::PathBuf;
294    use std::time::{SystemTime, UNIX_EPOCH};
295
296    fn test_dir(name: &str) -> io::Result<PathBuf> {
297        let unique = SystemTime::now()
298            .duration_since(UNIX_EPOCH)
299            .expect("system time before unix epoch")
300            .as_nanos();
301        let path = std::env::temp_dir().join(format!(
302            "mi_simple_io_{}_{}_{}",
303            name,
304            std::process::id(),
305            unique
306        ));
307        fs::create_dir_all(&path)?;
308        Ok(path)
309    }
310
311    #[test]
312    fn write_read_append_and_write_or_append_text() -> io::Result<()> {
313        let dir = test_dir("text")?;
314        let file = dir.join("notes.txt");
315
316        write_file(&file, "hello")?;
317        assert_eq!(read_file(&file)?, "hello");
318
319        append_file(&file, " world")?;
320        assert_eq!(read_file(&file)?, "hello world");
321
322        let new_file = dir.join("new.txt");
323        write_or_append(&new_file, "first")?;
324        write_or_append(&new_file, " second")?;
325        assert_eq!(read_file(&new_file)?, "first second");
326
327        fs::remove_dir_all(dir)?;
328        Ok(())
329    }
330
331    #[test]
332    fn reads_bytes_and_reports_file_size() -> io::Result<()> {
333        let dir = test_dir("bytes")?;
334        let file = dir.join("data.bin");
335
336        fs::write(&file, [0_u8, 1, 2, 3])?;
337
338        assert_eq!(read_bytes(&file)?, vec![0, 1, 2, 3]);
339        assert_eq!(file_size(&file)?, 4);
340
341        fs::remove_dir_all(dir)?;
342        Ok(())
343    }
344
345    #[test]
346    fn checks_file_and_directory_state() -> io::Result<()> {
347        let dir = test_dir("state")?;
348        let file = dir.join("state.txt");
349
350        assert!(exists(&dir));
351        assert!(is_dir(&dir));
352        assert!(!is_file(&dir));
353
354        write_file(&file, "state")?;
355        assert!(exists(&file));
356        assert!(is_file(&file));
357        assert!(!is_dir(&file));
358
359        fs::remove_dir_all(dir)?;
360        Ok(())
361    }
362
363    #[test]
364    fn creates_clears_and_removes_directories() -> io::Result<()> {
365        let dir = test_dir("dirs")?;
366        let nested = dir.join("a/b");
367        let file = nested.join("file.txt");
368
369        create_dir(&nested)?;
370        write_file(&file, "content")?;
371        assert!(is_file(&file));
372
373        clear_dir(dir.join("a"))?;
374        assert!(is_dir(dir.join("a")));
375        assert!(!exists(&file));
376
377        remove(dir.join("a"))?;
378        assert!(!exists(dir.join("a")));
379
380        fs::remove_dir_all(dir)?;
381        Ok(())
382    }
383
384    #[test]
385    fn copies_moves_and_extracts_path_parts() -> io::Result<()> {
386        let dir = test_dir("copy_move")?;
387        let source = dir.join("Report.TXT");
388        let copied = dir.join("copied.txt");
389        let moved = dir.join("moved.md");
390
391        write_file(&source, "copy me")?;
392        assert_eq!(copy_file(&source, &copied)?, 7);
393        assert_eq!(read_file(&copied)?, "copy me");
394
395        move_file(&copied, &moved)?;
396        assert!(!exists(&copied));
397        assert_eq!(read_file(&moved)?, "copy me");
398
399        assert_eq!(file_stem(&source), "Report");
400        assert_eq!(file_extension(&source), "txt");
401        assert!(current_dir()?.is_dir());
402        assert!(temp_dir().is_dir());
403
404        fs::remove_dir_all(dir)?;
405        Ok(())
406    }
407
408    #[test]
409    fn reads_lines_and_line_ranges() -> io::Result<()> {
410        let dir = test_dir("lines")?;
411        let file = dir.join("lines.txt");
412        write_file(&file, "one\ntwo\nthree\nfour\n")?;
413
414        let lines = read_all_lines(&file)?;
415        assert_eq!(lines, vec!["one", "two", "three", "four"]);
416
417        let streamed = read_lines(&file)?.collect::<io::Result<Vec<_>>>()?;
418        assert_eq!(streamed, vec!["one", "two", "three", "four"]);
419
420        assert_eq!(read_first_lines(&file, 2)?, vec!["one", "two"]);
421        assert_eq!(read_last_lines(&file, 2)?, vec!["three", "four"]);
422        assert_eq!(
423            read_last_lines(&file, 10)?,
424            vec!["one", "two", "three", "four"]
425        );
426
427        fs::remove_dir_all(dir)?;
428        Ok(())
429    }
430
431    #[test]
432    fn safely_writes_and_reports_file_stats() -> io::Result<()> {
433        let dir = test_dir("safe_stats")?;
434        let file = dir.join("stats.txt");
435
436        safe_write(&file, "hello rust\nsecond line")?;
437        assert_eq!(read_file(&file)?, "hello rust\nsecond line");
438        assert!(!exists(file.with_extension("tmp")));
439
440        let stats = file_stats(&file)?;
441        assert_eq!(stats.size, 22);
442        assert_eq!(stats.lines, 2);
443        assert_eq!(stats.words, 4);
444        assert_eq!(stats.chars, 22);
445
446        fs::remove_dir_all(dir)?;
447        Ok(())
448    }
449
450    #[test]
451    fn temp_file_writes_reads_and_removes_on_drop() -> io::Result<()> {
452        let path;
453        {
454            let temp = TempFile::with_content("unit", "temporary data")?;
455            path = temp.path().to_path_buf();
456            assert!(is_file(&path));
457            assert_eq!(temp.read()?, "temporary data");
458        }
459        assert!(!exists(path));
460        Ok(())
461    }
462
463    #[test]
464    fn confirm_defaults_match_empty_or_unknown_answers() {
465        assert_eq!(parse_confirmation("", true), true);
466        assert_eq!(parse_confirmation("", false), false);
467        assert_eq!(parse_confirmation("maybe", true), true);
468        assert_eq!(parse_confirmation("maybe", false), false);
469        assert_eq!(parse_confirmation("yes", false), true);
470        assert_eq!(parse_confirmation("Y", false), true);
471        assert_eq!(parse_confirmation("no", true), false);
472        assert_eq!(parse_confirmation("N", true), false);
473    }
474}