Skip to content

Commit

Permalink
Merge pull request #25 from TakaakiFuruse/i24-eliminte-unwrap
Browse files Browse the repository at this point in the history
I24 eliminte unwrap
  • Loading branch information
TakaakiFuruse authored Dec 14, 2019
2 parents 969e87d + 8c66dfd commit f4ba4d5
Show file tree
Hide file tree
Showing 11 changed files with 165 additions and 143 deletions.
10 changes: 5 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "jump-kun"
version = "0.3.1"
version = "0.3.2"
authors = ["TakaakiFuruse <[email protected]>"]
edition = "2018"
description = "A simple directory jumper made by rust."
Expand All @@ -15,9 +15,9 @@ path = "src/main.rs"
jump-kun-macros={version = "0.1.0", path = "jump-kun-macros"}
walkdir= "2.2.9"
skim = "0.6.9"
serde_json= "1.0.41"
serde = { version = "1.0.101", features = ["derive"] }
serde_json= "1.0.44"
serde = { version = "1.0.103", features = ["derive"] }
dirs = "2.0.2"
derive_builder = "0.8.0"
sled = "0.28.0"
sled = "0.30.0"
ignore = "0.4.10"
anyhow = "1.0.25"
2 changes: 1 addition & 1 deletion jump-kun-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn order_builder(item: TokenStream) -> TokenStream {
.as_str()
.unwrap()
.to_owned(),
Err(_) => "CurrentDir,VisitedDir,ParentDir,ChildDir,NotSure".to_string(),
Err(_) => "CurrentDir,VisitedDir,ParentDir,ChildDir,NotSure,Invalid".to_string(),
};

