diff --git a/crankshaft-engine/src/task/input.rs b/crankshaft-engine/src/task/input.rs index 43ffa58..deee7ba 100644 --- a/crankshaft-engine/src/task/input.rs +++ b/crankshaft-engine/src/task/input.rs @@ -1,13 +1,13 @@ //! Task inputs. -mod builder; - -use std::path::PathBuf; - pub use builder::Builder; use tokio::fs::File; use tokio::io::AsyncReadExt; -use url::Url; + +mod builder; +mod contents; + +pub use contents::Contents; /// A type of input. #[derive(Clone, Debug)] @@ -19,23 +19,6 @@ pub enum Type { Directory, } -/// The source of an input. -#[derive(Clone, Debug)] -pub enum Contents { - /// Contents sourced from a URL. - URL(Url), - - /// Contents provided as a string literal. - Literal(String), -} - -impl From for Contents { - fn from(value: PathBuf) -> Self { - let url = Url::from_file_path(value).unwrap_or_else(|_| panic!("Invalid path")); - Contents::URL(url) - } -} - /// An input to a task. #[derive(Clone, Debug)] pub struct Input { @@ -90,7 +73,7 @@ impl Input { pub async fn fetch(&self) -> Vec { match &self.contents { Contents::Literal(content) => content.as_bytes().to_vec(), - Contents::URL(url) => match url.scheme() { + Contents::Url(url) => match url.scheme() { "file" => { // SAFETY: we just checked to ensure this is a file, so // getting the file path should always unwrap. diff --git a/crankshaft-engine/src/task/input/contents.rs b/crankshaft-engine/src/task/input/contents.rs new file mode 100644 index 0000000..e2ba236 --- /dev/null +++ b/crankshaft-engine/src/task/input/contents.rs @@ -0,0 +1,40 @@ +//! Contents of an input. + +use url::Url; + +/// An error related to an input's [`Contents`]. +#[derive(Debug)] +pub enum Error { + /// An error parsing a [`Url`](url::Url). + ParseUrl(url::ParseError), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::ParseUrl(err) => write!(f, "parse url error: {err}"), + } + } +} + +impl std::error::Error for Error {} + +/// A [`Result`](std::result::Result) with an [`Error`]. +pub type Result = std::result::Result; + +/// The source of an input. +#[derive(Clone, Debug)] +pub enum Contents { + /// Contents sourced from a URL. + Url(Url), + + /// Contents provided as a string literal. + Literal(String), +} + +impl Contents { + /// Attempts to create a URL contents from a string slice. + pub fn url_from_str(url: impl AsRef) -> Result { + url.as_ref().parse().map(Self::Url).map_err(Error::ParseUrl) + } +}