xcstrings-mcp 0.4.0

MCP server for iOS/macOS .xcstrings localization file management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use tracing::warn;

use crate::error::XcStringsError;
use crate::model::specifier::extract_specifiers;
use crate::model::translation::TranslationUnit;
use crate::model::xcstrings::{ExtractionState, TranslationState, XcStringsFile};

/// Extract untranslated strings for a specific locale.
/// Returns `(batch, total_untranslated_count)`.
pub fn get_untranslated(
    file: &XcStringsFile,
    locale: &str,
    batch_size: usize,
    offset: usize,
) -> Result<(Vec<TranslationUnit>, usize), XcStringsError> {
    if locale.is_empty() {
        return Err(XcStringsError::LocaleNotFound("locale is empty".into()));
    }
    if batch_size == 0 || batch_size > 100 {
        return Err(XcStringsError::InvalidBatchSize(format!(
            "batch_size must be 1..=100, got {batch_size}"
        )));
    }

    let mut untranslated = Vec::new();

    // BTreeMap iteration = alphabetical order (deterministic)
    for (key, entry) in &file.strings {
        if !entry.should_translate {
            continue;
        }

        // Skip substitution-only keys (has substitutions but no string_unit).
        // These need plural translation via get_untranslated_plurals, not simple translation.
        // Keys with BOTH string_unit and substitutions are included here for the simple
        // string_unit translation; their substitution plurals are handled separately.
        if let Some(localizations) = &entry.localizations
            && let Some(source_loc) = localizations.get(&file.source_language)
            && source_loc.substitutions.is_some()
            && source_loc.string_unit.is_none()
        {
            warn!(key = %key, "skipping substitution-only key — handled by plural_extractor");
            continue;
        }

        let is_untranslated = match &entry.localizations {
            None => true,
            Some(locs) => match locs.get(locale) {
                None => true,
                Some(loc) => {
                    if let Some(su) = &loc.string_unit {
                        su.state != TranslationState::Translated
                    } else if loc.variations.is_some() {
                        // Has variations — treat as translated for Phase 1
                        false
                    } else {
                        true
                    }
                }
            },
        };

        if !is_untranslated {
            continue;
        }

        // Get source text: from source_language localization, fallback to key name
        let source_text = entry
            .localizations
            .as_ref()
            .and_then(|locs| locs.get(&file.source_language))
            .and_then(|loc| loc.string_unit.as_ref())
            .map(|su| su.value.clone())
            .unwrap_or_else(|| key.clone());

        let specifiers = extract_specifiers(&source_text);
        let format_specifier_strings: Vec<String> =
            specifiers.iter().map(|s| s.raw.clone()).collect();

        let has_plurals = entry
            .localizations
            .as_ref()
            .and_then(|locs| locs.get(&file.source_language))
            .and_then(|loc| loc.variations.as_ref())
            .is_some_and(|v| v.plural.is_some());

        let has_substitutions = entry
            .localizations
            .as_ref()
            .and_then(|locs| locs.get(&file.source_language))
            .and_then(|loc| loc.substitutions.as_ref())
            .is_some();

        untranslated.push(TranslationUnit {
            key: key.clone(),
            source_text,
            target_locale: locale.to_string(),
            comment: entry.comment.clone(),
            format_specifiers: format_specifier_strings,
            has_plurals,
            has_substitutions,
        });
    }

    let total = untranslated.len();

    let batch: Vec<TranslationUnit> = untranslated
        .into_iter()
        .skip(offset)
        .take(batch_size)
        .collect();

    Ok((batch, total))
}

