asimov_runner/programs/
fetcher.rs1use crate::{Executor, ExecutorError, GraphOutput, Input};
4use async_trait::async_trait;
5use derive_more::Debug;
6use std::{
7 ffi::OsStr,
8 io::{Cursor, Read},
9 process::Stdio,
10};
11use tokio::io::{AsyncRead, AsyncWrite};
12
13pub use asimov_patterns::FetcherOptions;
14
15pub type FetcherResult = std::result::Result<Cursor<Vec<u8>>, ExecutorError>; #[allow(unused)]
20#[derive(Debug)]
21pub struct Fetcher {
22 executor: Executor,
23 options: FetcherOptions,
24 input: String,
25 output: GraphOutput,
26}
27
28impl Fetcher {
29 pub fn new(
30 program: impl AsRef<OsStr>,
31 input: impl AsRef<str>,
32 output: GraphOutput,
33 options: FetcherOptions,
34 ) -> Self {
35 let input = input.as_ref().to_string();
36 let mut executor = Executor::new(program);
37 executor
38 .command()
39 .args(if let Some(ref output) = options.output {
40 vec![format!("--output={}", output)]
41 } else {
42 vec![]
43 })
44 .args(&options.other)
45 .arg(&input)
46 .stdin(Stdio::null())
47 .stdout(output.as_stdio())
48 .stderr(Stdio::piped());
49
50 Self {
51 executor,
52 options,
53 input,
54 output,
55 }
56 }
57
58 pub async fn execute(&mut self) -> FetcherResult {
59 let stdout = self.executor.execute().await?;
60 Ok(stdout)
61 }
62}
63
64impl asimov_patterns::Fetcher<Cursor<Vec<u8>>, ExecutorError> for Fetcher {}
65
66#[async_trait]
67impl asimov_patterns::Execute<Cursor<Vec<u8>>, ExecutorError> for Fetcher {
68 async fn execute(&mut self) -> FetcherResult {
69 self.execute().await
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use asimov_patterns::Execute;
77
78 #[tokio::test]
79 async fn test_execute() {
80 let mut fetcher = Fetcher::new(
81 "curl",
82 "https://www.google.com/robots.txt",
83 GraphOutput::Ignored,
84 FetcherOptions::default(),
85 );
86 let result = fetcher.execute().await;
87 assert!(result.is_ok());
88 }
89}