andrewchambers / janet-sh

Shorthand shell like functions for janet.
82 stars 6 forks source link

How to capture or redirect stderr? #18

Closed jwhetzel-gpc closed 1 year ago

jwhetzel-gpc commented 1 year ago

Hi! I apologize if this is a really basic question or if it's been answered elsewhere, but I have so far been unable to find janet-sh documentation or any answer in Janet for Mortals. I'm in the process of learning Janet and trying to use janet-sh as an alternate to some of my more simple shell scripts. My understanding is that the $, $< and $<_ macros will stop on an error, but what I'd like to is to allow the error to go through and capture stderr or redirect it somewhere.

For example, running git rev-parse --is-inside-work-tree from a normal shell will return "true" if the current directory is inside of a git worktree or repo, but it will give an error if it's not.

Within janet-sh, I'm trying this:

(use sh)
(def errput @"")
(def output ($< git rev-parse --is-inside-work-tree >, [stderr errput]))
(prin output)
(prin errput)

Running it outside of a git repo/worktree, it's giving this error:

error: command(s) (@[git rev-parse --is-inside-work-tree :> (<core/file 0x600003B7C620> @"fatal: not a git repository (or 
any parent up to mount point /Volumes)\nStopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not 
set).\n")]) failed, exit code(s) @[128]
    in $<* [/opt/homebrew/Cellar/janet/1.27.0/lib/janet/sh.janet] on line 282, column 5
    in _thunk [./devel/_git_inarepo] (tailcall) on line 57, column 13

I did see #17 but since I'm not trying to send stderr to stdout, I wasn't sure that it was applicable.

I don't want the Janet script to fail when running the shell command, but I'm not sure what I'm supposed to do. Can anyone point me in the right direction? Thanks.

ianthehenry commented 1 year ago

Yeah, if you want to capture stdout and allow non-zero exits, you need to use an explicit redirection and one of the $? or run macros. (Though you will have to string/strim yourself to duplicate the behavior of $<_ with a non-zero exit code, if you want that.)

Try something like this:

(use sh)
(def errput @"")
(def output @"")
($? git rev-parse --is-inside-work-tree >,output >[stderr errput])
(prin output)
(prin errput)
jwhetzel-gpc commented 1 year ago

Ah, thank you, @ianthehenry! That works.