zoxide/templates/xonsh.txt

169 lines
4.4 KiB
Plaintext
Raw Normal View History

2021-04-09 00:05:42 +05:30
{%- let section = "# =============================================================================\n#" -%}
{%- let not_configured = "# -- not configured --" -%}
2020-10-18 14:52:13 +05:30
2020-11-11 00:41:26 +05:30
"""Initialize zoxide on Xonsh."""
2020-10-18 14:52:13 +05:30
import os
import os.path
2020-10-20 23:29:28 +05:30
import subprocess
import sys
2020-11-11 00:41:26 +05:30
{%- if cmd.is_some() %}
from builtins import aliases # type: ignore # pylint: disable=no-name-in-module
{%- endif %}
{%- if hook != Hook::None %}
from builtins import events # type: ignore # pylint: disable=no-name-in-module
{%- endif %}
2020-10-20 23:29:28 +05:30
from subprocess import CalledProcessError
2020-11-11 00:41:26 +05:30
from typing import AnyStr, List, Optional
2021-03-01 11:40:10 +05:30
import xonsh.dirstack # type: ignore # pylint: disable=import-error
2021-03-30 18:44:29 +05:30
import xonsh.environ # type: ignore # pylint: disable=import-error
2020-10-18 14:52:13 +05:30
2021-04-09 00:05:42 +05:30
{{ section }}
2020-10-18 14:52:13 +05:30
# Utility functions for zoxide.
#
2020-11-11 00:41:26 +05:30
2021-03-30 18:44:29 +05:30
def __zoxide_bin() -> str:
"""Finds and returns the location of the zoxide binary."""
zoxide = xonsh.environ.locate_binary("zoxide")
if zoxide is None:
zoxide = "zoxide"
return zoxide
2020-10-18 14:52:13 +05:30
def __zoxide_pwd() -> str:
2020-11-11 00:41:26 +05:30
"""pwd based on the value of _ZO_RESOLVE_SYMLINKS."""
2020-10-18 14:52:13 +05:30
{%- if resolve_symlinks %}
2020-11-11 00:41:26 +05:30
pwd = os.getcwd()
2020-10-18 14:52:13 +05:30
{%- else %}
2020-11-11 00:41:26 +05:30
pwd = os.getenv("PWD")
if pwd is None:
raise Exception("$PWD not found in env")
2020-10-18 14:52:13 +05:30
{%- endif %}
2020-11-11 00:41:26 +05:30
return pwd
def __zoxide_cd(path: Optional[AnyStr] = None):
"""cd + custom logic based on the value of _ZO_ECHO."""
if path is None:
args = []
elif isinstance(path, bytes):
args = [path.decode("utf-8")]
elif isinstance(path, str):
args = [path]
_, exc, _ = xonsh.dirstack.cd(args)
if exc is not None:
raise Exception(exc)
{%- if echo %}
print(__zoxide_pwd())
{%- endif %}
class ZoxideSilentException(Exception):
"""Exit without complaining."""
def __zoxide_errhandler(func):
"""Print exception and exit with error code 1."""
def wrapper(args: List[str]):
try:
func(args)
return 0
except ZoxideSilentException:
return 1
except Exception as exc: # pylint: disable=broad-except
print(f"zoxide: {exc}", file=sys.stderr)
return 1
return wrapper
2020-10-18 14:52:13 +05:30
2021-04-09 00:05:42 +05:30
{{ section }}
2020-10-18 14:52:13 +05:30
# Hook configuration for zoxide.
#
# Initialize hook to add new entries to the database.
if globals().get("__zoxide_hooked") is not True:
globals()["__zoxide_hooked"] = True
2021-04-09 00:05:42 +05:30
{% match hook -%}
{%- when Hook::None %}
{{ not_configured }}
{%- when Hook::Prompt %}
@events.on_post_prompt # type: ignore # pylint:disable=undefined-variable
2021-04-09 00:05:42 +05:30
{%- when Hook::Pwd %}
@events.on_chdir # type: ignore # pylint:disable=undefined-variable
2021-04-09 00:05:42 +05:30
{%- endmatch %}
def __zoxide_hook(**_kwargs):
"""Hook to add new entries to the database."""
pwd = __zoxide_pwd()
2021-03-30 18:44:29 +05:30
zoxide = __zoxide_bin()
subprocess.run([zoxide, "add", "--", pwd], check=False)
2020-11-11 00:41:26 +05:30
2020-10-18 14:52:13 +05:30
2021-04-09 00:05:42 +05:30
{{ section }}
2020-10-18 14:52:13 +05:30
# When using zoxide with --no-aliases, alias these internal functions as
# desired.
#
2020-10-20 23:29:28 +05:30
2020-11-11 00:41:26 +05:30
@__zoxide_errhandler
def __zoxide_z(args: List[str]):
"""Jump to a directory using only keywords."""
if args == []:
__zoxide_cd()
elif args == ["-"]:
__zoxide_cd("-")
elif len(args) == 1 and os.path.isdir(args[0]):
__zoxide_cd(args[0])
else:
2020-10-20 23:29:28 +05:30
try:
2021-03-30 18:44:29 +05:30
zoxide = __zoxide_bin()
2020-11-11 00:41:26 +05:30
__zoxide_cmd = subprocess.run(
[zoxide, "query", "--exclude", __zoxide_pwd(), "--"] + args,
check=True,
stdout=subprocess.PIPE,
2020-11-11 00:41:26 +05:30
)
except CalledProcessError as exc:
raise ZoxideSilentException() from exc
2020-10-20 23:29:28 +05:30
2020-11-11 00:41:26 +05:30
__zoxide_result = __zoxide_cmd.stdout[:-1]
2020-10-20 23:29:28 +05:30
__zoxide_cd(__zoxide_result)
2020-10-18 14:52:13 +05:30
2020-10-20 23:29:28 +05:30
2020-11-11 00:41:26 +05:30
def __zoxide_zi(args: List[str]):
"""Jump to a directory using interactive search."""
2020-10-20 23:29:28 +05:30
try:
2021-03-30 18:44:29 +05:30
zoxide = __zoxide_bin()
2020-11-11 00:41:26 +05:30
__zoxide_cmd = subprocess.run(
2021-03-30 18:44:29 +05:30
[zoxide, "query", "-i", "--"] + args, check=True, stdout=subprocess.PIPE
2020-11-11 00:41:26 +05:30
)
except CalledProcessError as exc:
raise ZoxideSilentException() from exc
2020-10-20 23:29:28 +05:30
2020-11-11 00:41:26 +05:30
__zoxide_result = __zoxide_cmd.stdout[:-1]
2020-10-20 23:29:28 +05:30
__zoxide_cd(__zoxide_result)
2020-10-18 14:52:13 +05:30
2021-04-09 00:05:42 +05:30
{{ section }}
2020-10-18 14:52:13 +05:30
# Convenient aliases for zoxide. Disable these using --no-aliases.
#
{%- match cmd %}
{%- when Some with (cmd) %}
2020-11-11 00:41:26 +05:30
aliases["{{cmd}}"] = __zoxide_z
aliases["{{cmd}}i"] = __zoxide_zi
2020-10-18 14:52:13 +05:30
{%- when None %}
2021-04-09 00:05:42 +05:30
{{ not_configured }}
2020-10-18 14:52:13 +05:30
{%- endmatch %}
2021-04-09 00:05:42 +05:30
{{ section }}
2021-04-27 17:37:38 +05:30
# To initialize zoxide, add this to your configuration (usually ~/.xonshrc):
2020-10-18 14:52:13 +05:30
#
# execx($(zoxide init xonsh), 'exec', __xonsh__.ctx, filename='zoxide')