Make z exclude current directory

This commit is contained in:
Ajeet D'Souza 2021-04-04 12:25:11 +05:30
parent 4224f494ed
commit 72ec94c962
10 changed files with 89 additions and 38 deletions

View File

@ -26,6 +26,10 @@ pub struct Query {
/// Prints score with results /// Prints score with results
#[clap(long, short)] #[clap(long, short)]
score: bool, score: bool,
/// Excludes a path from results
#[clap(long, hidden = true)]
exclude: Option<String>,
} }
impl Cmd for Query { impl Cmd for Query {
@ -38,7 +42,9 @@ impl Cmd for Query {
let now = util::current_time()?; let now = util::current_time()?;
let resolve_symlinks = config::zo_resolve_symlinks(); let resolve_symlinks = config::zo_resolve_symlinks();
let mut matches = db.iter_matches(&query, now, resolve_symlinks); let mut matches = db
.iter_matches(&query, now, resolve_symlinks)
.filter(|dir| Some(dir.path.as_ref()) != self.exclude.as_deref());
if self.interactive { if self.interactive {
let mut fzf = Fzf::new()?; let mut fzf = Fzf::new()?;

View File

@ -21,6 +21,8 @@ pub fn main() {
env::remove_var("RUST_LIB_BACKTRACE"); env::remove_var("RUST_LIB_BACKTRACE");
env::remove_var("RUST_BACKTRACE"); env::remove_var("RUST_BACKTRACE");
eprintln!("{:?}", std::env::args());
if let Err(e) = App::parse().run() { if let Err(e) = App::parse().run() {
match e.downcast::<SilentExit>() { match e.downcast::<SilentExit>() {
Ok(SilentExit { code }) => process::exit(code), Ok(SilentExit { code }) => process::exit(code),

View File

@ -143,7 +143,7 @@ mod tests {
let tempdir = tempdir.path().to_str().unwrap(); let tempdir = tempdir.path().to_str().unwrap();
Command::new("fish") Command::new("fish")
.env("HOME", tempdir) // fish needs a writeable $HOME directory .env("HOME", tempdir)
.args(&["--command", &source, "--private"]) .args(&["--command", &source, "--private"])
.assert() .assert()
.success() .success()
@ -151,13 +151,35 @@ mod tests {
.stderr(""); .stderr("");
} }
// TODO: fishindent #[test]
fn fish_fishindent_#i() {
let opts = dbg!(&opts()[i]);
let mut source = Fish(opts).render().unwrap();
source.push('\n');
let tempdir = tempfile::tempdir().unwrap();
let tempdir = tempdir.path().to_str().unwrap();
Command::new("fish")
.env("HOME", tempdir)
.args(&["--command", "fish_indent", "--private"])
.write_stdin(source.to_string())
.assert()
.success()
.stdout(source)
.stderr("");
}
#[test] #[test]
fn nushell_nushell_#i() { fn nushell_nushell_#i() {
let opts = dbg!(&opts()[i]); let opts = dbg!(&opts()[i]);
let source = Nushell(opts).render().unwrap(); let source = Nushell(opts).render().unwrap();
let tempdir = tempfile::tempdir().unwrap();
let tempdir = tempdir.path().to_str().unwrap();
let assert = Command::new("nu") let assert = Command::new("nu")
.env("HOME", tempdir)
.args(&["--commands", &source]) .args(&["--commands", &source])
.assert() .assert()
.success() .success()
@ -277,7 +299,8 @@ mod tests {
} }
#[test] #[test]
// FIXME: caused by <https://github.com/xonsh/xonsh/issues/3959> // Xonsh complains about type-hinting here, although it works fine in practice.
// <https://github.com/xonsh/xonsh/issues/3959>
#[ignore] #[ignore]
fn xonsh_xonsh_#i() { fn xonsh_xonsh_#i() {
let opts = dbg!(&opts()[i]); let opts = dbg!(&opts()[i]);
@ -290,6 +313,21 @@ mod tests {
.stderr(""); .stderr("");
} }
#[test]
fn zsh_shellcheck_#i() {
let opts = dbg!(&opts()[i]);
let source = Zsh(opts).render().unwrap();
// ShellCheck doesn't support zsh yet.
// https://github.com/koalaman/shellcheck/issues/809
Command::new("shellcheck")
.args(&["--enable", "all", "--shell", "bash", "-"])
.write_stdin(source)
.assert()
.success()
.stdout("")
.stderr("");
}
#[test] #[test]
fn zsh_zsh_#i() { fn zsh_zsh_#i() {
let opts = dbg!(&opts()[i]); let opts = dbg!(&opts()[i]);

View File

@ -31,7 +31,7 @@ function __zoxide_cd() {
{%- when Hook::Prompt %} {%- when Hook::Prompt %}
function __zoxide_hook() { function __zoxide_hook() {
zoxide add "$(__zoxide_pwd)" zoxide add -- "$(__zoxide_pwd)"
} }
{%- when Hook::Pwd %} {%- when Hook::Pwd %}
@ -41,7 +41,7 @@ function __zoxide_hook() {
__zoxide_pwd_old="${__zoxide_pwd_tmp}" __zoxide_pwd_old="${__zoxide_pwd_tmp}"
elif [ "${__zoxide_pwd_old}" != "${__zoxide_pwd_tmp}" ]; then elif [ "${__zoxide_pwd_old}" != "${__zoxide_pwd_tmp}" ]; then
__zoxide_pwd_old="${__zoxide_pwd_tmp}" __zoxide_pwd_old="${__zoxide_pwd_tmp}"
zoxide add "${__zoxide_pwd_old}" zoxide add -- "${__zoxide_pwd_old}"
fi fi
} }
{%- endmatch %} {%- endmatch %}
@ -77,7 +77,7 @@ function __zoxide_z() {
__zoxide_cd "$1" __zoxide_cd "$1"
else else
\builtin local __zoxide_result \builtin local __zoxide_result
__zoxide_result="$(zoxide query -- "$@")" && __zoxide_cd "${__zoxide_result}" __zoxide_result="$(zoxide query --exclude "$(__zoxide_pwd)" -- "$@")" && __zoxide_cd "${__zoxide_result}"
fi fi
} }

View File

@ -30,8 +30,8 @@ end
# #
# Initialize hook to add new entries to the database. # Initialize hook to add new entries to the database.
if test "$__zoxide_hooked" != '1' if test "$__zoxide_hooked" != 1
set __zoxide_hooked '1' set __zoxide_hooked 1
{%- match hook %} {%- match hook %}
{%- when Hook::None %} {%- when Hook::None %}
function __zoxide_hook function __zoxide_hook
@ -40,7 +40,7 @@ if test "$__zoxide_hooked" != '1'
{%- when Hook::Pwd %} {%- when Hook::Pwd %}
function __zoxide_hook --on-variable PWD function __zoxide_hook --on-variable PWD
{%- endmatch %} {%- endmatch %}
command zoxide add (__zoxide_pwd) command zoxide add -- (__zoxide_pwd)
end end
end end
@ -54,12 +54,16 @@ function __zoxide_z
set argc (count $argv) set argc (count $argv)
if test $argc -eq 0 if test $argc -eq 0
__zoxide_cd $HOME __zoxide_cd $HOME
else if begin; test $argc -eq 1; and test $argv[1] = '-'; end else if begin
test $argc -eq 1; and test $argv[1] = -
end
__zoxide_cd - __zoxide_cd -
else if begin; test $argc -eq 1; and test -d $argv[1]; end else if begin
test $argc -eq 1; and test -d $argv[1]
end
__zoxide_cd $argv[1] __zoxide_cd $argv[1]
else else
set -l __zoxide_result (command zoxide query -- $argv) set -l __zoxide_result (command zoxide query --exclude (__zoxide_pwd) -- $argv)
and __zoxide_cd $__zoxide_result and __zoxide_cd $__zoxide_result
end end
end end
@ -79,17 +83,17 @@ end
# Remove definitions. # Remove definitions.
function __zoxide_unset function __zoxide_unset
set --erase $argv > /dev/null 2>&1 set --erase $argv >/dev/null 2>&1
abbr --erase $argv > /dev/null 2>&1 abbr --erase $argv >/dev/null 2>&1
builtin functions --erase $argv > /dev/null 2>&1 builtin functions --erase $argv >/dev/null 2>&1
end end
__zoxide_unset '{{cmd}}' __zoxide_unset {{cmd}}
function {{cmd}} function {{cmd}}
__zoxide_z $argv __zoxide_z $argv
end end
__zoxide_unset '{{cmd}}i' __zoxide_unset {{cmd}}i
function {{cmd}}i function {{cmd}}i
__zoxide_zi $argv __zoxide_zi $argv
end end

View File

@ -12,7 +12,7 @@ def __zoxide_hook [] {}
{%- when Hook::Prompt %} {%- when Hook::Prompt %}
def __zoxide_hook [] { def __zoxide_hook [] {
zoxide add "$(pwd)" zoxide add -- $(pwd)
} }
{%- when Hook::Pwd %} {%- when Hook::Pwd %}
@ -20,10 +20,6 @@ def __zoxide_hook [] {}
printf "zoxide: PWD hooks are not supported on Nushell.\n Use 'zoxide init nushell --hook prompt' instead.\n" printf "zoxide: PWD hooks are not supported on Nushell.\n Use 'zoxide init nushell --hook prompt' instead.\n"
def __zoxide_hook [] {
zoxide add "$(pwd)"
}
{%- endmatch %} {%- endmatch %}
{{ SECTION }} {{ SECTION }}
@ -45,11 +41,11 @@ def __zoxide_z [...rest:string] {
if $(echo $arg0 | path exists) { if $(echo $arg0 | path exists) {
cd $arg0 cd $arg0
} { } {
cd $(zoxide query -- $args | str trim) cd $(zoxide query --exclude $(pwd) -- $args | str trim)
} }
} }
} { } {
cd $(zoxide query -- $args | str trim) cd $(zoxide query --exclude $(pwd) -- $args | str trim)
} }
} }
{%- if echo %} {%- if echo %}

