Skip to content

Commit

Permalink
Simplify my JSON between Rust and Bash
Browse files Browse the repository at this point in the history
  • Loading branch information
tesujimath committed Aug 22, 2024
1 parent 58575bf commit 74d7e4d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
12 changes: 6 additions & 6 deletions scripts/bash_env.sh
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,19 @@ function send_environment() {
_tail=("$@")

# header
echo -n "{\"Value\":{\"Record\":{\"val\":{"
echo -n "{\"Env\":["

# names and values
if test $_n_env -gt 0; then
echo -n "\"$_head\":{\"String\":{\"val\":"
echo -n "{\"k\":\"$_head\",\"v\":"
send_value "${!_head}"
echo -n ",\"span\":{\"start\":0,\"end\":0}}}"
echo -n "}"

for _name in "${_tail[@]}"; do
if test -v "$_name"; then
echo -n ",\"$_name\":{\"String\":{\"val\":"
echo -n ",{\"k\":\"$_name\",\"v\":"
send_value "${!_name}"
echo -n ",\"span\":{\"start\":0,\"end\":0}}}"
echo -n "}"
else
# unset, TODO
:
Expand All @@ -67,7 +67,7 @@ function send_environment() {
fi

# trailer
echo '},"span":{"start":0,"end":0}}}}'
echo ']}'
}

function send_error() {
Expand Down
29 changes: 25 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,14 @@ impl PluginCommand for BashEnv {

debug!("run path={:?} stdin={:?}", &path, stdin);

bash_env(span.unwrap_or(Span::unknown()), stdin, path, cwd)
bash_env(span.unwrap_or(Span::unknown()), call.head, stdin, path, cwd)
.map(|value| value.into_pipeline_data())
}
}

fn bash_env(
input_span: Span,
creation_site_span: Span,
stdin: Option<String>,
path: Option<String>,
cwd: String,
Expand Down Expand Up @@ -141,18 +142,38 @@ fn bash_env(
.map_err(to_labeled)?;
}

match serde_json::from_reader(p.stdout.as_ref().unwrap()).map_err(to_labeled)? {
BashEnvResult::Record(value) => Ok(Value::record(value, input_span)),
match serde_json::from_reader(p.stdout.as_ref().unwrap())
.map_err(|e| create_error(format!("serde_json::from_reader(): {}", e), input_span))?
{
BashEnvResult::Env(env) => Ok(create_record(env, input_span, creation_site_span)),
BashEnvResult::Error(msg) => Err(create_error(msg, Span::unknown())),
}
}

fn create_record(env: Vec<KV>, input_span: Span, creation_site_span: Span) -> Value {
let cols = env.iter().map(|kv| kv.k.clone()).collect::<Vec<_>>();
let vals = env
.iter()
.map(|kv| Value::string(kv.v.clone(), Span::unknown()))
.collect::<Vec<_>>();
Value::record(
Record::from_raw_cols_vals(cols, vals, input_span, creation_site_span).unwrap(),
input_span,
)
}

#[derive(Serialize, Deserialize)]
enum BashEnvResult {
Record(Record),
Env(Vec<KV>),
Error(String),
}

#[derive(Serialize, Deserialize)]
struct KV {
k: String,
v: String,
}

fn create_error<S>(msg: S, creation_site_span: Span) -> LabeledError
where
S: Into<String>,
Expand Down

0 comments on commit 74d7e4d

Please sign in to comment.