let orders: Vec<&str> = order_config.split(",").collect();
Expand Down
8 changes: 6 additions & 2 deletions src/dir_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ pub fn create_ignore_if_not_found() -> File {
path.push(".config/jump-kun/.jump_kun_ignore");
match File::open(&path) {
Ok(e) => e,
Err(_e) => File::create(&path).unwrap(),
Err(_e) => {
File::create(&path).unwrap_or_else(|_| panic!("could not create .jump_kun_ignore file"))
}
}
}
pub fn create_jump_kun_ignore() -> Gitignore {
Expand All @@ -21,7 +23,9 @@ pub fn create_jump_kun_ignore() -> Gitignore {
home_path.push(".config/jump-kun/.jump_kun_ignore");
let mut builder = GitignoreBuilder::new(home_dir().unwrap());
builder.add(home_path);
builder.build().unwrap()
builder
.build()
.unwrap_or_else(|_| panic!("could not create .jump_kun_ignore file"))
}

pub fn must_be_included(entry: &DirEntry, jump_kun_ignore: &Gitignore) -> bool {
Expand Down
53 changes: 23 additions & 30 deletions src/dir_finder.rs
Original file line number Diff line number Diff line change
@@ -1,61 +1,54 @@
use super::enums::DirType;
use super::structs::{Dir, DirBuilder, DirVec};
use super::structs::{Dir, DirVec};
use super::walker::{start_walking_around, start_walking_down, start_walking_up};
use anyhow::Result;
use ignore::gitignore::Gitignore;

use std::env;
use std::path::{Path, PathBuf};

pub fn find_dirs(jump_kun_ignore: Gitignore) -> DirVec {
pub fn find_dirs(jump_kun_ignore: Gitignore) -> Result<DirVec> {
match env::var("DOWN_FROM") {
Ok(dir) => start_walking_down(from_specific_directory(dir), &jump_kun_ignore),
Ok(dir) => start_walking_down(from_specific_directory(dir)?, &jump_kun_ignore),
Err(_) => match env::var("UP_FROM") {
Ok(dir) => start_walking_up(from_parent_directory_or_root(dir), &jump_kun_ignore),
Err(_) => start_walking_around(from_current_directory(), &jump_kun_ignore),
Ok(dir) => start_walking_up(from_parent_directory_or_root(dir)?, &jump_kun_ignore),
Err(_) => start_walking_around(from_current_directory()?, &jump_kun_ignore),
},
}
}

fn from_specific_directory(dir: String) -> Dir {
DirBuilder::default()
fn from_specific_directory(dir: String) -> Result<Dir> {
Ok(Dir::default()
.path(PathBuf::from(dir))
.dirtype(DirType::CurrentDir)
.build()
.unwrap()
.dirtype(DirType::CurrentDir))
}

fn from_current_directory() -> Dir {
DirBuilder::default()
.path(env::current_dir().unwrap())
.dirtype(DirType::CurrentDir)
.build()
.unwrap()
fn from_current_directory() -> Result<Dir> {
Ok(Dir::default()
.path(env::current_dir()?)
.dirtype(DirType::CurrentDir))
}

fn from_parent_directory_or_root(dir: String) -> Dir {
DirBuilder::default()
fn from_parent_directory_or_root(dir: String) -> Result<Dir> {
Ok(Dir::default()
.path(
PathBuf::from(dir)
.parent()
.unwrap_or_else(|| Path::new("/"))
.to_path_buf(),
)
.dirtype(DirType::CurrentDir)
.build()
.unwrap()
.dirtype(DirType::CurrentDir))
}

pub fn current_dir() -> Dir {
pub fn current_dir() -> Result<Dir> {
let pathbuf = match env::var("DOWN_FROM") {
Ok(dir) => PathBuf::from(dir),
Err(_) => match env::var("UP_FROM") {
Ok(dir) => PathBuf::from(dir).parent().unwrap().to_path_buf(),
Err(_) => env::current_dir().unwrap(),
Ok(dir) => PathBuf::from(dir)
.parent()
.unwrap_or_else(|| Path::new("/"))
.to_path_buf(),
Err(_) => env::current_dir()?,
},
};
DirBuilder::default()
.path(pathbuf)
.dirtype(DirType::CurrentDir)
.build()
.unwrap()
Ok(Dir::default().path(pathbuf).dirtype(DirType::CurrentDir))
}
1 change: 1 addition & 0 deletions src/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub enum DirType {
ChildDir,
VisitedDir,
NotSure,
Invalid,
}

#[cfg(test)]
Expand Down
34 changes: 24 additions & 10 deletions src/history.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
use super::structs::{Dir, DirVec};
use crate::enums::DirType;
use anyhow::Result;
use serde_json;
use sled::Db;
use std::path::PathBuf;
use std::str;

pub fn read(path: &str) -> DirVec {
let tree = Db::open(path).unwrap();
pub fn read(path: &PathBuf) -> Result<DirVec> {
let tree = Db::open(path)?;
let dirvec: DirVec = tree
.iter()
.values()
.filter_map(|elm| {
let s: String = str::from_utf8(&elm.unwrap()).unwrap().to_owned();
let dir: Dir = serde_json::from_str(&s).unwrap();
if dir.path.exists() {
Some(dir)
.filter_map(|k| match k {
Ok((k, v)) => {
if PathBuf::from(str::from_utf8(&k).unwrap_or("str from error")).exists() {
let d: Dir =
serde_json::from_str(&str::from_utf8(&v).unwrap_or("str from error"))
.unwrap_or(Dir::invalid());

Some(d)
} else {
None
}
}
Err(_) => None,
})
.filter(|d| {
if let DirType::Invalid = d.dirtype {
false
} else {
None
true
}
})
.collect();
dirvec
Ok(dirvec)
}
13 changes: 9 additions & 4 deletions src/jump_then_add_to_hist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ use std::str;
pub fn jump_then_add_to_hist(item: String, path: &str) {
if !item.is_empty() {
let tree = Db::open(path).unwrap();
print!("{}", &item);
let new_visited_dir = Dir::new_visited(PathBuf::from(&item));
let insertion = match tree.update_and_fetch(&item.as_bytes(), update) {
Ok(v) => match v {
None => tree.insert(
&item.as_bytes(),
serde_json::to_string(&new_visited_dir).unwrap().as_bytes(),
serde_json::to_string(&new_visited_dir)
.unwrap_or("serde_json to_string error".to_string())
.as_bytes(),
),
_ => Ok(v),
},
Expand All @@ -29,7 +30,12 @@ fn update(old: Option<&[u8]>) -> Option<Vec<u8>> {
Some(bytes) => {
let mut dir: Dir = serde_json::from_str(str::from_utf8(&bytes).unwrap()).unwrap();
dir.add_cd_count();
Some(serde_json::to_string(&dir).unwrap().as_bytes().to_vec())
Some(
serde_json::to_string(&dir)
.unwrap_or("serde_json::to_string error".to_string())
.as_bytes()
.to_vec(),
)
}
None => None,
}
Expand Down Expand Up @@ -88,5 +94,4 @@ mod test_for_jump_then_add_to_hist {
assert_eq!(dir.cd_count, 2);
}
}

}
43 changes: 27 additions & 16 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,32 @@
use jump_kun::history;
use jump_kun::{dir_check, dir_finder, select_item};
extern crate skim;
use anyhow::Result;
use dirs::home_dir;
use jump_kun::jump_then_add_to_hist::jump_then_add_to_hist;
use jump_kun::structs::{Dir, DirVec};
use skim::SkimOptionsBuilder;
use skim::{SkimOptions, SkimOptionsBuilder};

fn runner(options: SkimOptions) -> Result<()> {
let mut default_db_path = match home_dir() {
Some(e) => e,
None => panic!("could not found home directory"),
};
default_db_path.push(".config/jump-kun/history");

let jump_kun_ignore = dir_check::create_jump_kun_ignore();

let history_dirs: DirVec = history::read(&default_db_path)?;
let mut found_dirs: DirVec = dir_finder::find_dirs(jump_kun_ignore)?;
let current_dir: Dir = dir_finder::current_dir()?;

found_dirs.append(history_dirs);
found_dirs.push(current_dir);
found_dirs.sort();
let item = select_item::select(found_dirs.all_path_to_string(), &options);
jump_then_add_to_hist(item, default_db_path.to_str().unwrap_or(""));
Ok(())
}

pub fn main() {
let options = SkimOptionsBuilder::default()
Expand All @@ -18,19 +40,8 @@ pub fn main() {
.preview_window(Some("right:30%:wrap"))
.build()
.unwrap();

let mut default_db_path = home_dir().unwrap();
default_db_path.push(".config/jump-kun/history");

let jump_kun_ignore = dir_check::create_jump_kun_ignore();

let history_dirs: DirVec = history::read(default_db_path.to_str().unwrap());
let mut found_dirs: DirVec = dir_finder::find_dirs(jump_kun_ignore);
let current_dir: Dir = dir_finder::current_dir();

found_dirs.append(history_dirs);
found_dirs.push(current_dir);
found_dirs.sort();
let item = select_item::select(found_dirs.all_path_to_string(), &options);
jump_then_add_to_hist(item, default_db_path.to_str().unwrap());
match runner(options) {
Ok(_e) => (),
Err(_e) => panic!("runner error"),
}
}
42 changes: 32 additions & 10 deletions src/structs.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
use super::enums::DirType;
use derive_builder::Builder;
use dirs::home_dir;
use serde::{Deserialize, Serialize};
use std::iter::FromIterator;
use std::iter::IntoIterator;
use std::path::PathBuf;

#[derive(Builder, PartialEq, Debug, Serialize, Deserialize, Clone, PartialOrd)]
#[builder(default)]
#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, PartialOrd)]
pub struct Dir {
pub path: PathBuf,
pub cd_count: u32,
Expand All @@ -25,11 +23,29 @@ impl Default for Dir {
}

impl Dir {
pub fn invalid() -> Self {
Self {
path: PathBuf::from(""),
cd_count: 0,
dirtype: DirType::Invalid,
}
}

pub fn path(mut self, path: PathBuf) -> Self {
self.path = path;
self
}

pub fn dirtype(mut self, dir_type: DirType) -> Self {
self.dirtype = dir_type;
self
}

pub fn new(path: PathBuf, cd_count: u32, dirtype: DirType) -> Dir {
Dir {
path: path,
cd_count: cd_count,
dirtype: dirtype,
path,
cd_count,
dirtype,
}
}

Expand Down Expand Up @@ -78,12 +94,19 @@ impl DirVec {
}

pub fn all_path_to_string(&self) -> String {
let str: String = self
let s: String = self
.map
.iter()
.map(|elm| format!("{}\n", elm.path.to_str().unwrap()))
.map(|elm| {
format!(
"{}\n",
elm.path
.to_str()
.unwrap_or("DirVec::all_path_to_string error")
)
})
.collect();
str
s
}

pub fn sort(&mut self) {
Expand Down Expand Up @@ -128,7 +151,6 @@ mod tests_for_dir {
let dir = Dir::new(path, 0, DirType::VisitedDir);
assert_eq!(dir_vec.map[0], dir);
}

}

#[cfg(test)]
Expand Down
Loading

0 comments on commit f4ba4d5

Please sign in to comment.