From 69edc2c1ae28500fa19873688771d8687fc7ee1f Mon Sep 17 00:00:00 2001 From: Thomas Forgione Date: Mon, 11 Feb 2019 20:27:21 +0100 Subject: [PATCH] Working on cdg --- src/cdg.rs | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 12 +++++++ 2 files changed, 106 insertions(+) diff --git a/src/cdg.rs b/src/cdg.rs index 4a7984c..603dec2 100644 --- a/src/cdg.rs +++ b/src/cdg.rs @@ -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; +fn flush_stdout() { + stdout().flush().ok(); +} + fn main() { 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::() { + 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]); + + }, + } + + } + diff --git a/src/lib.rs b/src/lib.rs index e5ac623..7328637 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,6 +59,18 @@ impl Cache { Ok(()) } + pub fn find(&self, dirname: &str) -> Vec { + 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) { self.0.push(value); }