Crate shellfn

Source
Expand description

§Overview

This is a rust attribute-like proc macro which reduces the amount of code required to call shell commands and parse the results.

It allows you to wrap a script in any language with strongly typed functions. The function’s arguments are set as env variables and the result of the script is parsed either as a value or as an iterator.

Crates.io license

Documentation

Repository

§Examples

§Basic

use shellfn::shell;
use std::error::Error;

#[shell]
fn list_modified(dir: &str) -> Result<impl Iterator<Item=String>, Box<Error>> { r#"
    cd $DIR
    git status | grep '^\s*modified:' | awk '{print $2}'
"# }

§Different interpreter

use shellfn::shell;
use std::error::Error;

#[shell(cmd = "python -c")]
fn pretty_json(json: &str, indent: u8, sort_keys: bool) -> Result<String, Box<Error>> { r#"
import os, json

input = os.environ['JSON']
indent = int(os.environ['INDENT'])
sort_keys = os.environ['SORT_KEYS'] == 'true'
obj = json.loads(input)

print(json.dumps(obj, indent=indent, sort_keys=sort_keys))
 "# }

§Usage

You can use the #[shell] attribute on functions that have:

  • a body containing only one expression - a string literal representing the script to execute
  • types that implement the .to_string() method
  • return a value that is either void, T, Result<T, E>, impl Iterator<Item=T>, Result<impl Iterator<Item=T>> or Result<impl Iterator<Item=Result<T, E>>> with constrains:
T: FromStr,
<T as FromStr>::Err: StdError,
E: From<shellfn::Error<<T as FromStr>::Err>>,
  • §Details

The #[shell] attribute does the following:

  1. Sets every argument as an env variable
  2. Runs a shell command
  3. Launches the command using std::process::Command
  4. Depending on the return type, it may parse the output

Most of the steps can be adjusted:

  • the default command is bash -c. You can change it using the cmd parameter:
#[shell(cmd = "python -c")]
  • by default, the script is added as the last argument. You can change it using the special variable PROGRAM in the cmd parameter:
#[shell(cmd = "bash -c PROGRAM -i")]
  • you can use env variables set from function’s arguments in the cmd parameters in the same way as in the script:
#[shell(cmd = "python -m $MODULE")]
fn run(module: &str)
  • if the return type is not wrapping some part of the result in Result, you may decide to suppress panics by adding the no_panic flag:
#[shell(no_panic)]

Following return types are currently recognized:

return typeflagson parse failon error exit codeon spawn failnotes
-panicpanic
no_panic-nothingnothing
()-panicpanic
()no_panic-nothingnothing
Result<(), E>-errorerror
Result<(), E>no_panic-errorerror1
Tpanicpanicpanic2
Tno_panicpanicpanicpanic1,2
Result<T, E>errorerrorerror2
Result<T, E>no_panicerrorerrorerror1,2
Vecpanicpanicpanic
Vecno_panicskipignoredempty vec3
Vec<Result<T, E>>item errorpanicpanic
Vec<Result<T, E>>no_panicitem errorignoredempty vec
Result<Vec, E>panicerrorerror
Result<Vec, E>no_panicskiperrorerror
Result<Vec<Result<T, E1>>, E2>item errorerrorerror
Result<Vec<Result<T, E1>>, E2>no_panicitem errorerrorerror1
impl Iterator<Item=T>panicpanicpanic
impl Iterator<Item=T>no_panicskipignoredempty iter3
impl Iterator<Item=Result<T, E>>item errorpanicpanic3
impl Iterator<Item=Result<T, E>>no_panicitem errorignoredempty iter
Result<impl Iterator<Item=T>, E>panicignorederror
Result<impl Iterator<Item=T>, E>no_panicskipignorederror
Result<impl Iterator<Item=Result<T, E1>>, E2>item errorignorederror
Result<impl Iterator<Item=Result<T, E1>>, E2>no_panicitem errorignorederror1

Glossary:

actionmeaning
panicpanics (.expect or panic!)
nothingconsumes and ignores error (let _ = …)
errorreturns error
skipyields all successfuly parsed items, ignores parsing failures (filter_map)
empty iter/vecreturns empty iterator / vector
item errorwhen parsing fails, yields Err
ignoredignores exit code, behaves in the same way for exit code 0 and != 0

Notes:

  1. The no_panic attribute makes no difference
  2. It reads all of stdout before producing any failures
  3. It yields all items until it encounters an error or an exit code

§Vector vs iterator

Variants with the Vec return type are very similar to the ones with impl Iterator. The key differences are:

  • impl Iterator is only allocating one item at the time and yields it immediately after it is parsed, while Vec is reading output line by line but stores parsed output in the temporary Vec
  • Vec is aware of exit code. When subprocess finishes with error, impl Iterator will stop yielding values while Vec will return error or panic

Enums§

Error

Functions§

execute_iter_nopanic_nopanic
Executes command with args and environment variables, parses output line by line
execute_iter_nopanic_result
Executes command with args and environment variables, parses output line by line
execute_iter_panic_panic
Executes command with args and environment variables, parses output line by line
execute_iter_panic_result
Executes command with args and environment variables, parses output line by line
execute_iter_result_nopanic
Executes command with args and environment variables, parses output line by line
execute_iter_result_panic
Executes command with args and environment variables, parses output line by line
execute_iter_result_result
Executes command with args and environment variables, parses output line by line
execute_parse_panic
Executes command with args and environment variables, parses output
execute_parse_result
Executes command with args and environment variables, parses output
execute_vec_nopanic_nopanic
Executes command with args and environment variables, parses output line by line, returns after reading whole output
execute_vec_nopanic_result
Executes command with args and environment variables, parses output line by line, returns after reading whole output
execute_vec_panic_panic
Executes command with args and environment variables, parses output line by line, returns after reading whole output
execute_vec_panic_result
Executes command with args and environment variables, parses output line by line, returns after reading whole output
execute_vec_result_nopanic
Executes command with args and environment variables, parses output line by line, returns after reading whole output
execute_vec_result_panic
Executes command with args and environment variables, parses output line by line, returns after reading whole output
execute_vec_result_result
Executes command with args and environment variables, parses output line by line, returns after reading whole output
execute_void_nopanic
Executes command with args and environment variables, ignores output
execute_void_panic
Executes command with args and environment variables, ignores output
execute_void_result
Executes command with args and environment variables, ignores output

Attribute Macros§

shell