mage
mage copied to clipboard
Add sh.ExecFrom command
Allow specifying the running directory of command in fully backwards-compatible way by using sh.ExecFrom
.
Looks like this closes https://github.com/magefile/mage/issues/213 (was not aware of this issue when I created the PR)
Possible workaround: https://github.com/magefile/mage/issues/213#issuecomment-803208849
@natefinch any update on this?
I think it would be nice to have a sh.RunFrom
function too.
I guess adding all the Run
commands with dir support makes sense? Also adding some tests
Is there interest in moving this forward and adding a dir param version for all the Run/Output functions? Meaning:
sh.RunFrom
sh.RunFromV
sh.RunWithFrom
sh.RunWithFromV
sh.OutputFrom
sh.OutputWithFrom
I'd be happy to do this, if people feel that's the right approach.
My 2 cents:
ExecFrom seems ok, but I would be very hesitant to add 6 more Run/Output functions. Especially since next time this happens it would be 12 more.
I think it should be possible to come up with something better on that part. Perhaps a Run function that takes options, such that only one is needed instead of 6, something like this:
sh.Options(sh.Verbose, sh.WorkDir(x), sh.Env(map[string]string{"x":"y"})).Run("sh", "-c", "pwd;env")
sh.Options(sh.Stdout(wout), sh.Stderr(werr)).Run("echo", "hello")
Perhaps a PR isn't the place to discuss this though. But if this PR goes in, I'd rather it be only the ExecFrom than also adding Run functions.
Yeah, I agree. Adding more and more variations can't be the way to do it. At some point you should just use os/exec. But we can try to brainstorm new ways, too (since there's a lot we can do better than os/exec)
@natefinch In case it's helpful, I've been using a builder pattern so that there isn't an endless combination of arguments. So instead of needing to build up a command perfectly the first time, you can successively modify the command until you are ready to finally call Run on it.
shx.Command("go", "run", "test_main.go").In(tmp).RunV()
You can modify the directory, set additional arguments, collapse any empty arguments (e.g. if you only conditionally set a flag), set the command to fail mage if the command fails (similar to set -euo in bash), set env vars and more.
Here's the implementation below. I'd be happy to contribute it upstream if there's interest. https://github.com/carolynvs/magex/blob/main/shx/prepared_command.go
Similar approach as @carolynvs here for reference: https://github.com/DavidGamba/dgtools/tree/master/run