/// Extract strings with `extractionState == Stale`.
/// The `locale` parameter sets `target_locale` on returned units (stale is a key-level
/// property, not locale-specific — all locales return the same stale keys).
/// Returns `(batch, total_stale_count)`.
pub fn get_stale(
    file: &XcStringsFile,
    locale: &str,
    batch_size: usize,
    offset: usize,
) -> Result<(Vec<TranslationUnit>, usize), XcStringsError> {
    if locale.is_empty() {
        return Err(XcStringsError::LocaleNotFound("locale is empty".into()));
    }
    if batch_size == 0 || batch_size > 100 {
        return Err(XcStringsError::InvalidBatchSize(format!(
            "batch_size must be 1..=100, got {batch_size}"
        )));
    }

    let mut stale = Vec::new();

    for (key, entry) in &file.strings {
        if !entry.should_translate {
            continue;
        }

        if entry.extraction_state != Some(ExtractionState::Stale) {
            continue;
        }

        let source_text = entry
            .localizations
            .as_ref()
            .and_then(|locs| locs.get(&file.source_language))
            .and_then(|loc| loc.string_unit.as_ref())
            .map(|su| su.value.clone())
            .unwrap_or_else(|| key.clone());

        let specifiers = extract_specifiers(&source_text);
        let format_specifier_strings: Vec<String> =
            specifiers.iter().map(|s| s.raw.clone()).collect();

        let has_plurals = entry
            .localizations
            .as_ref()
            .and_then(|locs| locs.get(&file.source_language))
            .and_then(|loc| loc.variations.as_ref())
            .is_some_and(|v| v.plural.is_some());

        let has_substitutions = entry
            .localizations
            .as_ref()
            .and_then(|locs| locs.get(&file.source_language))
            .and_then(|loc| loc.substitutions.as_ref())
            .is_some();

        stale.push(TranslationUnit {
            key: key.clone(),
            source_text,
            target_locale: locale.to_string(),
            comment: entry.comment.clone(),
            format_specifiers: format_specifier_strings,
            has_plurals,
            has_substitutions,
        });
    }

    let total = stale.len();

    let batch: Vec<TranslationUnit> = stale.into_iter().skip(offset).take(batch_size).collect();

    Ok((batch, total))
}

#[cfg(test)]
mod tests {
    use indexmap::IndexMap;

    use super::*;
    use crate::model::xcstrings::{Localization, StringEntry, StringUnit, XcStringsFile};

    fn make_file(strings: IndexMap<String, StringEntry>) -> XcStringsFile {
        XcStringsFile {
            source_language: "en".to_string(),
            strings,
            version: "1.0".to_string(),
        }
    }

    fn make_entry(
        source_value: Option<&str>,
        locales: &[(&str, &str, TranslationState)],
    ) -> StringEntry {
        let mut localizations = IndexMap::new();

        if let Some(val) = source_value {
            localizations.insert(
                "en".to_string(),
                Localization {
                    string_unit: Some(StringUnit {
                        state: TranslationState::Translated,
                        value: val.to_string(),
                    }),
                    variations: None,
                    substitutions: None,
                },
            );
        }

        for (locale, value, state) in locales {
            localizations.insert(
                locale.to_string(),
                Localization {
                    string_unit: Some(StringUnit {
                        state: state.clone(),
                        value: value.to_string(),
                    }),
                    variations: None,
                    substitutions: None,
                },
            );
        }

        StringEntry {
            extraction_state: None,
            should_translate: true,
            comment: None,
            localizations: if localizations.is_empty() {
                None
            } else {
                Some(localizations)
            },
        }
    }

    #[test]
    fn test_empty_file() {
        let file = make_file(IndexMap::new());
        let (batch, total) = get_untranslated(&file, "de", 10, 0).unwrap();
        assert!(batch.is_empty());
        assert_eq!(total, 0);
    }

    #[test]
    fn test_basic_untranslated() {
        let content = include_str!("../../tests/fixtures/simple.xcstrings");
        let file: XcStringsFile = serde_json::from_str(content).unwrap();

        // "de" doesn't exist → both translatable keys are untranslated
        let (batch, total) = get_untranslated(&file, "de", 100, 0).unwrap();
        assert_eq!(total, 2);
        assert_eq!(batch.len(), 2);
    }

    #[test]
    fn test_already_translated_skipped() {
        let content = include_str!("../../tests/fixtures/simple.xcstrings");
        let file: XcStringsFile = serde_json::from_str(content).unwrap();

        // "uk" has greeting translated, but welcome_message has no uk locale
        let (batch, total) = get_untranslated(&file, "uk", 100, 0).unwrap();
        assert_eq!(total, 1);
        assert_eq!(batch[0].key, "welcome_message");
    }

