From 2c2286cea223fdf40858b301e2a0c3058d14c158 Mon Sep 17 00:00:00 2001 From: Blonteractor <48821041+Blonteractor@users.noreply.github.com> Date: Mon, 9 Jan 2023 15:55:33 +0530 Subject: [PATCH] Added better output in query when already in the matched directory (#463) --- build.rs | 4 ++-- contrib/completions/_zoxide | 2 +- contrib/completions/_zoxide.ps1 | 2 +- contrib/completions/zoxide.elv | 2 +- contrib/completions/zoxide.fish | 2 +- contrib/completions/zoxide.ts | 2 +- rustfmt.toml | 1 - src/cmd/add.rs | 12 ++++++---- src/cmd/cmd.rs | 2 +- src/cmd/edit.rs | 3 ++- src/cmd/import.rs | 13 ++++++----- src/cmd/query.rs | 10 +++++++-- src/config.rs | 8 ++++--- src/db/dir.rs | 6 ++--- src/db/mod.rs | 40 ++++++++++++++++++++++----------- src/db/stream.rs | 10 +++++++++ src/shell.rs | 33 ++++++++++++++++++++------- src/util.rs | 40 ++++++++++++++++++++------------- tests/completions.rs | 13 +++++++---- xtask/src/main.rs | 25 +++++++++++++++------ 20 files changed, 154 insertions(+), 76 deletions(-) diff --git a/build.rs b/build.rs index a9aa7e5..f024a34 100644 --- a/build.rs +++ b/build.rs @@ -9,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=build.rs"); println!("cargo:rerun-if-changed=src/"); println!("cargo:rerun-if-changed=templates/"); diff --git a/contrib/completions/_zoxide b/contrib/completions/_zoxide index 3a5c48c..9a0df2a 100644 --- a/contrib/completions/_zoxide +++ b/contrib/completions/_zoxide @@ -117,7 +117,7 @@ _arguments "${_arguments_options[@]}" \ ;; (query) _arguments "${_arguments_options[@]}" \ -'--exclude=[Exclude a path from results]:path:_files -/' \ +'--exclude=[Exclude the current directory]:path:_files -/' \ '--all[Show deleted directories]' \ '(-l --list)-i[Use interactive selection]' \ '(-l --list)--interactive[Use interactive selection]' \ diff --git a/contrib/completions/_zoxide.ps1 b/contrib/completions/_zoxide.ps1 index abdee9d..2978e19 100644 --- a/contrib/completions/_zoxide.ps1 +++ b/contrib/completions/_zoxide.ps1 @@ -99,7 +99,7 @@ Register-ArgumentCompleter -Native -CommandName 'zoxide' -ScriptBlock { break } 'zoxide;query' { - [CompletionResult]::new('--exclude', 'exclude', [CompletionResultType]::ParameterName, 'Exclude a path from results') + [CompletionResult]::new('--exclude', 'exclude', [CompletionResultType]::ParameterName, 'Exclude the current directory') [CompletionResult]::new('--all', 'all', [CompletionResultType]::ParameterName, 'Show deleted directories') [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'Use interactive selection') [CompletionResult]::new('--interactive', 'interactive', [CompletionResultType]::ParameterName, 'Use interactive selection') diff --git a/contrib/completions/zoxide.elv b/contrib/completions/zoxide.elv index 2bcdb9b..abc01d7 100644 --- a/contrib/completions/zoxide.elv +++ b/contrib/completions/zoxide.elv @@ -87,7 +87,7 @@ set edit:completion:arg-completer[zoxide] = {|@words| cand --version 'Print version information' } &'zoxide;query'= { - cand --exclude 'Exclude a path from results' + cand --exclude 'Exclude the current directory' cand --all 'Show deleted directories' cand -i 'Use interactive selection' cand --interactive 'Use interactive selection' diff --git a/contrib/completions/zoxide.fish b/contrib/completions/zoxide.fish index 9545776..1dbe1c3 100644 --- a/contrib/completions/zoxide.fish +++ b/contrib/completions/zoxide.fish @@ -31,7 +31,7 @@ complete -c zoxide -n "__fish_seen_subcommand_from init" -l hook -d 'Changes how complete -c zoxide -n "__fish_seen_subcommand_from init" -l no-cmd -d 'Prevents zoxide from defining the `z` and `zi` commands' complete -c zoxide -n "__fish_seen_subcommand_from init" -s h -l help -d 'Print help information' complete -c zoxide -n "__fish_seen_subcommand_from init" -s V -l version -d 'Print version information' -complete -c zoxide -n "__fish_seen_subcommand_from query" -l exclude -d 'Exclude a path from results' -r -f -a "(__fish_complete_directories)" +complete -c zoxide -n "__fish_seen_subcommand_from query" -l exclude -d 'Exclude the current directory' -r -f -a "(__fish_complete_directories)" complete -c zoxide -n "__fish_seen_subcommand_from query" -l all -d 'Show deleted directories' complete -c zoxide -n "__fish_seen_subcommand_from query" -s i -l interactive -d 'Use interactive selection' complete -c zoxide -n "__fish_seen_subcommand_from query" -s l -l list -d 'List all matching directories' diff --git a/contrib/completions/zoxide.ts b/contrib/completions/zoxide.ts index 624d3c2..5f1d16f 100644 --- a/contrib/completions/zoxide.ts +++ b/contrib/completions/zoxide.ts @@ -196,7 +196,7 @@ const completion: Fig.Spec = { options: [ { name: "--exclude", - description: "Exclude a path from results", + description: "Exclude the current directory", isRepeatable: true, args: { name: "exclude", diff --git a/rustfmt.toml b/rustfmt.toml index ebaf638..024f400 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,6 +1,5 @@ group_imports = "StdExternalCrate" imports_granularity = "Module" -max_width = 120 newline_style = "Native" use_field_init_shorthand = true use_small_heuristics = "Max" diff --git a/src/cmd/add.rs b/src/cmd/add.rs index 21514b8..945bbe5 100644 --- a/src/cmd/add.rs +++ b/src/cmd/add.rs @@ -8,8 +8,8 @@ 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 stdout. + // These characters can't be printed cleanly to a single line, so they can cause + // confusion when writing to stdout. const EXCLUDE_CHARS: &[char] = &['\n', '\r']; let exclude_dirs = config::exclude_dirs()?; @@ -19,10 +19,14 @@ impl Run for Add { let mut db = Database::open()?; for path in &self.paths { - let path = if config::resolve_symlinks() { util::canonicalize } 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; } diff --git a/src/cmd/cmd.rs b/src/cmd/cmd.rs index 1f19a80..2ae88de 100644 --- a/src/cmd/cmd.rs +++ b/src/cmd/cmd.rs @@ -137,7 +137,7 @@ pub struct Query { #[clap(long, short)] pub score: bool, - /// Exclude a path from results + /// Exclude the current directory #[clap(long, value_hint = ValueHint::DirPath, value_name = "path")] pub exclude: Option, } diff --git a/src/cmd/edit.rs b/src/cmd/edit.rs index 2bbaedc..075f6c0 100644 --- a/src/cmd/edit.rs +++ b/src/cmd/edit.rs @@ -26,7 +26,8 @@ impl Run for Edit { let stdout = &mut io::stdout().lock(); for dir in db.dirs().iter().rev() { - write!(stdout, "{}\0", dir.display().with_score(now).with_separator('\t')).pipe_exit("fzf")?; + write!(stdout, "{}\0", dir.display().with_score(now).with_separator('\t')) + .pipe_exit("fzf")?; } Ok(()) } diff --git a/src/cmd/import.rs b/src/cmd/import.rs index 3a2c206..ae667d4 100644 --- a/src/cmd/import.rs +++ b/src/cmd/import.rs @@ -7,8 +7,9 @@ use crate::db::Database; impl Run for Import { fn run(&self) -> Result<()> { - let buffer = fs::read_to_string(&self.path) - .with_context(|| format!("could not open database for importing: {}", &self.path.display()))?; + let buffer = fs::read_to_string(&self.path).with_context(|| { + format!("could not open database for importing: {}", &self.path.display()) + })?; let mut db = Database::open()?; if !self.merge && !db.dirs().is_empty() { @@ -34,8 +35,9 @@ fn import_autojump(db: &mut Database, buffer: &str) -> Result<()> { let rank = split.next().with_context(|| format!("invalid entry: {line}"))?; let mut rank = rank.parse::().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}"))?; @@ -57,7 +59,8 @@ fn import_z(db: &mut Database, buffer: &str) -> Result<()> { let mut split = line.rsplitn(3, '|'); let last_accessed = split.next().with_context(|| format!("invalid entry: {line}"))?; - let last_accessed = last_accessed.parse().with_context(|| format!("invalid epoch: {last_accessed}"))?; + let last_accessed = + last_accessed.parse().with_context(|| format!("invalid epoch: {last_accessed}"))?; let rank = split.next().with_context(|| format!("invalid entry: {line}"))?; let rank = rank.parse().with_context(|| format!("invalid rank: {rank}"))?; diff --git a/src/cmd/query.rs b/src/cmd/query.rs index 14a25ef..b846ffe 100644 --- a/src/cmd/query.rs +++ b/src/cmd/query.rs @@ -1,6 +1,6 @@ use std::io::{self, Write}; -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use crate::cmd::{Query, Run}; use crate::config; @@ -47,7 +47,13 @@ impl Query { } } else { let handle = &mut io::stdout(); - let dir = stream.next().context("no match found")?; + let Some(dir) = stream.next() else { + bail!(if stream.did_exclude() { + "you are already in the only match" + } else { + "no match found" + }); + }; let dir = if self.score { dir.display().with_score(now) } else { dir.display() }; writeln!(handle, "{dir}").pipe_exit("stdout")?; } diff --git a/src/config.rs b/src/config.rs index c5cb6ae..4a1b6b4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -26,7 +26,8 @@ pub fn exclude_dirs() -> Result> { Some(paths) => env::split_paths(&paths) .map(|path| { let pattern = path.to_str().context("invalid unicode in _ZO_EXCLUDE_DIRS")?; - Pattern::new(pattern).with_context(|| format!("invalid glob in _ZO_EXCLUDE_DIRS: {pattern}")) + Pattern::new(pattern) + .with_context(|| format!("invalid glob in _ZO_EXCLUDE_DIRS: {pattern}")) }) .collect(), None => { @@ -47,8 +48,9 @@ pub fn fzf_opts() -> Option { pub fn maxage() -> Result { env::var_os("_ZO_MAXAGE").map_or(Ok(10_000.0), |maxage| { let maxage = maxage.to_str().context("invalid unicode in _ZO_MAXAGE")?; - let maxage = - maxage.parse::().with_context(|| format!("unable to parse _ZO_MAXAGE as integer: {maxage}"))?; + let maxage = maxage + .parse::() + .with_context(|| format!("unable to parse _ZO_MAXAGE as integer: {maxage}"))?; Ok(maxage as Rank) }) } diff --git a/src/db/dir.rs b/src/db/dir.rs index d545b40..5d6d62c 100644 --- a/src/db/dir.rs +++ b/src/db/dir.rs @@ -1,7 +1,5 @@ -use std::{ - borrow::Cow, - fmt::{self, Display, Formatter}, -}; +use std::borrow::Cow; +use std::fmt::{self, Display, Formatter}; use serde::{Deserialize, Serialize}; diff --git a/src/db/mod.rs b/src/db/mod.rs index 0e85e28..8eb9fc6 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -37,13 +37,16 @@ impl Database { match fs::read(&path) { Ok(bytes) => Self::try_new(path, bytes, |bytes| Self::deserialize(bytes), false), 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. - fs::create_dir_all(data_dir) - .with_context(|| format!("unable to create data directory: {}", data_dir.display()))?; + // 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(data_dir).with_context(|| { + format!("unable to create data directory: {}", data_dir.display()) + })?; Ok(Self::new(path, Vec::new(), |_| Vec::new(), false)) } - Err(e) => Err(e).with_context(|| format!("could not read from database: {}", path.display())), + Err(e) => { + Err(e).with_context(|| format!("could not read from database: {}", path.display())) + } } } @@ -64,7 +67,9 @@ impl Database { pub fn add(&mut self, path: impl AsRef + Into, by: Rank, now: Epoch) { self.with_dirs_mut(|dirs| match dirs.iter_mut().find(|dir| dir.path == path.as_ref()) { Some(dir) => dir.rank = (dir.rank + by).max(0.0), - None => dirs.push(Dir { path: path.into().into(), rank: by.max(0.0), last_accessed: now }), + None => { + dirs.push(Dir { path: path.into().into(), rank: by.max(0.0), last_accessed: now }) + } }); self.with_dirty_mut(|dirty| *dirty = true); } @@ -73,7 +78,9 @@ impl Database { /// directory is always in the database, it is expected that the user either /// does a check before calling this, or calls `dedup()` afterward. pub fn add_unchecked(&mut self, path: impl AsRef + Into, rank: Rank, now: Epoch) { - self.with_dirs_mut(|dirs| dirs.push(Dir { path: path.into().into(), rank, last_accessed: now })); + self.with_dirs_mut(|dirs| { + dirs.push(Dir { path: path.into().into(), rank, last_accessed: now }) + }); self.with_dirty_mut(|dirty| *dirty = true); } @@ -85,7 +92,9 @@ impl Database { dir.rank = (dir.rank + by).max(0.0); dir.last_accessed = now; } - None => dirs.push(Dir { path: path.into().into(), rank: by.max(0.0), last_accessed: now }), + None => { + dirs.push(Dir { path: path.into().into(), rank: by.max(0.0), last_accessed: now }) + } }); self.with_dirty_mut(|dirty| *dirty = true); } @@ -166,7 +175,9 @@ impl Database { pub fn sort_by_score(&mut self, now: Epoch) { self.with_dirs_mut(|dirs| { - dirs.sort_unstable_by(|dir1: &Dir, dir2: &Dir| dir1.score(now).total_cmp(&dir2.score(now))) + dirs.sort_unstable_by(|dir1: &Dir, dir2: &Dir| { + dir1.score(now).total_cmp(&dir2.score(now)) + }) }); self.with_dirty_mut(|dirty| *dirty = true); } @@ -182,7 +193,8 @@ impl Database { fn serialize(dirs: &[Dir<'_>]) -> Result> { (|| -> bincode::Result<_> { // Preallocate buffer with combined size of sections. - let buffer_size = bincode::serialized_size(&Self::VERSION)? + bincode::serialized_size(&dirs)?; + let buffer_size = + bincode::serialized_size(&Self::VERSION)? + bincode::serialized_size(&dirs)?; let mut buffer = Vec::with_capacity(buffer_size as usize); // Serialize sections into buffer. @@ -195,8 +207,8 @@ impl Database { } fn deserialize(bytes: &[u8]) -> Result> { - // 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); @@ -210,7 +222,9 @@ impl Database { // Deserialize sections. let version = deserializer.deserialize(bytes_version)?; let dirs = match version { - Self::VERSION => deserializer.deserialize(bytes_dirs).context("could not deserialize database")?, + Self::VERSION => { + deserializer.deserialize(bytes_dirs).context("could not deserialize database")? + } version => { bail!("unsupported version (got {version}, supports {})", Self::VERSION) } diff --git a/src/db/stream.rs b/src/db/stream.rs index 04b5c83..44b59d9 100644 --- a/src/db/stream.rs +++ b/src/db/stream.rs @@ -6,8 +6,12 @@ use crate::db::{Database, Dir, Epoch}; use crate::util::{self, MONTH}; pub struct Stream<'a> { + // State db: &'a mut Database, idxs: Rev>, + did_exclude: bool, + + // Configuration keywords: Vec, check_exists: bool, expire_below: Epoch, @@ -27,6 +31,7 @@ impl<'a> Stream<'a> { Stream { db, idxs, + did_exclude: false, keywords: Vec::new(), check_exists: false, expire_below, @@ -67,6 +72,7 @@ impl<'a> Stream<'a> { } if Some(dir.path.as_ref()) == self.exclude_path.as_deref() { + self.did_exclude = true; continue; } @@ -77,6 +83,10 @@ impl<'a> Stream<'a> { None } + pub fn did_exclude(&self) -> bool { + self.did_exclude + } + fn matches_exists(&self, path: &str) -> bool { if !self.check_exists { return true; diff --git a/src/shell.rs b/src/shell.rs index 53a742d..8321546 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -98,14 +98,21 @@ mod tests { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let mut source = String::new(); - // Filter out lines using edit:*, since those functions are only available in the - // interactive editor. - for line in Elvish(&opts).render().unwrap().split('\n').filter(|line| !line.contains("edit:")) { + // Filter out lines using edit:*, since those functions are only available in + // the interactive editor. + for line in + Elvish(&opts).render().unwrap().split('\n').filter(|line| !line.contains("edit:")) + { source.push_str(line); source.push('\n'); } - Command::new("elvish").args(["-c", &source, "-norc"]).assert().success().stdout("").stderr(""); + Command::new("elvish") + .args(["-c", &source, "-norc"]) + .assert() + .success() + .stdout("") + .stderr(""); } #[apply(opts)] @@ -151,8 +158,12 @@ mod tests { let tempdir = tempfile::tempdir().unwrap(); let tempdir = tempdir.path(); - let assert = - Command::new("nu").env("HOME", tempdir).args(["--commands", &source]).assert().success().stderr(""); + let assert = Command::new("nu") + .env("HOME", tempdir) + .args(["--commands", &source]) + .assert() + .success() + .stderr(""); if opts.hook != InitHook::Pwd { assert.stdout(""); @@ -179,7 +190,8 @@ mod tests { let opts = Opts { cmd, hook, echo, resolve_symlinks }; let source = Posix(&opts).render().unwrap(); - let assert = Command::new("dash").args(["-e", "-u", "-c", &source]).assert().success().stderr(""); + let assert = + Command::new("dash").args(["-e", "-u", "-c", &source]).assert().success().stderr(""); if opts.hook != InitHook::Pwd { assert.stdout(""); } @@ -234,7 +246,12 @@ mod tests { let mut source = Xonsh(&opts).render().unwrap(); source.push('\n'); - Command::new("black").args(["--check", "--diff", "-"]).write_stdin(source).assert().success().stdout(""); + Command::new("black") + .args(["--check", "--diff", "-"]) + .write_stdin(source) + .assert() + .success() + .stdout(""); } #[apply(opts)] diff --git a/src/util.rs b/src/util.rs index aa9c24a..f980f33 100644 --- a/src/util.rs +++ b/src/util.rs @@ -159,7 +159,9 @@ pub fn write(path: impl AsRef, contents: impl AsRef<[u8]>) -> Result<()> { let result = (|| { // Write to the tmpfile. let _ = tmp_file.set_len(contents.len() as u64); - tmp_file.write_all(contents).with_context(|| format!("could not write to file: {}", tmp_path.display()))?; + tmp_file + .write_all(contents) + .with_context(|| format!("could not write to file: {}", tmp_path.display()))?; // Set the owner of the tmpfile (UNIX only). #[cfg(unix)] @@ -224,16 +226,21 @@ fn rename(from: impl AsRef, to: impl AsRef) -> Result<()> { loop { match fs::rename(from, to) { - Err(e) if e.kind() == io::ErrorKind::PermissionDenied && attempts < MAX_ATTEMPTS => attempts += 1, + Err(e) if e.kind() == io::ErrorKind::PermissionDenied && attempts < MAX_ATTEMPTS => { + attempts += 1 + } result => { - break result.with_context(|| format!("could not rename file: {} -> {}", from.display(), to.display())) + break result.with_context(|| { + format!("could not rename file: {} -> {}", from.display(), to.display()) + }); } } } } pub fn canonicalize(path: impl AsRef) -> Result { - dunce::canonicalize(&path).with_context(|| format!("could not resolve path: {}", path.as_ref().display())) + dunce::canonicalize(&path) + .with_context(|| format!("could not resolve path: {}", path.as_ref().display())) } pub fn current_dir() -> Result { @@ -241,8 +248,10 @@ pub fn current_dir() -> Result { } pub fn current_time() -> Result { - let current_time = - SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).context("system clock set to invalid time")?.as_secs(); + let current_time = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .context("system clock set to invalid time")? + .as_secs(); Ok(current_time) } @@ -252,8 +261,8 @@ pub fn path_to_str(path: &impl AsRef) -> Result<&str> { path.to_str().with_context(|| format!("invalid unicode in path: {}", path.display())) } -/// Returns the absolute version of a path. Like [`std::path::Path::canonicalize`], but doesn't -/// resolve symlinks. +/// Returns the absolute version of a path. Like +/// [`std::path::Path::canonicalize`], but doesn't resolve symlinks. pub fn resolve_path(path: impl AsRef) -> Result { let path = path.as_ref(); let base_path; @@ -271,7 +280,9 @@ pub fn resolve_path(path: impl AsRef) -> Result { match components.next() { Some(Component::Prefix(prefix)) => match prefix.kind() { - Prefix::Disk(drive_letter) | Prefix::VerbatimDisk(drive_letter) => Some(drive_letter), + Prefix::Disk(drive_letter) | Prefix::VerbatimDisk(drive_letter) => { + Some(drive_letter) + } _ => None, }, _ => None, @@ -324,8 +335,9 @@ pub fn resolve_path(path: impl AsRef) -> Result { components.next(); let current_dir = env::current_dir()?; - let drive_letter = get_drive_letter(¤t_dir) - .with_context(|| format!("could not get drive letter: {}", current_dir.display()))?; + let drive_letter = get_drive_letter(¤t_dir).with_context(|| { + format!("could not get drive letter: {}", current_dir.display()) + })?; base_path = get_drive_path(drive_letter); stack.extend(base_path.components()); } @@ -361,9 +373,5 @@ pub fn resolve_path(path: impl AsRef) -> Result { /// Convert a string to lowercase, with a fast path for ASCII strings. pub fn to_lowercase(s: impl AsRef) -> String { let s = s.as_ref(); - if s.is_ascii() { - s.to_ascii_lowercase() - } else { - s.to_lowercase() - } + if s.is_ascii() { s.to_ascii_lowercase() } else { s.to_lowercase() } } diff --git a/tests/completions.rs b/tests/completions.rs index d122eb5..50d807c 100644 --- a/tests/completions.rs +++ b/tests/completions.rs @@ -6,12 +6,17 @@ use assert_cmd::Command; #[test] fn completions_bash() { let source = include_str!("../contrib/completions/zoxide.bash"); - Command::new("bash").args(["--noprofile", "--norc", "-c", source]).assert().success().stdout("").stderr(""); + Command::new("bash") + .args(["--noprofile", "--norc", "-c", source]) + .assert() + .success() + .stdout("") + .stderr(""); } -// Elvish: the completions file uses editor commands to add completions to the shell. However, -// Elvish does not support running editor commands from a script, so we can't create a test for -// this. See: https://github.com/elves/elvish/issues/1299 +// Elvish: the completions file uses editor commands to add completions to the +// shell. However, Elvish does not support running editor commands from a +// script, so we can't create a test for this. See: https://github.com/elves/elvish/issues/1299 #[test] fn completions_fish() { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ab99020..ff997f7 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -9,8 +9,11 @@ use ignore::Walk; fn main() -> Result<()> { let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let dir = dir.parent().with_context(|| format!("could not find workspace root: {}", dir.display()))?; - env::set_current_dir(dir).with_context(|| format!("could not set current directory: {}", dir.display()))?; + let dir = dir + .parent() + .with_context(|| format!("could not find workspace root: {}", dir.display()))?; + env::set_current_dir(dir) + .with_context(|| format!("could not set current directory: {}", dir.display()))?; let nix_enabled = enable_nix(); let app = App::parse(); @@ -55,7 +58,10 @@ impl CommandExt for &mut Command { fn run_ci(nix_enabled: bool) -> Result<()> { // Run cargo-clippy. - Command::new("cargo").args(["clippy", "--all-features", "--all-targets"]).args(["--", "-Dwarnings"]).run()?; + Command::new("cargo") + .args(["clippy", "--all-features", "--all-targets"]) + .args(["--", "-Dwarnings"]) + .run()?; run_fmt(nix_enabled, true)?; run_lint(nix_enabled)?; run_tests(nix_enabled, "") @@ -63,8 +69,9 @@ fn run_ci(nix_enabled: bool) -> Result<()> { fn run_fmt(nix_enabled: bool, check: bool) -> Result<()> { // Run cargo-fmt. - // let check_args: &[&str] = if check { &["--check", "--files-with-diff"] } else { &[] }; - // Command::new("cargo").args(&["fmt", "--all", "--"]).args(check_args).run()?; + // let check_args: &[&str] = if check {&["--check", "--files-with-diff"] } else + // { &[] }; Command::new("cargo").args(&["fmt", "--all", + // "--"]).args(check_args).run()?; // Run nixfmt. if nix_enabled { @@ -119,7 +126,8 @@ fn enable_nix() -> bool { if nix_enabled { return true; } - let nix_detected = Command::new("nix-shell").arg("--version").status().map(|s| s.success()).unwrap_or(false); + let nix_detected = + Command::new("nix-shell").arg("--version").status().map(|s| s.success()).unwrap_or(false); if !nix_detected { return false; } @@ -128,6 +136,9 @@ fn enable_nix() -> bool { let args = env::args(); let cmd = shell_words::join(args); - let status = Command::new("nix-shell").args(["--pure", "--run", &cmd, "--", "shell.nix"]).status().unwrap(); + let status = Command::new("nix-shell") + .args(["--pure", "--run", &cmd, "--", "shell.nix"]) + .status() + .unwrap(); process::exit(status.code().unwrap_or(1)); }