Skip to content

Instantly share code, notes, and snippets.

@jmsdnns
Created October 6, 2024 18:21
Show Gist options
  • Save jmsdnns/49d5438267ac7ac8fe1453209263dd5e to your computer and use it in GitHub Desktop.
Save jmsdnns/49d5438267ac7ac8fe1453209263dd5e to your computer and use it in GitHub Desktop.
Creating a file path verifying type with Rust's inquire crate
use inquire::{validator::Validation, CustomType};
use std::path::{self, Path};
fn full_path(p: String) -> String {
path::absolute(p.as_str())
.unwrap()
.canonicalize()
.unwrap()
.to_str()
.unwrap()
.to_string()
}
pub fn ui() {
let filepath = CustomType::<String>::new("Preview file:")
.with_starting_input("preview.mp3")
.with_formatter(&full_path)
.with_error_message("Please type a valid file path")
.with_help_message("Path to file you associate with this version")
.with_validator(|p: &String| {
if Path::new(p.as_str()).exists() {
Ok(Validation::Valid)
} else {
Ok(Validation::Invalid("Invalid file path".into()))
}
})
.prompt();
match filepath {
Ok(fp) => println!("Aww yeah :: {}", full_path(fp)),
Err(_) => println!("We could not process your donation"),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment