Skip to content

Instantly share code, notes, and snippets.

@brglng
Last active May 22, 2025 06:37
Show Gist options
  • Save brglng/c741e652293a4bd4dc5c1d01d23ec90e to your computer and use it in GitHub Desktop.
Save brglng/c741e652293a4bd4dc5c1d01d23ec90e to your computer and use it in GitHub Desktop.
Use Pixi in Nushell to replace direnv
$env.config = {
hooks: {
pre_prompt: [{
# Search for pixi.toml in the current directory and all parent directories
mut project_root = $env.PWD
while not ([$project_root, "pixi.toml"] | path join | path exists) {
let new_project_root = [$project_root, ".."] | path join | path expand -n
if $new_project_root == $project_root {
break
}
$project_root = $new_project_root
}
let found_project = [$project_root, "pixi.toml"] | path join | path exists
export-env {
if ("PIXI_IN_SHELL" in $env) and $env.PIXI_IN_SHELL == "1" { # and (not $found_project or $env.PIXI_PROJECT_ROOT != $project_root) {
# Deactivate for every prompt for now, in case any files have changed
# Try to find a better solution in the future
print $"(ansi blue)Deactivating (ansi attr_bold)($env.PIXI_PROJECT_NAME)(ansi reset)"
if "PIXI_OLD_PROMPT" in $env {
$env.PROMPT_COMMAND = $env.PIXI_OLD_PROMPT
hide-env PIXI_OLD_PROMPT
}
if "PIXI_SAVE_ENV" in $env {
$env.PIXI_SAVE_ENV | filter {|e| $e.v != null } | transpose -ird | load-env
$env.PIXI_SAVE_ENV | filter {|e| $e.v == null } | each {|e| $e.k } | hide-env ...$in
hide-env PIXI_SAVE_ENV
}
hide-env PIXI_IN_SHELL
}
if $found_project {
let new_env = pixi shell-hook --json | from json | get environment_variables | default {}
let project_name = if "PIXI_PROJECT_NAME" in $new_env {
$new_env.PIXI_PROJECT_NAME
} else {
# If there is already PIXI_PROJECT_NAME in the environment, pixi shell-hook does not return it,
# so use the one from the existing environment.
$env.PIXI_PROJECT_NAME
}
print $"(ansi blue)Activating (ansi attr_bold)($project_name)(ansi reset)"
let envs_to_save = $new_env | transpose k v | each {|new_e|
if $new_e.k in $env {
{ k: $new_e.k, v: ($env | get $new_e.k) }
} else {
{ k: $new_e.k, v: null }
}
}
$env.PIXI_SAVE_ENV = $envs_to_save
$new_env | load-env
$env.PATH = $env.PATH | split row (char env_sep)
$env.Path = $env.Path | split row (char env_sep)
$env.PIXI_OLD_PROMPT = $env.PROMPT_COMMAND
$env.PROMPT_COMMAND = {||
let old_prompt = (do $env.PIXI_OLD_PROMPT)
if ($old_prompt | str starts-with "\n") {
# If the old prompt starts with a newline, we need to trim it
# This is the case when starship is used and add_newline is set to true in starship.toml
echo $"\n($env.PIXI_PROMPT)($old_prompt | str trim --left)"
} else {
echo $"($env.PIXI_PROMPT)($old_prompt)"
}
}
}
}
}]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment