mirror of
https://github.com/gyoder/dots.git
synced 2026-02-27 17:03:45 +00:00
fish: added load_env func for loading a .env file
This commit is contained in:
parent
b98c70a882
commit
cb38494256
3 changed files with 93 additions and 25 deletions
|
|
@ -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
|
||||
|
|
|
|||
45
fish/.config/fish/functions/load_env.fish
Normal file
45
fish/.config/fish/functions/load_env.fish
Normal 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue