synek317 / shellfn

Rust proc macro for easily and safely use shell scripts in rust
MIT License
208 stars 4 forks source link

stderr handling #5

Closed yaahc closed 4 years ago

yaahc commented 5 years ago

The documentation doesn't seem to mention how shellfn handles stderr. I did some experimenting and it looked like stderr is just inherited and goes straight to the terminal. It would be nice if stderr could be captured and suppressed or handled however the caller desires.

Heres the example I played with.

#[shell]
fn get_temp_commit(local: &str) -> Result<String, Box<std::error::Error>> {
    r#"
    cd $LOCAL || exit 1

    function finalize() {
        code=$?
        git reset --soft HEAD~ >>/tmp/tempcommit.log 2>&1 && git reset HEAD . >>/tmp/tempcommit.log 2>&1
        [ $code -eq 0 ] || cat /tmp/tempcommit.log >&2
    }

    git add . &&
        git commit -n -m "gsync temp" --allow-empty >/tmp/tempcommit.log 2>&1 || exit 1

    trap finalize EXIT

    git rev-parse HEAD || exit 1
"#
}

What I'm trying to do is make a temporary commit and return the sha, and if there's an error I would like to have an informative error message. My first attempt was to pipe all stdout output other than the sha itself to stderr with the assumption that the Box type returned by shellfn would somehow contain that stderr content which I could print to act as an informative error message. Instead, all of that output went to the terminal, I got the sha correctly, but it caused a lot of output I didn't want to see. So I hacked around it by piping all that output to a temp file and cating that to stderr if the script exited with an error status.

In the past, I've been using the shells crate which has the following Error type, https://docs.rs/shells/0.2.0/shells/struct.Error.html. Having an option to get an error vaguely like this would be useful I think.