Skip to content

Commit

Permalink
Fix formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
ajeetdsouza committed Sep 13, 2021
1 parent 02029ae commit a60a305
Show file tree
Hide file tree
Showing 21 changed files with 108 additions and 121 deletions.
File renamed without changes.
7 changes: 3 additions & 4 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::env;
use std::io;
use std::process::Command;
use std::{env, io};

fn main() {
let pkg_version = env::var("CARGO_PKG_VERSION").unwrap();
Expand All @@ -10,8 +9,8 @@ fn main() {
};
println!("cargo:rustc-env=ZOXIDE_VERSION={}", version);

// Since we are generating completions in the package directory, we need to
// set this so that Cargo doesn't rebuild every time.
// Since we are generating completions in the package directory, we need to set this so that
// Cargo doesn't rebuild every time.
println!("cargo:rerun-if-changed=src");
println!("cargo:rerun-if-changed=templates");
println!("cargo:rerun-if-changed=tests");
Expand Down
4 changes: 4 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# comment_width = 100
# error_on_line_overflow = true
# error_on_unformatted = true
# group_imports = "StdExternalCrate"
# imports_granularity = "Module"
max_width = 120
Expand All @@ -6,3 +9,4 @@ use_field_init_shorthand = true
use_small_heuristics = "Max"
use_try_shorthand = true
# wrap_comments = true
# version = "Two"
4 changes: 2 additions & 2 deletions src/app/_app.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clap::{AppSettings, ArgEnum, Clap, ValueHint};

use std::path::PathBuf;

use clap::{AppSettings, ArgEnum, Clap, ValueHint};

const ENV_HELP: &str = "ENVIRONMENT VARIABLES:
_ZO_DATA_DIR Path for zoxide data files
_ZO_ECHO Prints the matched directory before navigating to it when set to 1
Expand Down
18 changes: 8 additions & 10 deletions src/app/add.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use crate::app::{Add, Run};
use crate::config;
use crate::db::DatabaseFile;
use crate::util;
use std::path::Path;

use anyhow::{bail, Result};

use std::path::Path;
use crate::app::{Add, Run};
use crate::db::DatabaseFile;
use crate::{config, util};

impl Run for Add {
fn run(&self) -> Result<()> {
// These characters can't be printed cleanly to a single line, so they
// can cause confusion when writing to fzf / stdout.
// These characters can't be printed cleanly to a single line, so they can cause confusion
// when writing to fzf / stdout.
const EXCLUDE_CHARS: &[char] = &['\n', '\r'];

let data_dir = config::data_dir()?;
Expand All @@ -22,11 +21,10 @@ impl Run for Add {
let mut db = db.open()?;

for path in &self.paths {
let path = if config::resolve_symlinks() { util::canonicalize(path) } else { util::resolve_path(path) }?;
let path = if config::resolve_symlinks() { util::canonicalize } else { util::resolve_path }(path)?;
let path = util::path_to_str(&path)?;

// Ignore path if it contains unsupported characters, or if it's in
// the exclude list.
// Ignore path if it contains unsupported characters, or if it's in the exclude list.
if path.contains(EXCLUDE_CHARS) || exclude_dirs.iter().any(|glob| glob.matches(path)) {
continue;
}
Expand Down
13 changes: 6 additions & 7 deletions src/app/import.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::app::{Import, ImportFrom, Run};
use crate::config;
use crate::db::{Database, DatabaseFile, Dir};
use std::fs;

use anyhow::{bail, Context, Result};

use std::fs;
use crate::app::{Import, ImportFrom, Run};
use crate::config;
use crate::db::{Database, DatabaseFile, Dir};

impl Run for Import {
fn run(&self) -> Result<()> {
Expand Down Expand Up @@ -37,9 +37,8 @@ fn from_autojump<'a>(db: &mut Database<'a>, buffer: &'a str) -> Result<()> {

let rank = split.next().with_context(|| format!("invalid entry: {}", line))?;
let mut rank = rank.parse::<f64>().with_context(|| format!("invalid rank: {}", rank))?;
// Normalize the rank using a sigmoid function. Don't import actual
// ranks from autojump, since its scoring algorithm is very different,
// and might take a while to get normalized.
// Normalize the rank using a sigmoid function. Don't import actual ranks from autojump,
// since its scoring algorithm is very different and might take a while to get normalized.
rank = sigmoid(rank);

let path = split.next().with_context(|| format!("invalid entry: {}", line))?;
Expand Down
10 changes: 5 additions & 5 deletions src/app/init.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::app::{Init, InitShell, Run};
use crate::config;
use crate::error::BrokenPipeHandler;
use crate::shell::{self, Opts};
use std::io::{self, Write};

use anyhow::{Context, Result};
use askama::Template;

use std::io::{self, Write};
use crate::app::{Init, InitShell, Run};
use crate::config;
use crate::error::BrokenPipeHandler;
use crate::shell::{self, Opts};

impl Run for Init {
fn run(&self) -> Result<()> {
Expand Down
4 changes: 2 additions & 2 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ mod init;
mod query;
mod remove;

pub use crate::app::_app::*;

use anyhow::Result;

pub use crate::app::_app::*;

pub trait Run {
fn run(&self) -> Result<()>;
}
Expand Down
11 changes: 5 additions & 6 deletions src/app/query.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use std::io::{self, Write};

use anyhow::{Context, Result};

use crate::app::{Query, Run};
use crate::config;
use crate::db::{Database, DatabaseFile};
use crate::error::BrokenPipeHandler;
use crate::fzf::Fzf;
use crate::util;

use anyhow::{Context, Result};

use std::io::{self, Write};
use crate::{config, util};

impl Run for Query {
fn run(&self) -> Result<()> {
Expand Down
11 changes: 5 additions & 6 deletions src/app/remove.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use std::io::Write;

use anyhow::{bail, Result};

use crate::app::{Remove, Run};
use crate::config;
use crate::db::DatabaseFile;
use crate::error::BrokenPipeHandler;
use crate::fzf::Fzf;
use crate::util;

use anyhow::{bail, Result};

use std::io::Write;
use crate::{config, util};

impl Run for Remove {
fn run(&self) -> Result<()> {
Expand Down
8 changes: 4 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::db::Rank;
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;

use anyhow::{bail, Context, Result};
use dirs_next as dirs;
use glob::Pattern;

use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
use crate::db::Rank;

pub fn data_dir() -> Result<PathBuf> {
let path = match env::var_os("_ZO_DATA_DIR") {
Expand Down
16 changes: 8 additions & 8 deletions src/db/dir.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use anyhow::{bail, Context, Result};
use bincode::Options as _;
use serde::{Deserialize, Serialize};

use std::borrow::Cow;
use std::fmt::{self, Display, Formatter};
use std::ops::{Deref, DerefMut};

use anyhow::{bail, Context, Result};
use bincode::Options as _;
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct DirList<'a>(#[serde(borrow)] pub Vec<Dir<'a>>);

Expand All @@ -17,8 +17,8 @@ impl DirList<'_> {
}

pub fn from_bytes(bytes: &[u8]) -> Result<DirList> {
// Assume a maximum size for the database. This prevents bincode from
// throwing strange errors when it encounters invalid data.
// Assume a maximum size for the database. This prevents bincode from throwing strange
// errors when it encounters invalid data.
const MAX_SIZE: u64 = 32 << 20; // 32 MiB
let deserializer = &mut bincode::options().with_fixint_encoding().with_limit(MAX_SIZE);

Expand Down Expand Up @@ -149,10 +149,10 @@ pub type Epoch = u64;

#[cfg(test)]
mod tests {
use super::{Dir, DirList};

use std::borrow::Cow;

use super::{Dir, DirList};

#[test]
fn zero_copy() {
let dirs = DirList(vec![Dir { path: "/".into(), rank: 0.0, last_accessed: 0 }]);
Expand Down
41 changes: 19 additions & 22 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
mod dir;
mod stream;

pub use dir::{Dir, DirList, Epoch, Rank};
pub use stream::Stream;

use anyhow::{Context, Result};
use tempfile::{NamedTempFile, PersistError};

use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
pub use dir::{Dir, DirList, Epoch, Rank};
pub use stream::Stream;
use tempfile::{NamedTempFile, PersistError};

#[derive(Debug)]
pub struct Database<'file> {
pub dirs: DirList<'file>,
Expand All @@ -28,9 +27,8 @@ impl<'file> Database<'file> {
let mut file = NamedTempFile::new_in(self.data_dir)
.with_context(|| format!("could not create temporary database in: {}", self.data_dir.display()))?;

// Preallocate enough space on the file, preventing copying later on.
// This optimization may fail on some filesystems, but it is safe to
// ignore it and proceed.
// Preallocate enough space on the file, preventing copying later on. This optimization may
// fail on some filesystems, but it is safe to ignore it and proceed.
let _ = file.as_file().set_len(buffer.len() as _);
file.write_all(&buffer)
.with_context(|| format!("could not write to temporary database: {}", file.path().display()))?;
Expand Down Expand Up @@ -89,8 +87,8 @@ impl<'file> Database<'file> {
Stream::new(self, now)
}

/// Removes the directory with `path` from the store.
/// This does not preserve ordering, but is O(1).
/// Removes the directory with `path` from the store. This does not preserve ordering, but is
/// O(1).
pub fn remove<S: AsRef<str>>(&mut self, path: S) -> bool {
let path = path.as_ref();

Expand Down Expand Up @@ -124,15 +122,16 @@ impl<'file> Database<'file> {

#[cfg(windows)]
fn persist<P: AsRef<Path>>(mut file: NamedTempFile, path: P) -> Result<(), PersistError> {
use std::thread;
use std::time::Duration;

use rand::distributions::{Distribution, Uniform};
use rand::rngs::SmallRng;
use rand::SeedableRng;
use std::thread;
use std::time::Duration;

// File renames on Windows are not atomic and sometimes fail with `PermissionDenied`.
// This is extremely unlikely unless it's running in a loop on multiple threads.
// Nevertheless, we guard against it by retrying the rename a fixed number of times.
// File renames on Windows are not atomic and sometimes fail with `PermissionDenied`. This is
// extremely unlikely unless it's running in a loop on multiple threads. Nevertheless, we guard
// against it by retrying the rename a fixed number of times.
const MAX_TRIES: usize = 10;
let mut rng = None;

Expand Down Expand Up @@ -170,9 +169,8 @@ impl DatabaseFile {
}

pub fn open(&mut self) -> Result<Database> {
// Read the entire database to memory. For smaller files, this is
// faster than mmap / streaming, and allows for zero-copy
// deserialization.
// Read the entire database to memory. For smaller files, this is faster than
// mmap / streaming, and allows for zero-copy deserialization.
let path = db_path(&self.data_dir);
match fs::read(&path) {
Ok(buffer) => {
Expand All @@ -182,9 +180,8 @@ impl DatabaseFile {
Ok(Database { dirs, modified: false, data_dir: &self.data_dir })
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
// Create data directory, but don't create any file yet.
// The file will be created later by [`Database::save`]
// if any data is modified.
// Create data directory, but don't create any file yet. The file will be created
// later by [`Database::save`] if any data is modified.
fs::create_dir_all(&self.data_dir)
.with_context(|| format!("unable to create data directory: {}", self.data_dir.display()))?;
Ok(Database { dirs: DirList::new(), modified: false, data_dir: &self.data_dir })
Expand Down
18 changes: 8 additions & 10 deletions src/db/stream.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use super::{Database, Dir, Epoch};
use crate::util;
use std::iter::Rev;
use std::ops::Range;
use std::{fs, path};

use ordered_float::OrderedFloat;

use std::fs;
use std::iter::Rev;
use std::ops::Range;
use std::path;
use super::{Database, Dir, Epoch};
use crate::util;

pub struct Stream<'db, 'file> {
db: &'db mut Database<'file>,
Expand All @@ -27,8 +26,7 @@ impl<'db, 'file> Stream<'db, 'file> {
db.dirs.sort_unstable_by_key(|dir| OrderedFloat(dir.score(now)));
let idxs = (0..db.dirs.len()).rev();

// If a directory is deleted and hasn't been used for 90 days, delete
// it from the database.
// If a directory is deleted and hasn't been used for 90 days, delete it from the database.
let expire_below = now.saturating_sub(90 * 24 * 60 * 60);

Stream {
Expand Down Expand Up @@ -124,11 +122,11 @@ impl<'db, 'file> Stream<'db, 'file> {

#[cfg(test)]
mod tests {
use super::Database;
use std::path::PathBuf;

use rstest::rstest;

use std::path::PathBuf;
use super::Database;

#[rstest]
// Case normalization
Expand Down
6 changes: 3 additions & 3 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use anyhow::{bail, Context, Result};

use std::fmt::{self, Display, Formatter};
use std::io;

// Custom error type for early exit.
use anyhow::{bail, Context, Result};

/// Custom error type for early exit.
#[derive(Debug)]
pub struct SilentExit {
pub code: i32,
Expand Down
Loading

0 comments on commit a60a305

Please sign in to comment.