| 1 |
use std::{ |
| 2 |
fs::{self, File}, |
| 3 |
io::{BufWriter, Result, Write}, |
| 4 |
path::Path, |
| 5 |
}; |
| 6 |
|
| 7 |
use crate::writer::untabber::Untabber; |
| 8 |
|
| 9 |
pub fn save_to_file<P, F>(path: P, make_backup: bool, mut closure: F) |
| 10 |
where |
| 11 |
P: AsRef<Path>, |
| 12 |
F: FnMut(&mut dyn Write) -> Result<()>, |
| 13 |
{ |
| 14 |
let path = path.as_ref(); |
| 15 |
if let Some(parent) = path.parent() { |
| 16 |
let _ = fs::create_dir_all(parent); |
| 17 |
} |
| 18 |
|
| 19 |
if make_backup { |
| 20 |
let _backuped = create_backup(path) |
| 21 |
.unwrap_or_else(|why| panic!("couldn't create backup for {path:?}: {why:?}")); |
| 22 |
} |
| 23 |
let file = File::create(path).unwrap_or_else(|why| panic!("couldn't create {path:?}: {why}")); |
| 24 |
let writer = BufWriter::new(file); |
| 25 |
let mut untabber = Untabber::new(Box::new(writer)); |
| 26 |
closure(&mut untabber).unwrap_or_else(|why| panic!("couldn't write to {path:?}: {why:?}")); |
| 27 |
} |
| 28 |
|
| 29 |
/// Create .bak file |
| 30 |
pub fn create_backup<P: AsRef<Path>>(path: P) -> Result<bool> { |
| 31 |
if fs::metadata(&path).is_err() { |
| 32 |
return Ok(false); |
| 33 |
} |
| 34 |
let new_path = path.as_ref().with_extension("bak"); |
| 35 |
fs::rename(path, new_path).map(|_| true) |
| 36 |
} |