|
| 1 | +#![feature(path_try_exists)] |
| 2 | + |
| 3 | +use fluent_bundle::FluentResource; |
| 4 | +use fluent_syntax::parser::ParserError; |
1 | 5 | use rustc_data_structures::sync::Lrc;
|
2 | 6 | use rustc_macros::{Decodable, Encodable};
|
3 | 7 | use rustc_span::Span;
|
4 | 8 | use std::borrow::Cow;
|
5 |
| -use tracing::debug; |
| 9 | +use std::error::Error; |
| 10 | +use std::fmt; |
| 11 | +use std::fs; |
| 12 | +use std::io; |
| 13 | +use std::path::Path; |
| 14 | +use tracing::{instrument, trace}; |
6 | 15 |
|
7 |
| -pub use fluent::{FluentArgs, FluentValue}; |
| 16 | +pub use fluent_bundle::{FluentArgs, FluentError, FluentValue}; |
| 17 | +pub use unic_langid::{langid, LanguageIdentifier}; |
8 | 18 |
|
9 | 19 | static FALLBACK_FLUENT_RESOURCE: &'static str = include_str!("../locales/en-US/diagnostics.ftl");
|
10 | 20 |
|
11 |
| -pub type FluentBundle = fluent::FluentBundle<fluent::FluentResource>; |
| 21 | +pub type FluentBundle = fluent_bundle::FluentBundle<FluentResource>; |
| 22 | + |
| 23 | +#[derive(Debug)] |
| 24 | +pub enum TranslationBundleError { |
| 25 | + /// Failed to read from `.ftl` file. |
| 26 | + ReadFtl(io::Error), |
| 27 | + /// Failed to parse contents of `.ftl` file. |
| 28 | + ParseFtl(ParserError), |
| 29 | + /// Failed to add `FluentResource` to `FluentBundle`. |
| 30 | + AddResource(FluentError), |
| 31 | + /// `$sysroot/share/locale/$locale` does not exist. |
| 32 | + MissingLocale(io::Error), |
| 33 | + /// Cannot read directory entries of `$sysroot/share/locale/$locale`. |
| 34 | + ReadLocalesDir(io::Error), |
| 35 | + /// Cannot read directory entry of `$sysroot/share/locale/$locale`. |
| 36 | + ReadLocalesDirEntry(io::Error), |
| 37 | + /// `$sysroot/share/locale/$locale` is not a directory. |
| 38 | + LocaleIsNotDir, |
| 39 | +} |
| 40 | + |
| 41 | +impl fmt::Display for TranslationBundleError { |
| 42 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 43 | + match self { |
| 44 | + TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e), |
| 45 | + TranslationBundleError::ParseFtl(e) => { |
| 46 | + write!(f, "could not parse ftl file: {}", e) |
| 47 | + } |
| 48 | + TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e), |
| 49 | + TranslationBundleError::MissingLocale(e) => { |
| 50 | + write!(f, "missing locale directory: {}", e) |
| 51 | + } |
| 52 | + TranslationBundleError::ReadLocalesDir(e) => { |
| 53 | + write!(f, "could not read locales dir: {}", e) |
| 54 | + } |
| 55 | + TranslationBundleError::ReadLocalesDirEntry(e) => { |
| 56 | + write!(f, "could not read locales dir entry: {}", e) |
| 57 | + } |
| 58 | + TranslationBundleError::LocaleIsNotDir => { |
| 59 | + write!(f, "`$sysroot/share/locales/$locale` is not a directory") |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl Error for TranslationBundleError { |
| 66 | + fn source(&self) -> Option<&(dyn Error + 'static)> { |
| 67 | + match self { |
| 68 | + TranslationBundleError::ReadFtl(e) => Some(e), |
| 69 | + TranslationBundleError::ParseFtl(e) => Some(e), |
| 70 | + TranslationBundleError::AddResource(e) => Some(e), |
| 71 | + TranslationBundleError::MissingLocale(e) => Some(e), |
| 72 | + TranslationBundleError::ReadLocalesDir(e) => Some(e), |
| 73 | + TranslationBundleError::ReadLocalesDirEntry(e) => Some(e), |
| 74 | + TranslationBundleError::LocaleIsNotDir => None, |
| 75 | + } |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +impl From<(FluentResource, Vec<ParserError>)> for TranslationBundleError { |
| 80 | + fn from((_, mut errs): (FluentResource, Vec<ParserError>)) -> Self { |
| 81 | + TranslationBundleError::ParseFtl(errs.pop().expect("failed ftl parse with no errors")) |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +impl From<Vec<FluentError>> for TranslationBundleError { |
| 86 | + fn from(mut errs: Vec<FluentError>) -> Self { |
| 87 | + TranslationBundleError::AddResource( |
| 88 | + errs.pop().expect("failed adding resource to bundle with no errors"), |
| 89 | + ) |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +/// Returns Fluent bundle with the user's locale resources from |
| 94 | +/// `$sysroot/share/locale/$requested_locale/*.ftl`. |
| 95 | +/// |
| 96 | +/// If `-Z additional-ftl-path` was provided, load that resource and add it to the bundle |
| 97 | +/// (overriding any conflicting messages). |
| 98 | +#[instrument(level = "trace")] |
| 99 | +pub fn fluent_bundle( |
| 100 | + sysroot: &Path, |
| 101 | + requested_locale: Option<LanguageIdentifier>, |
| 102 | + additional_ftl_path: Option<&Path>, |
| 103 | +) -> Result<Option<Lrc<FluentBundle>>, TranslationBundleError> { |
| 104 | + if requested_locale.is_none() && additional_ftl_path.is_none() { |
| 105 | + return Ok(None); |
| 106 | + } |
| 107 | + |
| 108 | + // If there is only `-Z additional-ftl-path`, assume locale is "en-US", otherwise use user |
| 109 | + // provided locale. |
| 110 | + let locale = requested_locale.clone().unwrap_or_else(|| langid!("en-US")); |
| 111 | + trace!(?locale); |
| 112 | + let mut bundle = FluentBundle::new(vec![locale]); |
| 113 | + |
| 114 | + if let Some(requested_locale) = requested_locale { |
| 115 | + let mut sysroot = sysroot.to_path_buf(); |
| 116 | + sysroot.push("share"); |
| 117 | + sysroot.push("locale"); |
| 118 | + sysroot.push(requested_locale.to_string()); |
| 119 | + trace!(?sysroot); |
| 120 | + |
| 121 | + let _ = sysroot.try_exists().map_err(TranslationBundleError::MissingLocale)?; |
| 122 | + |
| 123 | + if !sysroot.is_dir() { |
| 124 | + return Err(TranslationBundleError::LocaleIsNotDir); |
| 125 | + } |
| 126 | + |
| 127 | + for entry in sysroot.read_dir().map_err(TranslationBundleError::ReadLocalesDir)? { |
| 128 | + let entry = entry.map_err(TranslationBundleError::ReadLocalesDirEntry)?; |
| 129 | + let path = entry.path(); |
| 130 | + trace!(?path); |
| 131 | + if path.extension().and_then(|s| s.to_str()) != Some("ftl") { |
| 132 | + trace!("skipping"); |
| 133 | + continue; |
| 134 | + } |
| 135 | + |
| 136 | + let resource_str = fs::read_to_string(path).map_err(TranslationBundleError::ReadFtl)?; |
| 137 | + let resource = |
| 138 | + FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?; |
| 139 | + trace!(?resource); |
| 140 | + bundle.add_resource(resource).map_err(TranslationBundleError::from)?; |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + if let Some(additional_ftl_path) = additional_ftl_path { |
| 145 | + let resource_str = |
| 146 | + fs::read_to_string(additional_ftl_path).map_err(TranslationBundleError::ReadFtl)?; |
| 147 | + let resource = |
| 148 | + FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?; |
| 149 | + trace!(?resource); |
| 150 | + bundle.add_resource_overriding(resource); |
| 151 | + } |
| 152 | + |
| 153 | + let bundle = Lrc::new(bundle); |
| 154 | + Ok(Some(bundle)) |
| 155 | +} |
12 | 156 |
|
13 |
| -/// Return the default `FluentBundle` with standard en-US diagnostic messages. |
14 |
| -pub fn fallback_fluent_bundle() -> Lrc<FluentBundle> { |
15 |
| - let fallback_resource = fluent::FluentResource::try_new(FALLBACK_FLUENT_RESOURCE.to_string()) |
16 |
| - .expect("failed to parse ftl resource"); |
17 |
| - debug!(?fallback_resource); |
18 |
| - let mut fallback_bundle = FluentBundle::new(vec![unic_langid::langid!("en-US")]); |
19 |
| - fallback_bundle.add_resource(fallback_resource).expect("failed to add resource to bundle"); |
| 157 | +/// Return the default `FluentBundle` with standard "en-US" diagnostic messages. |
| 158 | +#[instrument(level = "trace")] |
| 159 | +pub fn fallback_fluent_bundle() -> Result<Lrc<FluentBundle>, TranslationBundleError> { |
| 160 | + let fallback_resource = FluentResource::try_new(FALLBACK_FLUENT_RESOURCE.to_string()) |
| 161 | + .map_err(TranslationBundleError::from)?; |
| 162 | + trace!(?fallback_resource); |
| 163 | + let mut fallback_bundle = FluentBundle::new(vec![langid!("en-US")]); |
| 164 | + fallback_bundle.add_resource(fallback_resource).map_err(TranslationBundleError::from)?; |
20 | 165 | let fallback_bundle = Lrc::new(fallback_bundle);
|
21 |
| - fallback_bundle |
| 166 | + Ok(fallback_bundle) |
22 | 167 | }
|
23 | 168 |
|
24 | 169 | /// Identifier for the Fluent message/attribute corresponding to a diagnostic message.
|
|
0 commit comments