Skip to content

env var API could be better #10953

@emidoots

Description

@emidoots

std.os.getenv doesn't work on Windows (see #10952) but I suspect it's what people will find first.

You should probably be using std.process.getEnvVarOwned but:

  1. It's a mouthful, I doubt it'd be clear to a new user of Zig that's the right API to use.
  2. It's usage feels a bit obtuse because of the fact that it returns an error in the case of no such env var:

var free_path = true;
const PATH = process.getEnvVarOwned(self.allocator, "PATH") catch |err| switch (err) {
error.EnvironmentVariableNotFound => blk: {
free_path = false;
break :blk "";
},
else => |e| return e,
};
defer if (free_path) self.allocator.free(PATH);

Solution

I'm not sure how to fix the naming issue, or if that is possible.

Perhaps we could change the function signature to not return an error for EnvironmentVariableNotFound though? Then usage would be just:

const PATH = try process.getEnvVarOwned(self.allocator, "PATH");
if (PATH) self.allocator.free(PATH);

And orelse usage would then just be:

const path = PATH orelse "";

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSolving this issue will likely involve adding new logic or components to the codebase.standard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions