Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 33 additions & 51 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
# Env Loader (envloader)

Shared utility for loading `.env` files when a service is run locally through a runner that does not start in the project directory (one that sets `BUILD_WORKING_DIRECTORY`, such as `bazel run`).
Load `.env` files at startup and restart the process so `init()` functions see them.

Pre-1.0, maintained on a best-effort basis. See [Project status](#project-status).

## Problem

Services are commonly run locally through a build/run tool that launches the process from a sandbox rather than from the project directory. Since the process no longer starts in the project directory, the usual `.env` / `.env.personal` files sitting next to the service aren't automatically picked up — they need to be loaded explicitly at startup. To avoid reimplementing this in every service, the common logic is consolidated here:

1. Check whether `BUILD_WORKING_DIRECTORY` is set (i.e. the runner was invoked from a checkout rather than a sandbox)
2. Build absolute paths to the env files relative to that directory
3. Load them with `godotenv.Overload` so they override any existing env vars
4. Set `ENV_LOADER_LOADED_ENVS=true` to prevent double-loading on restart
Loading `.env` files with `godotenv` directly updates the process environment, but packages whose
`init()` functions or package-level variables were initialized before that point keep the values
they saw at startup. `envloader` works around that by loading the files and then restarting the
process, so the restarted process starts with the loaded values before package initialization.

## Usage

### Typical service

Add a thin wrapper in your service's internal `myappenvloader` package that lists the files it wants to load:

```go
Expand All @@ -33,7 +29,7 @@ func MustLoadEnv(extraFiles ...string) bool {
}
```

Call it at the very top of `main` — before anything else initialises — so that all packages see the loaded environment variables:
Call it as early as possible in the load order, usually within the first few lines of `main` and before anything else initializes, so that all packages see the loaded environment variables:

```go
func main() {
Expand All @@ -46,71 +42,57 @@ There are no implicit defaults: the caller passes exactly the files it wants, in

### Path resolution and missing files

Relative paths resolve against `BUILD_WORKING_DIRECTORY` when it is set (bazel run), and against the process working directory otherwise. Files that do not exist are skipped, so local setups without `.env.personal` work without extra flags. Pass `RequireAll()` when every listed file must exist. A file that exists but cannot be read (for example a directory) panics either way.
Relative paths resolve against `WithBaseDir(dir)`, or against the process working directory when no base directory is set or the base directory is empty. Absolute paths ignore the base directory.

Passing an empty base directory is intentional: `WithBaseDir(os.Getenv("BUILD_WORKING_DIRECTORY"))` uses the variable when a runner provides it and falls back to the working directory when it does not.

### Use with Bazel
Files that do not exist are skipped, so local setups without `.env.personal` work without extra flags. Pass `RequireAll()` when every listed file must exist. A file that exists but cannot be read (for example a directory) panics either way.

Under `bazel run`, the launcher runs the binary from the sandbox and sets `BUILD_WORKING_DIRECTORY` to the directory the command was typed in. The loader uses that as the base directory, so list files relative to where you run it — which for a service is usually its own directory:
### Using with `bazel run`

`bazel run` sets `BUILD_WORKING_DIRECTORY` to the directory the command was run from. Pass it as the base directory:

```go
envloader.MustLoadEnv([]string{
"services/my-service/.env",
"services/my-service/.env.personal",
})
}, envloader.WithBaseDir(os.Getenv("BUILD_WORKING_DIRECTORY")))
```

The files are read from the user's checkout rather than from the runfiles tree, so local edits are picked up on the next run.

That base is the invocation directory, **not** the workspace root. Running `bazel run //services/my-service:my-service` from `services/my-service` resolves `.env` to `services/my-service/.env`; running the same command from the workspace root needs the path spelled out. Outside Bazel, the same relative paths resolve against the process working directory instead.
If `BUILD_WORKING_DIRECTORY` is empty, the loader falls back to the process working directory. `BUILD_WORKSPACE_DIRECTORY` can be used instead when paths should resolve from the repository root.

### Process restart after loading
### Restart after loading

Some services need every subsequently-imported package to see the loaded environment variables. Because Go packages may initialise `init()` functions before `main` runs, the solution is to restart the process via `syscall.Exec` after loading, so the new process inherits the updated environment from the very beginning. This makes calling `MustLoadEnv` as early as possible in `main` especially important.
After loading at least one file, `MustLoadEnv` restarts the process with the updated environment by default. This ensures packages whose `init()` functions already ran see the loaded values. The process is re-executed with the same arguments and environment.

Restarting is what makes the loaded values visible to packages whose `init()` has already run; without it, those packages keep the environment they saw at first start.
Use `NoRestart()` under debuggers (exec detaches Delve or IDE debuggers), in tests, and on platforms without process execution. Automatic restart is not supported on Windows, js/wasm, wasip1/wasm, or other non-Unix platforms; calling `MustLoadEnv` without `NoRestart()` there panics and asks the caller to pass `NoRestart()`.

```go
package myappenvloader

import (
"os"
"syscall"
Loaded files use `godotenv.Overload`, so values in the files override environment variables that were already set.

"github.com/instacart/go-envloader/envloader"
"github.com/instacart/go-testhooks/testhooks"
)

var execFuncHook = testhooks.NewValueHook[func(argv0 string, argv []string, envv []string) error]()

func MustLoadEnv(extraFiles ...string) {
files := append([]string{
".env",
".env.personal",
}, extraFiles...)
if envloader.MustLoadEnv(files) {
executable, _ := os.Executable()
_ = execFuncHook.Apply(syscall.Exec)(executable, os.Args, os.Environ())
}
}
```

