Working on cdg

This commit is contained in:
Thomas Forgione 2019-02-11 20:27:21 +01:00
parent aa736dc2a8
commit 69edc2c1ae
No known key found for this signature in database
GPG Key ID: BFD17A2D71B3B5E7
2 changed files with 106 additions and 0 deletions

View File

@ -1,5 +1,99 @@
use std::env;
use std::error::Error;
use std::process::exit;
use std::io::{stdout, stdin, Write};
use std::num::Wrapping;
use colored::*;
use gclone::Cache; use gclone::Cache;
fn flush_stdout() {
stdout().flush().ok();
}
fn main() { fn main() {
let cache = Cache::read(); let cache = Cache::read();
let request = match env::args().nth(1) {
Some(arg) => arg,
None => {
eprintln!("{} {}",
"error:".bold().red(),
"cdg expects an argument".bold());
exit(1);
},
};
let matches = cache.find(&request);
match matches.len() {
0 => {
eprintln!("{} {}",
"error:".bold().red(),
"no such directory".bold());
exit(1);
},
1 => {
println!("{}", matches[0]);
},
len => {
eprintln!("{} {}",
"info:".bold(),
"multiple entries found, please select one");
for (i, j) in matches.iter().enumerate() {
eprintln!("[{}] {}", i + 1, j);
}
eprint!("Enter your choice: ");
flush_stdout();
let mut string = String::new();
match stdin().read_line(&mut string) {
Ok(_) => (),
Err(e) => {
eprintln!("{} {} {}",
"error:".bold().red(),
"couldn't read line:".bold(),
e.description());
exit(1);
},
};
// Pop the trailing \n of the string
string.pop();
// Use wrapping to move 0 to std::usize::MAX which is ok.
let value = (Wrapping(match string.parse::<usize>() {
Ok(v) => v,
Err(e) => {
eprintln!("{} {} {}",
"error:".bold().red(),
"couldn't parse integer:".bold(),
e.description());
exit(1);
}
}) - Wrapping(1)).0;
if value >= len {
eprintln!("{} {}",
"error:".bold().red(),
"integer wasn't in the right range".bold());
exit(1);
}
println!("{}", matches[value]);
},
}
} }

View File

@ -59,6 +59,18 @@ impl Cache {
Ok(()) Ok(())
} }
pub fn find(&self, dirname: &str) -> Vec<String> {
let dirname = &format!("/{}", dirname);
let mut matches = vec![];
for line in &self.0 {
if line.ends_with(dirname) {
matches.push(line.clone());
}
}
matches
}
pub fn append(&mut self, value: String) { pub fn append(&mut self, value: String) {
self.0.push(value); self.0.push(value);
} }