use std::{collections::BTreeMap, fs, io, path::Path};
use serde_json::Value;
use crate::error::{Error, ErrorKind, Result};
#[derive(Debug, Default)]
pub(super) struct Table {
json: BTreeMap<String, Value>,
groups: BTreeMap<String, BTreeMap<String, Value>>,
}
#[derive(Debug, PartialEq)]
pub(super) enum Line<'a> {
Text(&'a str),
Table,
Missing,
}
impl Table {
pub(super) fn load(dir: &Path) -> Result<Self> {
let mut table = Self::default();
for entry in entries(dir)? {
let path = entry.path();
let file_name = entry.file_name();
let Some(name) = file_name.to_str() else {
continue;
};
let kind = entry
.file_type()
.map_err(|error| unreadable(&path, &error))?;
if kind.is_dir() {
if name != "vendor" && is_locale_path_segment(name) {
table.read_groups(&path, name, "")?;
}
} else if kind.is_file()
&& let Some(locale) = name
.strip_suffix(".json")
.filter(|locale| is_locale_path_segment(locale))
{
let value = match read(&path)? {
value @ Value::Object(_) => value,
Value::Array(lines) => Value::Object(
lines
.into_iter()
.enumerate()
.map(|(index, line)| (index.to_string(), line))
.collect(),
),
_ => return Err(invalid(&path)),
};
table.json.insert(locale.to_owned(), value);
}
}
Ok(table)
}
fn read_groups(&mut self, dir: &Path, locale: &str, prefix: &str) -> Result<()> {
for entry in entries(dir)? {
let path = entry.path();
let file_name = entry.file_name();
let Some(name) = file_name.to_str() else {
continue;
};
let kind = entry
.file_type()
.map_err(|error| unreadable(&path, &error))?;
if kind.is_dir() && is_safe_path_segment(name) {
self.read_groups(&path, locale, &format!("{prefix}{name}/"))?;
} else if kind.is_file()
&& let Some(group) = name
.strip_suffix(".json")
.filter(|group| is_safe_path_segment(group))
{
let lines = read(&path)?;
if !matches!(lines, Value::Object(_) | Value::Array(_)) {
return Err(invalid(&path));
}
self.groups
.entry(format!("{prefix}{group}"))
.or_default()
.insert(locale.to_owned(), lines);
}
}
Ok(())
}
pub(super) fn json_line(&self, locale: &str, key: &str) -> Option<&Value> {
self.json
.get(locale)?
.as_object()?
.get(key)
.filter(|value| !value.is_null())
}
pub(super) fn group(&self, group: &str, locale: &str, item: Option<&str>) -> Line<'_> {
let lines = match group {
"*" => self.json.get(locale),
group => self
.groups
.get(group)
.and_then(|locales| locales.get(locale)),
};
match arr_get(lines, item) {
Some(Value::String(text)) => Line::Text(text),
Some(value) if is_table(value) => Line::Table,
_ => Line::Missing,
}
}
}
fn is_locale_path_segment(locale: &str) -> bool {
is_safe_path_segment(locale) && !locale.contains('/')
}
fn is_safe_path_segment(name: &str) -> bool {
!name.is_empty() && !name.contains(['\\', '\0']) && !name.contains("..")
}
fn is_table(value: &Value) -> bool {
matches!(value, Value::Array(items) if !items.is_empty())
|| matches!(value, Value::Object(entries) if !entries.is_empty())
}
fn arr_get<'a>(lines: Option<&'a Value>, key: Option<&str>) -> Option<&'a Value> {
let mut lines = lines?;
let Some(key) = key else {
return Some(lines);
};
if let Some(found) = key_get(lines, key) {
return Some(found);
}
for segment in key.split('.') {
lines = key_get(lines, segment)?;
}
Some(lines)
}
fn key_get<'a>(lines: &'a Value, key: &str) -> Option<&'a Value> {
match lines {
Value::Object(entries) => entries.get(key),
Value::Array(items) => items.get(index(key)?),
_ => None,
}
}
fn index(key: &str) -> Option<usize> {
let index = key.parse::<usize>().ok()?;
(index.to_string() == key).then_some(index)
}
fn entries(dir: &Path) -> Result<Vec<fs::DirEntry>> {
let read = match fs::read_dir(dir) {
Ok(read) => read,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(unreadable(dir, &error)),
};
let mut entries = read
.collect::<std::result::Result<Vec<fs::DirEntry>, io::Error>>()
.map_err(|error| unreadable(dir, &error))?;
entries.sort_by_key(|entry| entry.file_name());
Ok(entries)
}
fn read(path: &Path) -> Result<Value> {
let bytes = fs::read(path).map_err(|error| unreadable(path, &error))?;
serde_json::from_slice(&bytes).map_err(|_| invalid(path))
}
fn invalid(path: &Path) -> Error {
Error::new(
ErrorKind::Load,
format!(
"Translation file [{}] contains an invalid JSON structure.",
path.display()
),
None,
)
}
fn unreadable(path: &Path, error: &io::Error) -> Error {
Error::new(
ErrorKind::Load,
format!(
"Translation path [{}] cannot be read: {error}.",
path.display()
),
None,
)
}
#[cfg(test)]
pub(super) struct TempDir(std::path::PathBuf);
#[cfg(test)]
impl TempDir {
pub(super) fn new(name: &str) -> Self {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let unique = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!(
"oxblade-translate-{}-{unique}-{name}",
std::process::id()
));
Self(dir)
}
pub(super) fn path(&self) -> &Path {
&self.0
}
pub(super) fn write(&self, file: &str, contents: &str) -> &Self {
let path = self.0.join(file);
fs::create_dir_all(path.parent().expect("a temporary file has a parent"))
.expect("create a temporary directory");
fs::write(&path, contents).expect("write a temporary file");
self
}
}
#[cfg(test)]
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn load(files: &[(&str, &str)]) -> Result<Table> {
let dir = TempDir::new("table");
for (file, contents) in files {
dir.write(file, contents);
}
Table::load(dir.path())
}
fn text<'a>(table: &'a Table, group: &str, locale: &str, item: &str) -> Option<&'a str> {
match table.group(group, locale, Some(item)) {
Line::Text(text) => Some(text),
_ => None,
}
}
#[test]
fn reads_every_file_under_the_directory() {
let table = load(&[
("en.json", r#" {"Welcome": "Hello", "n": 5, "nil": null} "#),
("nl.json", "{}"),
("en/messages.json", r#"{"welcome": "Hi", "nested": {"deep": {"key": "Deep"}}, "list": ["zero", "one"]}"#),
("en/auth/passwords.json", r#"{"reset": "Reset"}"#),
("en/auth/deeper/still.json", r#"{"x": "y"}"#),
("en.json.bak", "not json"),
("en/notes.txt", "not json"),
("vendor/pkg/en/messages.json", r#"{"welcome": "Package"}"#),
("vendor/pkg/en.json", r#"{"Welcome": "Package"}"#),
])
.expect("a valid directory");
assert_eq!(text(&table, "messages", "en", "welcome"), Some("Hi"));
assert_eq!(text(&table, "messages", "nl", "welcome"), None);
assert_eq!(text(&table, "auth/passwords", "en", "reset"), Some("Reset"));
assert_eq!(text(&table, "auth/deeper/still", "en", "x"), Some("y"));
assert_eq!(
table.group("pkg/en/messages", "vendor", Some("welcome")),
Line::Missing
);
assert_eq!(table.json_line("vendor", "Welcome"), None);
assert_eq!(table.json_line("pkg", "Welcome"), None);
assert!(matches!(
table.json_line("en", "Welcome"),
Some(Value::String(_))
));
assert!(matches!(table.json_line("en", "n"), Some(Value::Number(_))));
assert_eq!(table.json_line("en", "nil"), None, "null is not set");
assert_eq!(table.json_line("nl", "Welcome"), None);
assert!(
table.json_line("en.json", "x").is_none(),
"only `.json` is a locale file"
);
}
#[test]
fn unsafe_locale_files_are_ignored() {
let table = load(&[
(".json", "not json"),
("bad..locale.json", "not json"),
("bad..locale/messages.json", "not json"),
("en/bad..group/messages.json", "not json"),
])
.expect("unsafe paths are ignored");
assert_eq!(table.json_line("", "x"), None);
assert_eq!(
table.group("messages", "bad..locale", Some("x")),
Line::Missing
);
}
#[cfg(unix)]
#[test]
fn symlinks_inside_the_directory_are_ignored() {
let root = TempDir::new("links");
let external = TempDir::new("external");
external.write("messages.json", r#"{"welcome": "External"}"#);
root.write("en/real.json", r#"{"welcome": "Local"}"#);
std::os::unix::fs::symlink(external.path(), root.path().join("en/external"))
.expect("create a directory symlink");
std::os::unix::fs::symlink(root.path(), root.path().join("en/cycle"))
.expect("create a symlink cycle");
std::os::unix::fs::symlink(
external.path().join("messages.json"),
root.path().join("en/link.json"),
)
.expect("create a file symlink");
let table = Table::load(root.path()).expect("read only the translation tree");
assert_eq!(text(&table, "real", "en", "welcome"), Some("Local"));
assert_eq!(text(&table, "external/messages", "en", "welcome"), None);
assert_eq!(text(&table, "link", "en", "welcome"), None);
}
#[test]
fn invalid_files_are_errors() {
for contents in ["{", "null", r#""text""#, "5", "true"] {
assert!(load(&[("en.json", contents)]).is_err(), "{contents}");
assert!(
load(&[("en/messages.json", contents)]).is_err(),
"{contents}"
);
}
let error = load(&[("en.json", "{")]).unwrap_err();
assert_eq!(error.kind, ErrorKind::Load);
assert!(
error.message.contains("contains an invalid JSON structure"),
"{}",
error.message
);
assert!(load(&[("en.json", "[]"), ("en/list.json", r#"["zero", "one"]"#)]).is_ok());
}
#[test]
fn a_missing_directory_is_empty_and_a_path_that_is_a_file_is_an_error() {
let missing = TempDir::new("missing");
let table = Table::load(&missing.0.join("lang")).expect("a missing directory loads");
assert_eq!(table.json_line("en", "x"), None);
assert_eq!(table.group("messages", "en", Some("x")), Line::Missing);
let file = TempDir::new("file");
file.write("lang", "not a directory");
let error = Table::load(&file.0.join("lang")).expect_err("a file is not a directory");
assert_eq!(error.kind, ErrorKind::Load);
assert!(
error.message.contains("cannot be read"),
"{}",
error.message
);
}
#[test]
fn an_array_in_a_locale_file_is_reached_by_index() {
let table = load(&[("en.json", r#"["zero", "one"]"#)]).expect("valid");
assert_eq!(table.group("*", "en", Some("0")), Line::Text("zero"));
assert_eq!(table.group("*", "en", Some("1")), Line::Text("one"));
assert_eq!(table.group("*", "en", Some("00")), Line::Missing);
assert_eq!(table.group("*", "en", Some("+1")), Line::Missing);
assert_eq!(table.group("*", "en", Some("01")), Line::Missing);
assert_eq!(table.group("*", "en", Some("2")), Line::Missing);
}
#[test]
fn dot_notation_follows_arr_get() {
let table = load(&[
("en/messages.json", r#"{"a": {"b": "nested"}, "a.b": "literal", "list": [{"x": 0}, {"x": 1}], "": {"": "blank"}, "n": null, "zero": 0, "no": false}"#),
])
.expect("valid");
let lookup = |item: &str| table.group("messages", "en", Some(item));
assert_eq!(lookup("a.b"), Line::Text("literal"));
assert_eq!(lookup("list.0.x"), Line::Missing);
assert_eq!(lookup("a"), Line::Table);
assert_eq!(lookup("list"), Line::Table);
assert_eq!(lookup("list.0"), Line::Table);
assert_eq!(lookup("list.01.x"), Line::Missing);
assert_eq!(lookup("list.2"), Line::Missing);
assert_eq!(lookup(""), Line::Table);
assert_eq!(lookup("."), Line::Text("blank"));
assert_eq!(lookup(".."), Line::Missing);
assert_eq!(lookup("n"), Line::Missing);
assert_eq!(lookup("zero"), Line::Missing);
assert_eq!(lookup("no"), Line::Missing);
assert_eq!(
lookup("a.b.c"),
Line::Missing,
"a string has no keys below it"
);
assert_eq!(table.group("messages", "en", None), Line::Table);
assert_eq!(table.group("missing", "en", Some("a")), Line::Missing);
assert_eq!(table.group("*", "en", Some("a")), Line::Missing);
}
#[test]
fn a_literal_key_with_a_dot_is_only_taken_when_present() {
let table = load(&[(
"en/messages.json",
r#"{"a.b": "literal", "a": {"b": "nested"}}"#,
)])
.expect("valid");
assert_eq!(
table.group("messages", "en", Some("a.b")),
Line::Text("literal")
);
let table = load(&[(
"en/messages.json",
r#"{"a": {"b": "nested"}, "a.b.c": "deep literal"}"#,
)])
.expect("valid");
assert_eq!(
table.group("messages", "en", Some("a.b")),
Line::Text("nested")
);
assert_eq!(
table.group("messages", "en", Some("a.b.c")),
Line::Text("deep literal")
);
}
#[test]
fn an_empty_group_is_missing_whatever_its_shape() {
let table = load(&[("en/empty.json", "{}"), ("en/none.json", "[]")]).expect("valid");
assert_eq!(table.group("empty", "en", None), Line::Missing);
assert_eq!(table.group("none", "en", Some("0")), Line::Missing);
}
#[test]
fn a_repeated_key_takes_its_last_value_as_php_decodes_it() {
let table = load(&[("en.json", r#"{"a": "1", "a": "2"}"#)]).expect("valid");
assert_eq!(table.group("*", "en", Some("a")), Line::Text("2"));
}
}