1#![doc = include_str!("../README.md")]
2
3use clap::ValueEnum;
4use es_fluent_derive_core::namer::FluentKey;
5use es_fluent_derive_core::registry::{FtlTypeInfo, FtlVariant};
6use fluent_syntax::{ast, parser};
7use indexmap::IndexMap;
8use std::{fs, path::Path};
9
10pub mod clean;
11pub mod error;
12pub mod formatting;
13pub mod value;
14
15use es_fluent_derive_core::EsFluentResult;
16use value::ValueFormatter;
17
18#[derive(Clone, Debug, Default, PartialEq, ValueEnum)]
20pub enum FluentParseMode {
21 Aggressive,
23 #[default]
25 Conservative,
26}
27
28impl std::fmt::Display for FluentParseMode {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 match self {
31 Self::Aggressive => write!(f, "aggressive"),
32 Self::Conservative => write!(f, "conservative"),
33 }
34 }
35}
36
37#[derive(Clone, Debug, Eq, Hash, PartialEq)]
39struct OwnedVariant {
40 name: String,
41 ftl_key: String,
42 args: Vec<String>,
43}
44
45impl From<&FtlVariant> for OwnedVariant {
46 fn from(v: &FtlVariant) -> Self {
47 Self {
48 name: v.name.to_string(),
49 ftl_key: v.ftl_key.to_string(),
50 args: v.args.iter().map(|s| s.to_string()).collect(),
51 }
52 }
53}
54
55#[derive(Clone, Debug)]
56struct OwnedTypeInfo {
57 type_name: String,
58 variants: Vec<OwnedVariant>,
59}
60
61impl From<&FtlTypeInfo> for OwnedTypeInfo {
62 fn from(info: &FtlTypeInfo) -> Self {
63 Self {
64 type_name: info.type_name.to_string(),
65 variants: info.variants.iter().map(OwnedVariant::from).collect(),
66 }
67 }
68}
69
70pub fn generate<P: AsRef<Path>, M: AsRef<Path>, I: AsRef<FtlTypeInfo>>(
72 crate_name: &str,
73 i18n_path: P,
74 manifest_dir: M,
75 items: &[I],
76 mode: FluentParseMode,
77 dry_run: bool,
78) -> EsFluentResult<bool> {
79 let i18n_path = i18n_path.as_ref();
80 let manifest_dir = manifest_dir.as_ref();
81 let items_ref: Vec<&FtlTypeInfo> = items.iter().map(|i| i.as_ref()).collect();
82
83 let mut namespaced: IndexMap<Option<String>, Vec<&FtlTypeInfo>> = IndexMap::new();
85 for item in &items_ref {
86 let namespace = item.resolved_namespace(manifest_dir);
87 namespaced.entry(namespace).or_default().push(item);
88 }
89
90 let mut any_changed = false;
91
92 for (namespace, ns_items) in namespaced {
93 let (dir_path, file_path) = match namespace {
94 Some(ns) => {
95 let dir = i18n_path.join(crate_name);
97 let file = dir.join(format!("{}.ftl", ns));
98 (dir, file)
99 },
100 None => {
101 (
103 i18n_path.to_path_buf(),
104 i18n_path.join(format!("{}.ftl", crate_name)),
105 )
106 },
107 };
108
109 if !dry_run {
110 fs::create_dir_all(&dir_path)?;
111 }
112
113 let existing_resource = read_existing_resource(&file_path)?;
114
115 let final_resource = if matches!(mode, FluentParseMode::Aggressive) {
116 build_target_resource(&ns_items)
117 } else {
118 smart_merge(existing_resource, &ns_items, MergeBehavior::Append)
119 };
120
121 if write_updated_resource(
122 &file_path,
123 &final_resource,
124 dry_run,
125 formatting::sort_ftl_resource,
126 )? {
127 any_changed = true;
128 }
129 }
130
131 Ok(any_changed)
132}
133
134pub(crate) fn print_diff(old: &str, new: &str) {
135 use colored::Colorize as _;
136 use similar::{ChangeTag, TextDiff};
137
138 let diff = TextDiff::from_lines(old, new);
139
140 for (idx, group) in diff.grouped_ops(3).iter().enumerate() {
141 if idx > 0 {
142 println!("{}", " ...".dimmed());
143 }
144 for op in group {
145 for change in diff.iter_changes(op) {
146 let sign = match change.tag() {
147 ChangeTag::Delete => "-",
148 ChangeTag::Insert => "+",
149 ChangeTag::Equal => " ",
150 };
151 let line = format!("{} {}", sign, change);
152 match change.tag() {
153 ChangeTag::Delete => print!("{}", line.red()),
154 ChangeTag::Insert => print!("{}", line.green()),
155 ChangeTag::Equal => print!("{}", line.dimmed()),
156 }
157 }
158 }
159 }
160}
161
162fn read_existing_resource(file_path: &Path) -> EsFluentResult<ast::Resource<String>> {
167 if !file_path.exists() {
168 return Ok(ast::Resource { body: Vec::new() });
169 }
170
171 let content = fs::read_to_string(file_path)?;
172 if content.trim().is_empty() {
173 return Ok(ast::Resource { body: Vec::new() });
174 }
175
176 match parser::parse(content) {
177 Ok(res) => Ok(res),
178 Err((res, errors)) => {
179 tracing::warn!(
180 "Warning: Encountered parsing errors in {}: {:?}",
181 file_path.display(),
182 errors
183 );
184 Ok(res)
185 },
186 }
187}
188
189fn write_updated_resource(
193 file_path: &Path,
194 resource: &ast::Resource<String>,
195 dry_run: bool,
196 formatter: impl Fn(&ast::Resource<String>) -> String,
197) -> EsFluentResult<bool> {
198 let is_empty = resource.body.is_empty();
199 let final_content = if is_empty {
200 String::new()
201 } else {
202 formatter(resource)
203 };
204
205 let current_content = if file_path.exists() {
206 fs::read_to_string(file_path)?
207 } else {
208 String::new()
209 };
210
211 let has_changed = match is_empty {
213 true => current_content != final_content && !current_content.trim().is_empty(),
214 false => current_content.trim() != final_content.trim(),
215 };
216
217 if !has_changed {
218 log_unchanged(file_path, is_empty, dry_run);
219 return Ok(false);
220 }
221
222 write_or_preview(
223 file_path,
224 ¤t_content,
225 &final_content,
226 is_empty,
227 dry_run,
228 )?;
229 Ok(true)
230}
231
232fn log_unchanged(file_path: &Path, is_empty: bool, dry_run: bool) {
234 if dry_run {
235 return;
236 }
237 let msg = match is_empty {
238 true => format!(
239 "FTL file unchanged (empty or no items): {}",
240 file_path.display()
241 ),
242 false => format!("FTL file unchanged: {}", file_path.display()),
243 };
244 tracing::debug!("{}", msg);
245}
246
247fn write_or_preview(
249 file_path: &Path,
250 current_content: &str,
251 final_content: &str,
252 is_empty: bool,
253 dry_run: bool,
254) -> EsFluentResult<()> {
255 if dry_run {
256 let display_path = fs::canonicalize(file_path).unwrap_or_else(|_| file_path.to_path_buf());
257 let msg = match (is_empty, !current_content.trim().is_empty()) {
258 (true, true) => format!(
259 "Would write empty FTL file (no items): {}",
260 display_path.display()
261 ),
262 (true, false) => format!("Would write empty FTL file: {}", display_path.display()),
263 (false, _) => format!("Would update FTL file: {}", display_path.display()),
264 };
265 println!("{}", msg);
266 print_diff(current_content, final_content);
267 println!();
268 return Ok(());
269 }
270
271 fs::write(file_path, final_content)?;
272 let msg = match is_empty {
273 true => format!("Wrote empty FTL file (no items): {}", file_path.display()),
274 false => format!("Updated FTL file: {}", file_path.display()),
275 };
276 tracing::info!("{}", msg);
277 Ok(())
278}
279
280fn compare_type_infos(a: &OwnedTypeInfo, b: &OwnedTypeInfo) -> std::cmp::Ordering {
282 let a_is_this = a
284 .variants
285 .iter()
286 .any(|v| v.ftl_key.ends_with(FluentKey::THIS_SUFFIX));
287 let b_is_this = b
288 .variants
289 .iter()
290 .any(|v| v.ftl_key.ends_with(FluentKey::THIS_SUFFIX));
291
292 formatting::compare_with_this_priority(a_is_this, &a.type_name, b_is_this, &b.type_name)
293}
294
295#[derive(Clone, Copy, Debug, PartialEq)]
296pub(crate) enum MergeBehavior {
297 Append,
299 Clean,
301}
302
303pub(crate) fn smart_merge(
304 existing: ast::Resource<String>,
305 items: &[&FtlTypeInfo],
306 behavior: MergeBehavior,
307) -> ast::Resource<String> {
308 let mut pending_items = merge_ftl_type_infos(items);
309 pending_items.sort_by(compare_type_infos);
310
311 let mut item_map: IndexMap<String, OwnedTypeInfo> = pending_items
312 .into_iter()
313 .map(|i| (i.type_name.clone(), i))
314 .collect();
315 let mut key_to_group: IndexMap<String, String> = IndexMap::new();
316 for (group_name, info) in &item_map {
317 for variant in &info.variants {
318 key_to_group.insert(variant.ftl_key.clone(), group_name.clone());
319 }
320 }
321 let mut relocated_by_group: IndexMap<String, Vec<ast::Entry<String>>> = IndexMap::new();
322
323 let mut new_body = Vec::new();
324 let mut current_group_name: Option<String> = None;
325 let cleanup = matches!(behavior, MergeBehavior::Clean);
326
327 for entry in existing.body {
328 match entry {
329 ast::Entry::GroupComment(ref comment) => {
330 if let Some(ref old_group) = current_group_name
331 && let Some(info) = item_map.get_mut(old_group)
332 {
333 if matches!(behavior, MergeBehavior::Append) {
335 if let Some(entries) = relocated_by_group.shift_remove(old_group) {
336 new_body.extend(entries);
337 }
338 if !info.variants.is_empty() {
339 for variant in &info.variants {
340 new_body.push(create_message_entry(variant));
341 }
342 }
343 }
344 info.variants.clear();
345 }
346
347 if let Some(content) = comment.content.first() {
348 let trimmed = content.trim();
349 current_group_name = Some(trimmed.to_string());
350 } else {
351 current_group_name = None;
352 }
353
354 let keep_group = if let Some(ref group_name) = current_group_name {
355 !cleanup || item_map.contains_key(group_name)
356 } else {
357 true
358 };
359
360 if keep_group {
361 new_body.push(entry);
362 }
363 },
364 ast::Entry::Message(msg) => {
365 let key = msg.id.name.clone();
366 let mut handled = false;
367 let mut relocate_to: Option<String> = None;
368
369 if let Some(ref group_name) = current_group_name
370 && let Some(info) = item_map.get_mut(group_name)
371 && let Some(idx) = info.variants.iter().position(|v| v.ftl_key == key)
372 {
373 info.variants.remove(idx);
374 handled = true;
375 }
376
377 if !handled
378 && let Some(expected_group) = key_to_group.get(&key)
379 && matches!(behavior, MergeBehavior::Append)
380 && current_group_name.as_deref() != Some(expected_group.as_str())
381 && let Some(info) = item_map.get_mut(expected_group)
382 && let Some(idx) = info.variants.iter().position(|v| v.ftl_key == key)
383 {
384 info.variants.remove(idx);
385 relocate_to = Some(expected_group.clone());
386 }
387
388 if relocate_to.is_none() && !handled {
389 for info in item_map.values_mut() {
390 if let Some(idx) = info.variants.iter().position(|v| v.ftl_key == key) {
391 info.variants.remove(idx);
392 handled = true;
393 break;
394 }
395 }
396 }
397
398 if let Some(group_name) = relocate_to {
399 relocated_by_group
400 .entry(group_name)
401 .or_default()
402 .push(ast::Entry::Message(msg));
403 } else if handled || !cleanup {
404 new_body.push(ast::Entry::Message(msg));
405 }
406 },
407 ast::Entry::Term(ref term) => {
408 let key = format!("{}{}", FluentKey::DELIMITER, term.id.name);
409 let mut handled = false;
410 for info in item_map.values_mut() {
411 if let Some(idx) = info.variants.iter().position(|v| v.ftl_key == key) {
412 info.variants.remove(idx);
413 handled = true;
414 break;
415 }
416 }
417
418 if handled || !cleanup {
419 new_body.push(entry);
420 }
421 },
422 ast::Entry::Junk { .. } => {
423 new_body.push(entry);
424 },
425 _ => {
426 new_body.push(entry);
427 },
428 }
429 }
430
431 if let Some(ref last_group) = current_group_name
433 && let Some(info) = item_map.get_mut(last_group)
434 {
435 if matches!(behavior, MergeBehavior::Append) {
437 if let Some(entries) = relocated_by_group.shift_remove(last_group) {
438 new_body.extend(entries);
439 }
440 if !info.variants.is_empty() {
441 for variant in &info.variants {
442 new_body.push(create_message_entry(variant));
443 }
444 }
445 }
446 info.variants.clear();
447 }
448
449 if matches!(behavior, MergeBehavior::Append) {
451 let mut remaining_groups: Vec<_> = item_map.into_iter().collect();
452 remaining_groups.sort_by(|(_, a), (_, b)| compare_type_infos(a, b));
453
454 for (type_name, info) in remaining_groups {
455 let relocated = relocated_by_group.shift_remove(&type_name);
456 if !info.variants.is_empty() || relocated.is_some() {
457 new_body.push(create_group_comment_entry(&type_name));
458 if let Some(entries) = relocated {
459 new_body.extend(entries);
460 }
461 for variant in info.variants {
462 new_body.push(create_message_entry(&variant));
463 }
464 }
465 }
466 }
467
468 ast::Resource { body: new_body }
469}
470
471fn create_group_comment_entry(type_name: &str) -> ast::Entry<String> {
472 ast::Entry::GroupComment(ast::Comment {
473 content: vec![type_name.to_owned()],
474 })
475}
476
477fn create_message_entry(variant: &OwnedVariant) -> ast::Entry<String> {
478 let message_id = ast::Identifier {
479 name: variant.ftl_key.clone(),
480 };
481
482 let base_value = ValueFormatter::expand(&variant.name);
483
484 let mut elements = vec![ast::PatternElement::TextElement { value: base_value }];
485
486 for arg_name in &variant.args {
487 elements.push(ast::PatternElement::TextElement { value: " ".into() });
488
489 elements.push(ast::PatternElement::Placeable {
490 expression: ast::Expression::Inline(ast::InlineExpression::VariableReference {
491 id: ast::Identifier {
492 name: arg_name.clone(),
493 },
494 }),
495 });
496 }
497
498 let pattern = ast::Pattern { elements };
499
500 ast::Entry::Message(ast::Message {
501 id: message_id,
502 value: Some(pattern),
503 attributes: Vec::new(),
504 comment: None,
505 })
506}
507
508fn merge_ftl_type_infos(items: &[&FtlTypeInfo]) -> Vec<OwnedTypeInfo> {
509 use std::collections::BTreeMap;
510
511 let mut grouped: BTreeMap<String, Vec<OwnedVariant>> = BTreeMap::new();
513
514 for item in items {
515 let entry = grouped.entry(item.type_name.to_string()).or_default();
516 entry.extend(item.variants.iter().map(OwnedVariant::from));
517 }
518
519 grouped
520 .into_iter()
521 .map(|(type_name, mut variants)| {
522 variants.sort_by(|a, b| {
523 let a_is_this = a.ftl_key.ends_with(FluentKey::THIS_SUFFIX);
524 let b_is_this = b.ftl_key.ends_with(FluentKey::THIS_SUFFIX);
525 formatting::compare_with_this_priority(a_is_this, &a.name, b_is_this, &b.name)
526 });
527 variants.dedup();
528
529 OwnedTypeInfo {
530 type_name,
531 variants,
532 }
533 })
534 .collect()
535}
536
537fn build_target_resource(items: &[&FtlTypeInfo]) -> ast::Resource<String> {
538 let items = merge_ftl_type_infos(items);
539 let mut body: Vec<ast::Entry<String>> = Vec::new();
540 let mut sorted_items = items.to_vec();
541 sorted_items.sort_by(compare_type_infos);
542
543 for info in &sorted_items {
544 body.push(create_group_comment_entry(&info.type_name));
545
546 for variant in &info.variants {
547 body.push(create_message_entry(variant));
548 }
549 }
550
551 ast::Resource { body }
552}