    #[test]
    fn test_batch_pagination() {
        let mut strings = IndexMap::new();
        for i in 0..5 {
            strings.insert(
                format!("key_{i}"),
                make_entry(Some(&format!("val {i}")), &[]),
            );
        }
        let file = make_file(strings);

        let (batch, total) = get_untranslated(&file, "de", 2, 0).unwrap();
        assert_eq!(total, 5);
        assert_eq!(batch.len(), 2);

        let (batch, _) = get_untranslated(&file, "de", 2, 2).unwrap();
        assert_eq!(batch.len(), 2);

        let (batch, _) = get_untranslated(&file, "de", 2, 4).unwrap();
        assert_eq!(batch.len(), 1);
    }

    #[test]
    fn test_should_not_translate_filtered() {
        let content = include_str!("../../tests/fixtures/should_not_translate.xcstrings");
        let file: XcStringsFile = serde_json::from_str(content).unwrap();

        let (batch, total) = get_untranslated(&file, "de", 100, 0).unwrap();
        assert_eq!(total, 1);
        assert_eq!(batch[0].key, "hello");
    }

    #[test]
    fn test_invalid_batch_size() {
        let file = make_file(IndexMap::new());
        let result = get_untranslated(&file, "de", 0, 0);
        assert!(matches!(
            result.unwrap_err(),
            XcStringsError::InvalidBatchSize(_)
        ));
    }

    #[test]
    fn test_source_text_fallback() {
        let mut strings = IndexMap::new();
        // Entry with no source language localization → key name used as source_text
        strings.insert("my_key".to_string(), make_entry(None, &[]));
        let file = make_file(strings);

        let (batch, _) = get_untranslated(&file, "de", 10, 0).unwrap();
        assert_eq!(batch[0].source_text, "my_key");
    }

    #[test]
    fn test_format_specifiers_extracted() {
        let mut strings = IndexMap::new();
        strings.insert(
            "greet".to_string(),
            make_entry(Some("Hello %@, you have %lld items"), &[]),
        );
        let file = make_file(strings);

        let (batch, _) = get_untranslated(&file, "de", 10, 0).unwrap();
        assert_eq!(batch[0].format_specifiers, vec!["%@", "%lld"]);
    }

    // --- get_stale tests ---

    fn make_stale_entry(source_value: Option<&str>) -> StringEntry {
        let mut entry = make_entry(source_value, &[]);
        entry.extraction_state = Some(ExtractionState::Stale);
        entry
    }

    #[test]
    fn test_stale_no_stale_keys() {
        let mut strings = IndexMap::new();
        strings.insert(
            "key1".to_string(),
            make_entry(
                Some("Hello"),
                &[("de", "Hallo", TranslationState::Translated)],
            ),
        );
        let file = make_file(strings);

        let (batch, total) = get_stale(&file, "de", 10, 0).unwrap();
        assert!(batch.is_empty());
        assert_eq!(total, 0);
    }

    #[test]
    fn test_stale_keys_returned() {
        let mut strings = IndexMap::new();
        strings.insert("stale_key".to_string(), make_stale_entry(Some("Old text")));
        strings.insert("fresh_key".to_string(), make_entry(Some("Fresh"), &[]));
        let file = make_file(strings);

        let (batch, total) = get_stale(&file, "de", 10, 0).unwrap();
        assert_eq!(total, 1);
        assert_eq!(batch.len(), 1);
        assert_eq!(batch[0].key, "stale_key");
        assert_eq!(batch[0].source_text, "Old text");
    }

    #[test]
    fn test_stale_should_not_translate_excluded() {
        let mut strings = IndexMap::new();
        let mut entry = make_stale_entry(Some("Do not translate"));
        entry.should_translate = false;
        strings.insert("no_translate".to_string(), entry);
        strings.insert(
            "stale_ok".to_string(),
            make_stale_entry(Some("Translate me")),
        );
        let file = make_file(strings);

        let (batch, total) = get_stale(&file, "de", 10, 0).unwrap();
        assert_eq!(total, 1);
        assert_eq!(batch[0].key, "stale_ok");
    }

    #[test]
    fn test_stale_batch_pagination() {
        let mut strings = IndexMap::new();
        for i in 0..5 {
            strings.insert(
                format!("stale_{i}"),
                make_stale_entry(Some(&format!("val {i}"))),
            );
        }
        let file = make_file(strings);

        let (batch, total) = get_stale(&file, "de", 2, 0).unwrap();
        assert_eq!(total, 5);
        assert_eq!(batch.len(), 2);

        let (batch, _) = get_stale(&file, "de", 2, 4).unwrap();
        assert_eq!(batch.len(), 1);
    }
}