Skip to content

Instantly share code, notes, and snippets.

@drannex42
Last active October 29, 2024 16:14
Show Gist options
  • Save drannex42/9a0e9ae306872e4dcd747edfa90582d9 to your computer and use it in GitHub Desktop.
Save drannex42/9a0e9ae306872e4dcd747edfa90582d9 to your computer and use it in GitHub Desktop.
Environment File (.env) Reader [Odin]
// Two options:
// Option 1: set a struct that stores the values,
// Option 2: Use the native Environment Variable options:
// https://pkg.odin-lang.org/core/os/#set_env
// Option 1:
Global_Env :: struct {
USER: string,
PWD: string
}
// Option 1:
global: Global_Env = {}
check_env :: proc() -> bool {
env_file, env_status := os.read_entire_file_from_filename(".env")
if env_status {
env := strings.split_lines(transmute(string)env_file)
defer delete(env)
for item in env {
item := strings.split_n(item, "=", 2)
defer delete(item)
switch {
case item[0] == "PWD":
fmt.println("[ Config :: Env ] PWD Set")
// Option 2: set_env(item[0], item[1])
global.pwd = item[1]
case item[0] == "USER":
fmt.println("[ Config :: Env ] USER Set =", item[1])
// Option 2: set_env(item[0], item[1])
global.user = item[1]
}
}
return true
} else {
fmt.printf(
ansi.CSI + ansi.BOLD + ";" + ansi.FG_RED + ansi.SGR + \
"No environment file detected" \
+ ansi.CSI + ansi.RESET + ansi.SGR
)
return false
}
}
// .env
// USER=drannex42
// PWD=totally_secret_pwd_that_can_include_=_and_any_other_character
@drannex42
Copy link
Author

drannex42 commented Oct 29, 2024

You could, should, probably check against an enum and set the value accordingly, but I didn't here as it doesn't quite fit with my current system.

You could also set them to an environment value, I'm not entirely keen on this model, but it's an option, I've included it above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment