Skip to content

Commit

Permalink
revise: better handling for URL contents in inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
claymcleod committed Feb 5, 2025
1 parent f39208c commit 2aa95b8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 23 deletions.
29 changes: 6 additions & 23 deletions crankshaft-engine/src/task/input.rs
Original file line number Diff line number Diff line change
@@ -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)]
Expand All @@ -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<PathBuf> 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 {
Expand Down Expand Up @@ -90,7 +73,7 @@ impl Input {
pub async fn fetch(&self) -> Vec<u8> {
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.
Expand Down
40 changes: 40 additions & 0 deletions crankshaft-engine/src/task/input/contents.rs
Original file line number Diff line number Diff line change
@@ -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<T> = std::result::Result<T, Error>;

/// 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<str>) -> Result<Self> {
url.as_ref().parse().map(Self::Url).map_err(Error::ParseUrl)
}
}

0 comments on commit 2aa95b8

Please sign in to comment.