View File

@ -31,7 +31,7 @@ __zoxide_cd() {
{%- when Hook::Prompt %} {%- when Hook::Prompt %}
__zoxide_hook() { __zoxide_hook() {
zoxide add "$(__zoxide_pwd)" zoxide add -- "$(__zoxide_pwd)"
} }
{%- when Hook::Pwd %} {%- when Hook::Pwd %}
@ -74,7 +74,7 @@ __zoxide_z() {
elif [ "$#" -eq 1 ] && [ -d "$1" ]; then elif [ "$#" -eq 1 ] && [ -d "$1" ]; then
__zoxide_cd "$1" __zoxide_cd "$1"
else else
__zoxide_result="$(zoxide query -- "$@")" && __zoxide_cd "${__zoxide_result}" __zoxide_result="$(zoxide query --exclude "$(__zoxide_pwd)" -- "$@")" && __zoxide_cd "${__zoxide_result}"
fi fi
} }

View File

@ -24,7 +24,7 @@ function __zoxide_cd($dir) {
# Hook to add new entries to the database. # Hook to add new entries to the database.
function __zoxide_hook { function __zoxide_hook {
zoxide add $(__zoxide_pwd) zoxide add -- $(__zoxide_pwd)
} }
# Initialize hook. # Initialize hook.
@ -65,11 +65,11 @@ function __zoxide_z {
elseif ($args.Length -eq 1 -and $args[0] -eq '-') { elseif ($args.Length -eq 1 -and $args[0] -eq '-') {
__zoxide_cd - __zoxide_cd -
} }
elseif ($args.Length -eq 1 -and ( Test-Path $args[0] -PathType Container) ) { elseif ($args.Length -eq 1 -and (Test-Path $args[0] -PathType Container)) {
__zoxide_cd $args[0] __zoxide_cd $args[0]
} }
else { else {
$__zoxide_result = zoxide query -- @args $__zoxide_result = zoxide query --exclude $(__zoxide_pwd) -- @args
if ($LASTEXITCODE -eq 0) { if ($LASTEXITCODE -eq 0) {
__zoxide_cd $__zoxide_result __zoxide_cd $__zoxide_result
} }

View File

@ -100,7 +100,7 @@ if globals().get("__zoxide_hooked") is not True:
"""Hook to add new entries to the database.""" """Hook to add new entries to the database."""
pwd = __zoxide_pwd() pwd = __zoxide_pwd()
zoxide = __zoxide_bin() zoxide = __zoxide_bin()
subprocess.run([zoxide, "add", pwd], check=False) subprocess.run([zoxide, "add", "--", pwd], check=False)
{{ SECTION }} {{ SECTION }}
@ -122,7 +122,9 @@ def __zoxide_z(args: List[str]):
try: try:
zoxide = __zoxide_bin() zoxide = __zoxide_bin()
__zoxide_cmd = subprocess.run( __zoxide_cmd = subprocess.run(
[zoxide, "query", "--"] + args, check=True, stdout=subprocess.PIPE [zoxide, "query", "--exclude", __zoxide_pwd(), "--"] + args,
check=True,
stdout=subprocess.PIPE,
) )
except CalledProcessError as exc: except CalledProcessError as exc:
raise ZoxideSilentException() from exc raise ZoxideSilentException() from exc

View File

@ -16,6 +16,7 @@ function __zoxide_pwd() {
# cd + custom logic based on the value of _ZO_ECHO. # cd + custom logic based on the value of _ZO_ECHO.
function __zoxide_cd() { function __zoxide_cd() {
# shellcheck disable=SC2164
\builtin cd "$@" {%- if echo %} && __zoxide_pwd {%- endif %} \builtin cd "$@" {%- if echo %} && __zoxide_pwd {%- endif %}
} }
@ -25,7 +26,7 @@ function __zoxide_cd() {
# Hook to add new entries to the database. # Hook to add new entries to the database.
function __zoxide_hook() { function __zoxide_hook() {
zoxide add "$(__zoxide_pwd)" zoxide add -- "$(__zoxide_pwd)"
} }
# Initialize hook. # Initialize hook.
@ -37,7 +38,7 @@ if [ "${__zoxide_hooked}" != '1' ]; then
{%- when Hook::Prompt %} {%- when Hook::Prompt %}
precmd_functions+=(__zoxide_hook) precmd_functions+=(__zoxide_hook)
{%- when Hook::Pwd %} {%- when Hook::Pwd %}
chpwd_functions=(${chpwd_functions[@]} "__zoxide_hook") chpwd_functions=("${chpwd_functions[@]}" "__zoxide_hook")
{%- endmatch %} {%- endmatch %}
fi fi
@ -51,9 +52,10 @@ function __zoxide_z() {
if [ "$#" -eq 0 ]; then if [ "$#" -eq 0 ]; then
__zoxide_cd ~ __zoxide_cd ~
elif [ "$#" -eq 1 ] && [ "$1" = '-' ]; then elif [ "$#" -eq 1 ] && [ "$1" = '-' ]; then
if [ -n "$OLDPWD" ]; then if [ -n "${OLDPWD}" ]; then
__zoxide_cd "$OLDPWD" __zoxide_cd "${OLDPWD}"
else else
# shellcheck disable=SC2016
\builtin printf 'zoxide: $OLDPWD is not set' \builtin printf 'zoxide: $OLDPWD is not set'
return 1 return 1
fi fi
@ -61,14 +63,15 @@ function __zoxide_z() {
__zoxide_cd "$1" __zoxide_cd "$1"
else else
\builtin local __zoxide_result \builtin local __zoxide_result
__zoxide_result="$(zoxide query -- "$@")" && __zoxide_cd "$__zoxide_result" __zoxide_result="$(zoxide query --exclude "$(__zoxide_pwd)" -- "$@")" \
&& __zoxide_cd "${__zoxide_result}"
fi fi
} }
# Jump to a directory using interactive search. # Jump to a directory using interactive search.
function __zoxide_zi() { function __zoxide_zi() {
\builtin local __zoxide_result \builtin local __zoxide_result
__zoxide_result="$(zoxide query -i -- "$@")" && __zoxide_cd "$__zoxide_result" __zoxide_result="$(zoxide query -i -- "$@")" && __zoxide_cd "${__zoxide_result}"
} }
{{ SECTION }} {{ SECTION }}