Skip to content

Commit

Permalink
fix: awkward?
Browse files Browse the repository at this point in the history
  • Loading branch information
gadomski committed Nov 1, 2024
1 parent c9bd10a commit bcb3ef2
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 6 deletions.
9 changes: 5 additions & 4 deletions crates/core/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{
Error, FromJson, FromNdjson, Href, Result, SelfHref, ToJson, ToNdjson,
};
use bytes::Bytes;
use stac_types::PathBufOrUrl;
use std::{fmt::Display, path::Path, str::FromStr};

/// The format of STAC data.
Expand Down Expand Up @@ -49,8 +50,8 @@ impl Format {
href: impl Into<Href>,
) -> Result<T> {
let mut href = href.into();
let mut value: T = match href.clone() {
Href::Url(url) => {
let mut value: T = match href.clone().path_buf_or_url() {
PathBufOrUrl::Url(url) => {
#[cfg(feature = "reqwest")]
{
let bytes = reqwest::blocking::get(url)?.bytes()?;
Expand All @@ -61,8 +62,8 @@ impl Format {
return Err(Error::FeatureNotEnabled("reqwest"));
}
}
Href::String(path) => {
let path = Path::new(&path).canonicalize()?;
PathBufOrUrl::PathBuf(path) => {
let path = path.canonicalize()?;
let value = self.from_path(&path)?;
href = path.as_path().into();
value
Expand Down
31 changes: 30 additions & 1 deletion crates/types/src/href.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::{fmt::Display, path::Path};
use std::{
fmt::Display,
path::{Path, PathBuf},
};
use url::Url;

/// An href.
Expand All @@ -17,6 +20,16 @@ pub enum Href {
/// This is expected to have `/` delimiters. Windows-style `\` delimiters are not supported.
String(String),
}

#[derive(Debug)]
pub enum PathBufOrUrl {
/// A path buf
PathBuf(PathBuf),

/// A url
Url(Url),
}

/// Implemented by all three STAC objects, the [SelfHref] trait allows getting
/// and setting an object's href.
///
Expand Down Expand Up @@ -126,6 +139,22 @@ impl Href {
Href::String(s) => s.as_str(),
}
}

/// If the url scheme is `file`, convert it to a path string.
pub fn path_buf_or_url(self) -> PathBufOrUrl {
match self {
Href::Url(url) => {
if url.scheme() == "file" {
url.to_file_path()
.map(PathBufOrUrl::PathBuf)
.unwrap_or_else(|_| PathBufOrUrl::Url(url))
} else {
PathBufOrUrl::Url(url)
}
}
Href::String(s) => PathBufOrUrl::PathBuf(PathBuf::from(s)),
}
}
}

impl Display for Href {
Expand Down
2 changes: 1 addition & 1 deletion crates/types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub type Result<T> = std::result::Result<T, Error>;
pub use {
error::Error,
fields::Fields,
href::{Href, SelfHref},
href::{Href, PathBufOrUrl, SelfHref},
link::{Link, Links},
migrate::Migrate,
version::Version,
Expand Down

0 comments on commit bcb3ef2

Please sign in to comment.