fish: added load_env func for loading a .env file

This commit is contained in:
gyoder 2025-06-16 09:14:07 -06:00
parent b98c70a882
commit cb38494256
3 changed files with 93 additions and 25 deletions

View file

@ -18,5 +18,28 @@ set -x PATH /Users/scie/.local/nvim-macos-arm64/bin \
/usr/bin \
/bin
if status is-interactive
# Commands to run in interactive sessions can go here
function source_env
if not test -f .env
echo "No .env file found in current directory"
return 1
end
for line in (cat .env)
set line (string trim -- $line)
# Skip empty lines and comments
if test -z "$line" -o (string sub --start 1 --length 1 "$line") = "#"
continue
end
# Check if line contains =
if string match -q "*=*" "$line"
set parts (string split -m1 '=' "$line")
set var_name $parts[1]
set var_value $parts[2]
# Remove surrounding quotes if present
set var_value (string trim --chars='"' "$var_value")
set var_value (string trim --chars="'" "$var_value")
set -x $var_name $var_value
end
end
end
end

View file

@ -0,0 +1,45 @@
# Copilot Generated
function load_env --description 'Load environment variables from a .env file (defaults to ./.env)'
set -l env_file ".env"
if test (count $argv) -gt 0
set env_file $argv[1]
end
if not test -f "$env_file"
echo "Error: Environment file not found: $env_file" >&2
return 1
end
for line in (cat -- "$env_file")
set -l trimmed (string trim -- "$line")
# Skip empty lines and comments
if test -z "$trimmed"; or string match -q -r "^\s*#" -- "$trimmed"
continue
end
# Only process lines with =
if not string match -q -- '*=*' "$trimmed"
continue
end
# Use regex to extract key and value, and preserve quotes in value
set -l key (string match -r '^[^=]+' "$trimmed")
set -l rest (string match -r '=[\s\S]*$' "$trimmed")
if test -z "$key" -o -z "$rest"
continue
end
set -l key (string trim -- "$key")
set -l value (string trim -- (string sub -s 2 -- "$rest")) # Remove leading '='
# Validate variable name
if not string match -q -r '^[a-zA-Z_][a-zA-Z0-9_]*$' "$key"
echo "Warning: Invalid variable name '$key'. Skipping."
continue
end
# Reconstruct assignment and use eval to preserve value as-is
eval "set -gx $key $value"
end
end