fetcher.rs (2336B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ 4 5 use l10nregistry::source::{FileFetcher, ResourceId}; 6 7 use std::{borrow::Cow, io}; 8 9 pub struct GeckoFileFetcher; 10 11 fn try_string_from_box_u8(input: Box<[u8]>) -> io::Result<String> { 12 String::from_utf8(input.into()) 13 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err.utf8_error())) 14 } 15 16 // For historical reasons we maintain a locale in Firefox with a codename `ja-JP-mac`. 17 // This string is an invalid BCP-47 language tag, so we don't store it in Gecko, which uses 18 // valid BCP-47 tags only, but rather keep that quirk local to Gecko L10nRegistry file fetcher. 19 // 20 // Here, if we encounter `ja-JP-macos` (valid BCP-47), we swap it for `ja-JP-mac`. 21 // 22 // See bug 1726586 for details, and source::get_locale_from_gecko. 23 fn get_path_for_gecko<'s>(input: &'s str) -> Cow<'s, str> { 24 if input.contains("ja-JP-macos") { 25 input.replace("ja-JP-macos", "ja-JP-mac").into() 26 } else { 27 input.into() 28 } 29 } 30 31 #[async_trait::async_trait(?Send)] 32 impl FileFetcher for GeckoFileFetcher { 33 fn fetch_sync(&self, resource_id: &ResourceId) -> io::Result<String> { 34 let path = get_path_for_gecko(&resource_id.value); 35 crate::load::load_sync(path).and_then(try_string_from_box_u8) 36 } 37 38 async fn fetch(&self, resource_id: &ResourceId) -> io::Result<String> { 39 let path = get_path_for_gecko(&resource_id.value); 40 crate::load::load_async(path) 41 .await 42 .and_then(try_string_from_box_u8) 43 } 44 } 45 46 pub struct MockFileFetcher { 47 fs: Vec<(String, String)>, 48 } 49 50 impl MockFileFetcher { 51 pub fn new(fs: Vec<(String, String)>) -> Self { 52 Self { fs } 53 } 54 } 55 56 #[async_trait::async_trait(?Send)] 57 impl FileFetcher for MockFileFetcher { 58 fn fetch_sync(&self, resource_id: &ResourceId) -> io::Result<String> { 59 for (p, source) in &self.fs { 60 if p == &resource_id.value { 61 return Ok(source.clone()); 62 } 63 } 64 Err(io::Error::new(io::ErrorKind::NotFound, "File not found")) 65 } 66 67 async fn fetch(&self, resource_id: &ResourceId) -> io::Result<String> { 68 self.fetch_sync(resource_id) 69 } 70 }