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

Correct error types for icu_provider_fs #3682

Merged
merged 2 commits into from
Jul 20, 2023
Merged
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
4 changes: 2 additions & 2 deletions provider/adapters/src/fork/by_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ where
F: ForkByErrorPredicate,
{
fn supported_locales_for_key(&self, key: DataKey) -> Result<Vec<DataLocale>, DataError> {
let mut last_error = DataErrorKind::MissingDataKey.with_key(key);
let mut last_error = F::ERROR.with_key(key);
robertbastian marked this conversation as resolved.
Show resolved Hide resolved
for provider in self.providers.iter() {
let result = provider.supported_locales_for_key(key);
match result {
Expand All @@ -260,7 +260,7 @@ where
key: DataKey,
mut from: DataPayload<MFrom>,
) -> Result<DataPayload<MTo>, (DataPayload<MFrom>, DataError)> {
let mut last_error = DataErrorKind::MissingDataKey.with_key(key);
let mut last_error = F::ERROR.with_key(key);
for provider in self.providers.iter() {
let result = provider.convert(key, from);
match result {
Expand Down
7 changes: 7 additions & 0 deletions provider/adapters/src/fork/predicates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ use icu_provider::prelude::*;
///
/// [`ForkByErrorProvider`]: super::ForkByErrorProvider
pub trait ForkByErrorPredicate {
/// The error to return if there are zero providers.
const ERROR: DataErrorKind = DataErrorKind::MissingDataKey;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: NO_PROVIDER_ERROR_KIND or FALLBACK_ERROR_KIND would be more clear because ForkByErrorPredicate normally uses the predicate function to test its error type.


/// This function is called when a data request fails and there are additional providers
/// that could possibly fulfill the request.
///
Expand Down Expand Up @@ -43,6 +46,8 @@ pub trait ForkByErrorPredicate {
pub struct MissingDataKeyPredicate;

impl ForkByErrorPredicate for MissingDataKeyPredicate {
const ERROR: DataErrorKind = DataErrorKind::MissingDataKey;

#[inline]
fn test(&self, _: DataKey, _: Option<DataRequest>, err: DataError) -> bool {
matches!(
Expand Down Expand Up @@ -125,6 +130,8 @@ impl ForkByErrorPredicate for MissingDataKeyPredicate {
pub struct MissingLocalePredicate;

impl ForkByErrorPredicate for MissingLocalePredicate {
const ERROR: DataErrorKind = DataErrorKind::MissingLocale;

#[inline]
fn test(&self, _: DataKey, _: Option<DataRequest>, err: DataError) -> bool {
matches!(
Expand Down
2 changes: 1 addition & 1 deletion provider/fs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ displaydoc = { version = "0.2.3", default-features = false }
icu_provider = { version = "1.2.0", path = "../core", features = ["serde", "std"] }
serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] }
serde-json-core = { version = "0.4", default-features = false, features = ["std"] }
writeable = { version = "0.5.1", path = "../../utils/writeable" }

# Dependencies for the export feature
bincode = { version = "1.3", optional = true }
Expand All @@ -48,6 +47,7 @@ icu_benchmark_macros = { path = "../../tools/benchmark/macros" }
icu_locid = { path = "../../components/locid", features = ["serde"] }
icu_provider = { path = "../core", features = ["deserialize_json", "deserialize_bincode_1", "deserialize_postcard_1", "datagen"] }
icu_datagen = { path = "../datagen" }
writeable = { path = "../../utils/writeable" }

[features]
# Enables the "export" module and FilesystemExporter
Expand Down
36 changes: 25 additions & 11 deletions provider/fs/src/export/fs_exporter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ use crate::manifest::Manifest;
use icu_provider::datagen::*;
use icu_provider::prelude::*;
use serde::{Deserialize, Serialize};
use std::fmt::Write;
use std::fs;
#[allow(deprecated)]
// We're using SipHash, which is deprecated, but we want a stable hasher
// (we're fine with it not being cryptographically secure since we're just using it to track diffs)
use std::hash::{Hasher, SipHasher};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use writeable::Writeable;

/// Choices of what to do if [`FilesystemExporter`] tries to write to a pre-existing directory.
#[non_exhaustive]
Expand Down Expand Up @@ -119,15 +119,19 @@ impl DataExporter for FilesystemExporter {
locale: &DataLocale,
obj: &DataPayload<ExportMarker>,
) -> Result<(), DataError> {
let mut path_buf = self.root.clone();
path_buf.push(&*key.write_to_string());
path_buf.push(&*locale.write_to_string());
path_buf.set_extension(self.manifest.file_extension);

if let Some(parent_dir) = path_buf.parent() {
fs::create_dir_all(parent_dir)
.map_err(|e| DataError::from(e).with_path_context(&parent_dir))?;
}
let mut path_buf = self.root.clone().into_os_string();
write!(
&mut path_buf,
"/{key}/{locale}.{}",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issue, here and elsewhere: using / is not good because Windows and other OSes need different separators. That is what PathBuf::push handles for us. I don't think either write! or Path::new fixes it for us since write! is writing directly to a string and Path::new tries to borrow where possible.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apparently this works because Windows tests are not failing. Note that before we used push(&str), which used AsRef<Path> for &str, so the slashes in the str were still forward slashes (and push itself doesn't replace them).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, so before we were appending individual path segments for root, key, and locale, but the key can contain a slash which wasn't being processed.

I wouldn't be surprised if Windows accepts these characters but does some weird handling with them.

@eggrobin and @makotokato are the two ICU4X engineers who routinely use Windows and might be able to provide some insight here.

self.manifest.file_extension
)
.expect("infallible");

#[allow(clippy::unwrap_used)] // has parent by construction
let parent_dir = Path::new(&path_buf).parent().unwrap();

fs::create_dir_all(parent_dir)
.map_err(|e| DataError::from(e).with_path_context(&parent_dir))?;

let mut file = HashingFile {
file: if self.serializer.is_text_format() {
Expand Down Expand Up @@ -163,6 +167,16 @@ impl DataExporter for FilesystemExporter {
Ok(())
}

fn flush_with_fallback(&self, key: DataKey, _: FallbackMode) -> Result<(), DataError> {
let mut path_buf = self.root.clone().into_os_string();
write!(&mut path_buf, "/{key}").expect("infallible");

fs::create_dir_all(&path_buf)
.map_err(|e| DataError::from(e).with_path_context(&path_buf))?;
robertbastian marked this conversation as resolved.
Show resolved Hide resolved

Ok(())
}

fn close(&mut self) -> Result<(), DataError> {
if let Some(fingerprints) = self.fingerprints.as_mut() {
let fingerprints = fingerprints.get_mut().expect("poison");
Expand Down
24 changes: 16 additions & 8 deletions provider/fs/src/fs_data_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
use crate::manifest::Manifest;
use icu_provider::prelude::*;
use std::fmt::Debug;
use std::fmt::Write;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use writeable::Writeable;

/// A data provider that reads ICU4X data from a filesystem directory.
///
Expand Down Expand Up @@ -70,17 +71,24 @@ impl BufferProvider for FsDataProvider {
key: DataKey,
req: DataRequest,
) -> Result<DataResponse<BufferMarker>, DataError> {
let mut path_buf = self.root.join(&*key.write_to_string());
if !path_buf.exists() {
if key.metadata().singleton && !req.locale.is_empty() {
return Err(DataErrorKind::ExtraneousLocale.with_req(key, req));
}
let mut path = self.root.clone().into_os_string();
write!(&mut path, "/{key}").expect("infallible");
if !Path::new(&path).exists() {
return Err(DataErrorKind::MissingDataKey.with_req(key, req));
}
path_buf.push(&*req.locale.write_to_string());
path_buf.set_extension(self.manifest.file_extension);
if !path_buf.exists() {
write!(
&mut path,
"/{}.{}",
req.locale, self.manifest.file_extension
)
.expect("infallible");
if !Path::new(&path).exists() {
return Err(DataErrorKind::MissingLocale.with_req(key, req));
}
let buffer =
fs::read(&path_buf).map_err(|e| DataError::from(e).with_path_context(&path_buf))?;
let buffer = fs::read(&path).map_err(|e| DataError::from(e).with_path_context(&path))?;
let mut metadata = DataResponseMetadata::default();
metadata.buffer_format = Some(self.manifest.buffer_format);
Ok(DataResponse {
Expand Down
Loading