The standard library
Slide 63 of 85
63envThe standard library

Environment variables

hive.env.get(name) answers with a Result<Str, hive.env.EnvironmentError>, since a variable nobody set is an ordinary outcome rather than a crash. It looks in this order, and the first to name the key wins:

  • the .env file beside the executable;
  • the one in the folder the program was started in — which hive run makes the entrypoint's folder;
  • the .env in the parent folder of either;
  • the operating system's environment.

So a value in a nearby .env wins over one exported in the shell. The file is read once, on the first get: blank lines and # comments are skipped, an export prefix is allowed, and a quoted value has its quotes removed. A .env holding anything private belongs in a file only you can read, which hive.file.writeSecret makes.

hive.env.getSecret(name) is the same lookup answering a Secret<Str>. The environment and the .env still hold it as text, but the program's own copy is locked and cannot be printed.

proc main(): void {
	result := hive.env.get("DATABASE_URL")
	if result is Result.Ok(url) {
		echo "DATABASE_URL is {url}"
	} else if result is Result.Error(why) {
		echo "DATABASE_URL is not set: {why.message}"
	}
}
A variable that is a secret
proc main(): void {
	if hive.env.getSecret("API_KEY") is Result.Ok(key) {
		echo "API_KEY has {len(reveal(key))} characters"
	}
}