Skip to content

proposal: cmd/vet: warn if cmd.Dir is set after calling cmd.Environ #63782

Description

@cherrymui

Suppose cmd is a *os/exec.Command. On platforms that uses the PWD environment variable (non-Windows non-Plan 9 platforms), cmd.Environ sets PWD if cmd.Dir is set and cmd.Env is not already set. cmd.Environ has an example suggests that cmd.Dir should be set before calling cmd.Environ. But this is not enforced.

cmd.Environ is usually used to set cmd.Env. If that is done before cmd.Dir is set, the PWD environment variable will not be set correctly. Many programs probably don't care about PWD. But for ones that do care, this may lead to subtle and surprising behavior, e.g. how symlinks are handled.

It would be nice if we can have a way to check cmd.Dir is set after calling cmd.Environ. Ideally that check only fires if cmd.Environ is called for setting cmd.Env (probably most of them are).

It would be nice if we can also handle functions wrapping cmd.Environ, like internal/testenv.CleanCmdEnv. Not sure how hard the implementation will be.

One downside for this is that many programs probably don't care about PWD, so setting cmd.Dir after would not lead to incorrect behavior. On the other hand, cmd.Environ is relatively new (added in Go 1.19), so maybe only programs that this matters use cmd.Environ?

This is from a discussion on CL 535915. cc @bcmills

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status
    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions