zoxide/src/subcommand/query.rs

73 lines
2 KiB
Rust
Raw Normal View History

use crate::env::Env;
2020-03-13 00:49:37 +00:00
use crate::util;
2020-03-17 07:04:53 +00:00
use anyhow::{bail, Result};
use std::io::{self, Write};
2020-03-13 00:49:37 +00:00
use std::path::Path;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(about = "Search for a directory")]
pub struct Query {
keywords: Vec<String>,
#[structopt(short, long, help = "Opens an interactive selection menu using fzf")]
interactive: bool,
}
impl Query {
pub fn run(mut self, env: &Env) -> Result<()> {
2020-03-13 00:49:37 +00:00
let path_opt = if self.interactive {
2020-03-17 07:04:53 +00:00
self.query_interactive(env)?
2020-03-13 00:49:37 +00:00
} else {
2020-03-17 07:04:53 +00:00
self.query(env)?
};
2020-03-13 00:49:37 +00:00
2020-03-17 07:04:53 +00:00
match path_opt {
Some(path) => {
let stdout = io::stdout();
let mut handle = stdout.lock();
handle.write_all(b"query: ").unwrap();
handle.write_all(&path).unwrap();
handle.write_all(b"\n").unwrap();
}
2020-03-17 07:04:53 +00:00
None => bail!("no match found"),
};
2020-03-13 00:49:37 +00:00
Ok(())
}
fn query(&mut self, env: &Env) -> Result<Option<Vec<u8>>> {
2020-03-13 00:49:37 +00:00
if let [path] = self.keywords.as_slice() {
if Path::new(path).is_dir() {
return Ok(Some(path.as_bytes().to_vec()));
2020-03-13 00:49:37 +00:00
}
}
let now = util::get_current_time()?;
2020-03-13 00:49:37 +00:00
for keyword in &mut self.keywords {
*keyword = keyword.to_lowercase();
2020-03-13 00:49:37 +00:00
}
if let Some(dir) = util::get_db(env)?.query(&self.keywords, now) {
// `path_to_bytes` is guaranteed to succeed here since
// the path has already been queried successfully
let path_bytes = util::path_to_bytes(&dir.path).unwrap();
Ok(Some(path_bytes.to_vec()))
2020-03-17 07:04:53 +00:00
} else {
Ok(None)
2020-03-13 00:49:37 +00:00
}
}
fn query_interactive(&mut self, env: &Env) -> Result<Option<Vec<u8>>> {
2020-03-13 00:49:37 +00:00
let now = util::get_current_time()?;
for keyword in &mut self.keywords {
*keyword = keyword.to_lowercase();
2020-03-13 00:49:37 +00:00
}
let dirs = util::get_db(env)?.query_all(&self.keywords);
2020-03-13 00:49:37 +00:00
util::fzf_helper(now, dirs)
}
}