The `execFuncHook` allows tests to intercept the `syscall.Exec` call without actually restarting the process.
`ENV_LOADER_LOADED_ENVS` is an internal guard. The loader sets it to `true` before restarting, and the restarted process inherits it so it does not load or restart again. If you set it manually, loading becomes a no-op.

## API

```go
// Option configures MustLoadEnv.
type Option func(*config)

// WithBaseDir sets the directory used to resolve relative paths. An empty
// directory, or omitting the option, uses the process working directory.
func WithBaseDir(dir string) Option

// NoRestart skips the automatic process restart after env files are loaded.
func NoRestart() Option

// RequireAll makes MustLoadEnv panic when any of the given files does not
// exist. Equivalent of Ruby's Dotenv.load!.
func RequireAll() Option

// MustLoadEnv loads the given env files. Relative paths resolve against
// BUILD_WORKING_DIRECTORY when set, otherwise the working directory.
// Missing files are skipped unless RequireAll is passed; any other error
// panics. Returns true if at least one file was loaded, false if already
// loaded or none of the files exist.
// MustLoadEnv loads the given env files, then restarts the process unless
// NoRestart is passed. Relative paths resolve against WithBaseDir or the
// working directory. Missing files are skipped unless RequireAll is passed;
// any other error panics. Returns true if at least one file was loaded, false
// if already loaded or none of the files exist.
func MustLoadEnv(files []string, opts ...Option) bool
```

Expand All @@ -120,7 +102,7 @@ func MustLoadEnv(files []string, opts ...Option) bool
- Panics if a file exists but cannot be read
- Is a no-op if `ENV_LOADER_LOADED_ENVS=true` (already ran in this process)

Pass `RequireAll()` to panic on a missing file instead of skipping it.
Pass `RequireAll()` to panic on a missing file instead of skipping it. Pass `NoRestart()` to keep the current process running after loading.

## Development

Expand Down
74 changes: 65 additions & 9 deletions envloader/envloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package envloader

import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
Expand All @@ -19,6 +20,8 @@ type Option func(*config)

type config struct {
requireAll bool
noRestart bool
baseDir string
}

// RequireAll returns an Option that makes MustLoadEnv panic when any of the
Expand All @@ -29,13 +32,36 @@ func RequireAll() Option {
}
}

// WithBaseDir sets the directory that relative file paths are resolved against.
// An empty directory, or no WithBaseDir option, uses the current working
// directory. Absolute paths ignore the base directory.
//
// This makes it possible to write
// WithBaseDir(os.Getenv("BUILD_WORKING_DIRECTORY")): an empty environment
// variable falls back to the process working directory, while Bazel supplies
// the directory the command was run from.
func WithBaseDir(dir string) Option {
return func(c *config) {
c.baseDir = dir
}
}

// NoRestart disables the process restart after env files are loaded. Use it
// when running under a debugger, in tests, or on Windows.
func NoRestart() Option {
return func(c *config) {
c.noRestart = true
}
}

// MustLoadEnv loads the given env files. Relative paths resolve against
// BUILD_WORKING_DIRECTORY when it is set (bazel run), and against the current
// working directory otherwise. That variable is the directory the command was
// invoked from rather than the workspace root, so the paths are relative to
// where the user ran it. Files that do not exist are skipped unless
// RequireAll is passed; any other error panics. Returns true if at least one
// file was loaded.
// WithBaseDir, or the current working directory when no base directory is set.
// Files that do not exist are skipped unless RequireAll is passed; any other
// error panics. Returns true if at least one file was loaded.
//
// After loading at least one file, MustLoadEnv restarts the process so packages
// whose init functions already ran see the new environment. Pass NoRestart to
// skip that restart.
//
// Loading is skipped once ENV_LOADER_LOADED_ENVS is "true", which the loader
// sets itself so a restarted process does not load the files twice.
Expand All @@ -52,12 +78,26 @@ func loadEnv(files []string, cfg *config) bool {
return false
}

workingDirectory := os.Getenv("BUILD_WORKING_DIRECTORY")
var (
baseDir string
baseDirResolved bool
)
var paths []string
for _, file := range files {
path := file
if workingDirectory != "" && !filepath.IsAbs(path) {
path = filepath.Join(workingDirectory, filepath.FromSlash(path))
if !filepath.IsAbs(path) {
if !baseDirResolved {
baseDir = cfg.baseDir
if baseDir == "" {
var err error
baseDir, err = os.Getwd()
if err != nil {
panic(fmt.Errorf("envloader: resolve working directory: %w", err))
}
}
baseDirResolved = true
}
path = filepath.Join(baseDir, filepath.FromSlash(path))
}

_, err := os.Stat(path)
Expand All @@ -74,9 +114,25 @@ func loadEnv(files []string, cfg *config) bool {
if len(paths) == 0 {
return false
}

// Resolve the executable before loading: on some platforms os.Executable
// consults PATH, and an env file can change PATH.
var executable string
if !cfg.noRestart {
var err error
executable, err = os.Executable()
if err != nil {
panic(fmt.Errorf("envloader: resolve executable: %w", err))
}
}

if err := godotenv.Overload(paths...); err != nil {
panic(err)
}
_ = os.Setenv("ENV_LOADER_LOADED_ENVS", "true")

if !cfg.noRestart {
restartProcess(executable)
}
return true
}
Loading
Loading