Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Output implementation for deserializing JSON #218

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@ keywords = ["child", "child-process", "command", "process", "shell"]
categories = ["filesystem", "os"]
exclude = ["/.github"]

[features]
serde = ["dep:serde", "dep:serde_json"]
test_executables = ["nix", "serde"]

[workspace]
members = [".", "context-integration-tests", "memory-tests"]

[dependencies]
rustversion = "1.0.4"
serde = { version = "1.0.196", optional = true }
serde_json = {version = "1.0.113", optional = true }

[dev-dependencies]
executable-path = "1.0.0"
Expand All @@ -31,7 +37,7 @@ bitflags = "=1.2.1"
[[bin]]
name = "test_executables_helper"
path = "src/test_executables/helper.rs"
required-features = ["test_executables"]
required-features = ["test_executables", "serde"]

[[bin]]
name = "test_executables_panic"
Expand All @@ -41,6 +47,3 @@ required-features = ["test_executables"]
[target.'cfg(unix)'.dependencies.nix]
version = "0.22.2"
optional = true

[features]
test_executables = ["nix"]
2 changes: 1 addition & 1 deletion context-integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ edition = "2018"
publish = false

[target.'cfg(unix)'.dependencies]
cradle = { path = ".." }
cradle = { path = "..", features = ["serde"] }
executable-path = "1.0.0"
gag = "0.1.10"
3 changes: 3 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,6 @@ all-rustc-versions *args="ci":
cargo version
just {{ args }}
done

watch +args='test':
cargo watch --clear --exec '{{args}}'
2 changes: 1 addition & 1 deletion memory-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ publish = false

[dependencies]
anyhow = "1.0.42"
cradle = { path = ".." }
cradle = { path = "..", features = ["serde"] }
rustversion = "1.0.5"
2 changes: 1 addition & 1 deletion src/common_re_exports.rs.snippet
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
pub use crate::{
error::Error,
input::{CurrentDir, Env, Input, LogCommand, Split, Stdin},
output::{Output, Status, Stderr, StdoutTrimmed, StdoutUntrimmed},
output::{Output, Status, Stderr, StdoutTrimmed, StdoutUntrimmed, Json},
};
10 changes: 9 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ pub enum Error {
/// }
/// ```
NoExecutableGiven,
Deserialize {
source: serde_json::Error,
},
/// A `file not found` error occurred while trying to spawn
/// the child process:
///
Expand Down Expand Up @@ -58,7 +61,10 @@ pub enum Error {
/// - reading from `stdout` or `stderr` of the child process fails,
/// - writing to the parent's `stdout` or `stderr` fails,
/// - the given executable doesn't have the executable flag set.
CommandIoError { message: String, source: io::Error },
CommandIoError {
message: String,
source: io::Error,
},
/// The child process exited with a non-zero exit code.
///
/// ```
Expand Down Expand Up @@ -176,6 +182,7 @@ impl Display for Error {
use Error::*;
match self {
NoExecutableGiven => write!(f, "no arguments given"),
Deserialize { source } => write!(f, "JSON deserialization failed: {source}"),
FileNotFound { executable, .. } => {
let executable = executable.to_string_lossy();
write!(f, "File not found error when executing '{}'", executable)?;
Expand Down Expand Up @@ -223,6 +230,7 @@ impl std::error::Error for Error {
use Error::*;
match self {
FileNotFound { source, .. } | CommandIoError { source, .. } => Some(source),
Deserialize { source } => Some(source),
InvalidUtf8ToStdout { source, .. } | InvalidUtf8ToStderr { source, .. } => Some(source),
NoExecutableGiven | NonZeroExitCode { .. } | Internal { .. } => None,
}
Expand Down
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1494,4 +1494,20 @@ mod tests {
}
}
}

#[cfg(feature = "serde")]
mod json {
use super::*;

#[test]
fn json_can_be_deserialized() {
let Json(bar): Json<u32> = run_output!("echo", "100");
assert_eq!(bar, 100);
}

#[test]
fn json_errors() {
let result: Result<Json<u32>, Error> = run_result!("echo", "null");
}
}
}
25 changes: 23 additions & 2 deletions src/output.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
//! The [`Output`] trait that defines all possible outputs of a child process.

use crate::{child_output::ChildOutput, config::Config, error::Error};
use std::process::ExitStatus;
use {
crate::{child_output::ChildOutput, config::Config, error::Error},
serde::de::DeserializeOwned,
std::process::ExitStatus,
};

/// All possible return types of [`run!`], [`run_output!`] or
/// [`run_result!`] must implement this trait.
Expand Down Expand Up @@ -177,6 +180,24 @@ impl Output for StdoutTrimmed {
}
}

#[derive(Debug)]
pub struct Json<T: DeserializeOwned>(pub T);

impl<T: DeserializeOwned> Output for Json<T> {
#[doc(hidden)]
fn configure(config: &mut Config) {
StdoutUntrimmed::configure(config);
}

#[doc(hidden)]
fn from_child_output(config: &Config, child_output: &ChildOutput) -> Result<Self, Error> {
let StdoutUntrimmed(stdout) = StdoutUntrimmed::from_child_output(config, child_output)?;
Ok(Self(
serde_json::from_str::<T>(&stdout).map_err(|source| Error::Deserialize { source })?,
))
}
}

/// Same as [`StdoutTrimmed`], but does not trim whitespace from the output:
///
/// ```
Expand Down
Loading