Update nushell init script (#966)

This commit is contained in:
Bahex 2025-02-10 00:17:41 +03:00 committed by GitHub
parent 3fe42e901e
commit da0fdb2bae
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 60 additions and 36 deletions

View File

@ -392,11 +392,13 @@ When calling `zoxide init`, the following flags are available:
- `--cmd cd` would replace the `cd` command. - `--cmd cd` would replace the `cd` command.
- `--hook <HOOK>` - `--hook <HOOK>`
- Changes how often zoxide increments a directory's score: - Changes how often zoxide increments a directory's score:
| Hook | Description | | Hook | Description |
| --------------- | --------------------------------- | | --------------- | --------------------------------- |
| `none` | Never | | `none` | Never |
| `prompt` | At every shell prompt | | `prompt` | At every shell prompt |
| `pwd` (default) | Whenever the directory is changed | | `pwd` (default) | Whenever the directory is changed |
- `--no-cmd` - `--no-cmd`
- Prevents zoxide from defining the `z` and `zi` commands. - Prevents zoxide from defining the `z` and `zi` commands.
- These functions will still be available in your shell as `__zoxide_z` and - These functions will still be available in your shell as `__zoxide_z` and
@ -410,11 +412,13 @@ Environment variables[^2] can be used for configuration. They must be set before
- `_ZO_DATA_DIR` - `_ZO_DATA_DIR`
- Specifies the directory in which the database is stored. - Specifies the directory in which the database is stored.
- The default value varies across OSes: - The default value varies across OSes:
| OS | Path | Example | | OS | Path | Example |
| ----------- | ---------------------------------------- | ------------------------------------------ | | ----------- | ---------------------------------------- | ------------------------------------------ |
| Linux / BSD | `$XDG_DATA_HOME` or `$HOME/.local/share` | `/home/alice/.local/share` | | Linux / BSD | `$XDG_DATA_HOME` or `$HOME/.local/share` | `/home/alice/.local/share` |
| macOS | `$HOME/Library/Application Support` | `/Users/Alice/Library/Application Support` | | macOS | `$HOME/Library/Application Support` | `/Users/Alice/Library/Application Support` |
| Windows | `%LOCALAPPDATA%` | `C:\Users\Alice\AppData\Local` | | Windows | `%LOCALAPPDATA%` | `C:\Users\Alice\AppData\Local` |
- `_ZO_ECHO` - `_ZO_ECHO`
- When set to 1, `z` will print the matched directory before navigating to - When set to 1, `z` will print the matched directory before navigating to
it. it.
@ -422,10 +426,12 @@ Environment variables[^2] can be used for configuration. They must be set before
- Excludes the specified directories from the database. - Excludes the specified directories from the database.
- This is provided as a list of [globs][glob], separated by OS-specific - This is provided as a list of [globs][glob], separated by OS-specific
characters: characters:
| OS | Separator | Example | | OS | Separator | Example |
| ------------------- | --------- | ----------------------- | | ------------------- | --------- | ----------------------- |
| Linux / macOS / BSD | `:` | `$HOME:$HOME/private/*` | | Linux / macOS / BSD | `:` | `$HOME:$HOME/private/*` |
| Windows | `;` | `$HOME;$HOME/private/*` | | Windows | `;` | `$HOME;$HOME/private/*` |
- By default, this is set to `"$HOME"`. - By default, this is set to `"$HOME"`.
- `_ZO_FZF_OPTS` - `_ZO_FZF_OPTS`
- Custom options to pass to [fzf] during interactive selection. See - Custom options to pass to [fzf] during interactive selection. See

View File

@ -5,4 +5,4 @@ use_field_init_shorthand = true
use_small_heuristics = "Max" use_small_heuristics = "Max"
use_try_shorthand = true use_try_shorthand = true
wrap_comments = true wrap_comments = true
version = "Two" style_edition = "2024"

View File

@ -1,10 +1,10 @@
let let
pkgs = import (builtins.fetchTarball pkgs = import (builtins.fetchTarball
"https://github.com/NixOS/nixpkgs/archive/4d513ab5f170d66afa3387bdd718d41aa936ee9f.tar.gz") { "https://github.com/NixOS/nixpkgs/archive/056faf24027e12f0ba6edebe299ed136e030d29a.tar.gz") {
overlays = [ rust ]; overlays = [ rust ];
}; };
rust = import (builtins.fetchTarball rust = import (builtins.fetchTarball
"https://github.com/oxalica/rust-overlay/archive/ab150c7412db7bea5879ce2776718f53fba37aa2.tar.gz"); "https://github.com/oxalica/rust-overlay/archive/f61820fa2c3844d6940cce269a6afdec30aa2e6c.tar.gz");
rust-nightly = rust-nightly =
pkgs.rust-bin.selectLatestNightlyWith (toolchain: toolchain.minimal); pkgs.rust-bin.selectLatestNightlyWith (toolchain: toolchain.minimal);

View File

@ -1,6 +1,6 @@
use std::path::Path; use std::path::Path;
use anyhow::{bail, Result}; use anyhow::{Result, bail};
use crate::cmd::{Add, Run}; use crate::cmd::{Add, Run};
use crate::db::Database; use crate::db::Database;

View File

@ -1,6 +1,6 @@
use std::fs; use std::fs;
use anyhow::{bail, Context, Result}; use anyhow::{Context, Result, bail};
use crate::cmd::{Import, ImportFrom, Run}; use crate::cmd::{Import, ImportFrom, Run};
use crate::db::Database; use crate::db::Database;

View File

@ -1,4 +1,4 @@
use anyhow::{bail, Result}; use anyhow::{Result, bail};
use crate::cmd::{Remove, Run}; use crate::cmd::{Remove, Run};
use crate::db::Database; use crate::db::Database;

View File

@ -2,7 +2,7 @@ use std::env;
use std::ffi::OsString; use std::ffi::OsString;
use std::path::PathBuf; use std::path::PathBuf;
use anyhow::{ensure, Context, Result}; use anyhow::{Context, Result, ensure};
use glob::Pattern; use glob::Pattern;
use crate::db::Rank; use crate::db::Rank;
@ -20,7 +20,7 @@ pub fn data_dir() -> Result<PathBuf> {
} }
pub fn echo() -> bool { pub fn echo() -> bool {
env::var_os("_ZO_ECHO").map_or(false, |var| var == "1") env::var_os("_ZO_ECHO").is_some_and(|var| var == "1")
} }
pub fn exclude_dirs() -> Result<Vec<Pattern>> { pub fn exclude_dirs() -> Result<Vec<Pattern>> {
@ -58,5 +58,5 @@ pub fn maxage() -> Result<Rank> {
} }
pub fn resolve_symlinks() -> bool { pub fn resolve_symlinks() -> bool {
env::var_os("_ZO_RESOLVE_SYMLINKS").map_or(false, |var| var == "1") env::var_os("_ZO_RESOLVE_SYMLINKS").is_some_and(|var| var == "1")
} }

View File

@ -4,7 +4,7 @@ mod stream;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::{fs, io}; use std::{fs, io};
use anyhow::{bail, Context, Result}; use anyhow::{Context, Result, bail};
use bincode::Options; use bincode::Options;
use ouroboros::self_referencing; use ouroboros::self_referencing;

View File

@ -1,7 +1,7 @@
use std::fmt::{self, Display, Formatter}; use std::fmt::{self, Display, Formatter};
use std::io; use std::io;
use anyhow::{bail, Context, Result}; use anyhow::{Context, Result, bail};
/// Custom error type for early exit. /// Custom error type for early exit.
#[derive(Debug)] #[derive(Debug)]

View File

@ -8,7 +8,7 @@ use std::{env, mem};
#[cfg(windows)] #[cfg(windows)]
use anyhow::anyhow; use anyhow::anyhow;
use anyhow::{bail, Context, Result}; use anyhow::{Context, Result, bail};
use crate::db::{Dir, Epoch}; use crate::db::{Dir, Epoch};
use crate::error::SilentExit; use crate::error::SilentExit;

View File

@ -12,23 +12,40 @@
{%- else -%} {%- else -%}
# Initialize hook to add new entries to the database. # Initialize hook to add new entries to the database.
if (not ($env | default false __zoxide_hooked | get __zoxide_hooked)) { export-env {
$env.__zoxide_hooked = true
{%- if hook == InitHook::Prompt %} {%- if hook == InitHook::Prompt %}
$env.config = ($env | default {} config).config $env.config = (
$env.config = ($env.config | default {} hooks) $env.config?
$env.config = ($env.config | update hooks ($env.config.hooks | default [] pre_prompt)) | default {}
$env.config = ($env.config | update hooks.pre_prompt ($env.config.hooks.pre_prompt | append { || | upsert hooks { default {} }
zoxide add -- $env.PWD | upsert hooks.pre_prompt { default [] }
})) )
let __zoxide_hooked = (
$env.config.hooks.pre_prompt | any { try { get __zoxide_hook } catch { false } }
)
if not $__zoxide_hooked {
$env.config.hooks.pre_prompt = ($env.config.hooks.pre_prompt | append {
__zoxide_hook: true,
code: {|| zoxide add -- $env.PWD}
})
}
{%- else if hook == InitHook::Pwd %} {%- else if hook == InitHook::Pwd %}
$env.config = ($env | default {} config).config $env.config = (
$env.config = ($env.config | default {} hooks) $env.config?
$env.config = ($env.config | update hooks ($env.config.hooks | default {} env_change)) | default {}
$env.config = ($env.config | update hooks.env_change ($env.config.hooks.env_change | default [] PWD)) | upsert hooks { default {} }
$env.config = ($env.config | update hooks.env_change.PWD ($env.config.hooks.env_change.PWD | append {|_, dir| | upsert hooks.env_change { default {} }
zoxide add -- $dir | upsert hooks.env_change.PWD { default [] }
})) )
let __zoxide_hooked = (
$env.config.hooks.env_change.PWD | any { try { get __zoxide_hook } catch { false } }
)
if not $__zoxide_hooked {
$env.config.hooks.env_change.PWD = ($env.config.hooks.env_change.PWD | append {
__zoxide_hook: true,
code: {|_, dir| zoxide add -- $dir}
})
}
{%- endif %} {%- endif %}
} }
@ -39,13 +56,14 @@ if (not ($env | default false __zoxide_hooked | get __zoxide_hooked)) {
# #
# Jump to a directory using only keywords. # Jump to a directory using only keywords.
def --env --wrapped __zoxide_z [...rest:string] { def --env --wrapped __zoxide_z [...rest: string] {
let arg0 = ($rest | append '~').0 let path = match $rest {
let arg0_is_dir = (try {$arg0 | path expand | path type}) == 'dir' [] => {'~'},
let path = if (($rest | length) <= 1) and ($arg0 == '-' or $arg0_is_dir) { [ '-' ] => {'-'},
$arg0 [ $arg ] if ($arg | path type) == 'dir' => {$arg}
} else { _ => {
(zoxide query --exclude $env.PWD -- ...$rest | str trim -r -c "\n") zoxide query --exclude $env.PWD -- ...$rest | str trim -r -c "\n"
}
} }
cd $path cd $path
{%- if echo %} {%- if echo %}

View File

@ -43,13 +43,13 @@ def __zoxide_pwd() -> str:
return pwd return pwd
def __zoxide_cd(path: typing.Optional[typing.AnyStr] = None) -> None: def __zoxide_cd(path: str | bytes | None = None) -> None:
"""cd + custom logic based on the value of _ZO_ECHO.""" """cd + custom logic based on the value of _ZO_ECHO."""
if path is None: if path is None:
args = [] args = []
elif isinstance(path, bytes): elif isinstance(path, bytes):
args = [path.decode("utf-8")] args = [path.decode("utf-8")]
elif isinstance(path, str): else:
args = [path] args = [path]
_, exc, _ = xonsh.dirstack.cd(args) _, exc, _ = xonsh.dirstack.cd(args)
if exc is not None: if exc is not None: