first steps

This commit is contained in:
Ward Wouts 2024-11-19 16:17:54 +01:00
parent 9f1e0cbba8
commit a0014cf247
3 changed files with 265 additions and 2 deletions

View file

@ -1,3 +1,101 @@
fn main() {
println!("Hello, world!");
use std::fs;
use std::fs::File;
use std::path::PathBuf;
use std::path::Path;
use std::io::ErrorKind;
use std::io::Write;
use tempfile::NamedTempFile;
const LOCK_FILE: &str = ".mvwrap";
fn read_current_dir() -> Vec<String> {
let paths : Vec<PathBuf> = match fs::read_dir(".") {
Err(e) if e.kind() == ErrorKind::NotFound => Vec::new(),
Err(e) => panic!("Unexpected Error! {:?}", e),
Ok(entries) => entries.filter_map(|e| e.ok())
.map(|e| e.path())
.collect()
};
let mut path_list : Vec<String> = vec![];
for path in paths {
let path_string = path.display().to_string();
if path_string != format!("./{}", LOCK_FILE) {
path_list.push(path_string[2..].to_string());
}
}
path_list.sort();
path_list
}
fn lock_dir() {
if Path::new(LOCK_FILE).is_file() {
panic!("Lock file \"{}\" exists!", LOCK_FILE);
}
let _file = match File::create(LOCK_FILE) {
Ok(file) => file,
Err(_) => panic!("Could not create lock file: {}", LOCK_FILE),
};
}
fn unlock_dir() {
if Path::new(LOCK_FILE).is_file() {
let _result = match fs::remove_file(LOCK_FILE){
Ok(result) => result,
Err(_) => panic!("Could not remove lock file: {}", LOCK_FILE),
};
}
}
fn create_temp_file(paths: Vec<String>) -> String {
let mut tmpfile = match NamedTempFile::new(){
Ok(file) => file,
Err(e) => panic!("Could not create tempfile: {}", e),
};
for path in paths {
let _ = writeln!(tmpfile, "{}", path);
}
let filepath = tmpfile.path().display().to_string();
let _ = match tmpfile.keep(){
Ok(res) => res,
Err(e) => panic!("Can't keep tempfile: {}", e),
};
filepath
}
fn remove_temp_file(tmpfile: String) {
if Path::new(&tmpfile).is_file() {
let _result = match fs::remove_file(&tmpfile){
Ok(result) => result,
Err(_) => panic!("Could not remove tempfile: {}", &tmpfile),
};
}
}
fn main() {
lock_dir();
let paths = read_current_dir();
// create named tempfile and fill with paths
let temp_file = create_temp_file(paths);
// edit tempfile
// read and process tempfile
println!("In file: {}", temp_file);
let contents = fs::read_to_string(temp_file.clone())
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
println!("----- END ----");
remove_temp_file(temp_file);
unlock_dir();
}