winure/path-convert/src/main.rs
2024-06-05 10:04:44 -04:00

70 lines
1.5 KiB
Rust

use std::path::Path;
use pico_args::Arguments;
const DRIVE: &str = "/mnt/c/";
const HELP: [&str;2] = [ "-h", "--help" ];
const QUOTED: [&str;2] = [ "-q", "--quotes" ];
pub fn main() {
let mut args = Arguments::from_env();
// handle help flag
if args.contains(HELP) {
help_text();
return;
}
// handle quote flag
let quotes: &str =
if args.contains(QUOTED) {
if args.contains(QUOTED) { "\"" } // -qq -> "..." (output with double quotes)
else { "'" } // -q -> '...' (output with single quotes)
} else { "" }; // _ -> ... (output with no quotes)
loop {
let next = args.subcommand().unwrap();
if let Some(arg) = next {
let mut output: String;
// canonicalize; windows doesn't recognize symlinks
let path = Path::new(&arg).canonicalize();
if let Ok(target) = path {
output = target.to_string_lossy().to_string();
} else {
output = arg;
}
// simple C-drive substitution
if output.starts_with(DRIVE) {
output = output.replace(DRIVE, "C:\\");
}
// switch out separators
output = output.replace("/", "\\");
// emit to stdout
println!("{quotes}{output}{quotes}");
} else {
break;
}
}
}
pub fn help_text() {
println!("path-convert v{}
Valerie Wolfe <sleeplessval@gmail.com>
Canonicalize and convert Unix paths for DOS programs.
usage: path-convert [flags] <paths...>
args:
<paths...> one or more paths to convert
flags:
-h, --help show this help text
-q, --quotes surround the output strings with quotes (-qq for double quotes)
", env!("CARGO_PKG_VERSION"));
}