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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use schemars::JsonSchema;
use serde::Deserialize;
use tokio::sync::Mutex;

use crate::error::XcStringsError;
use crate::io::FileStore;
use crate::model::translation::{CompletedTranslation, RejectedTranslation, SubmitResult};
use crate::service::{formatter, merger, parser, validator};
use crate::tools::FileCache;
use crate::tools::parse::CachedFile;
use crate::tools::resolve_file;

fn default_true() -> bool {
    true
}

#[derive(Debug, Deserialize, JsonSchema)]
pub(crate) struct SubmitTranslationsParams {
    /// Path to .xcstrings file (optional if already parsed)
    #[serde(default)]
    pub file_path: Option<String>,
    /// Translations to submit
    pub translations: Vec<CompletedTranslation>,
    /// If true, validate without writing to disk
    #[serde(default)]
    pub dry_run: bool,
    /// If true (default), write accepted translations even when some are rejected.
    /// If false, reject ALL translations when any single one fails validation.
    #[serde(default = "default_true")]
    pub continue_on_error: bool,
}

/// Submit translations: validate, merge, and write back.
pub(crate) async fn handle_submit_translations(
    store: &dyn FileStore,
    cache: &Mutex<FileCache>,
    write_lock: &Mutex<()>,
    params: SubmitTranslationsParams,
) -> Result<serde_json::Value, XcStringsError> {
    let (path, file) = resolve_file(store, cache, params.file_path.as_deref()).await?;

    // Validate all translations against the file
    let rejected = validator::validate_translations(&file, &params.translations);

    // If continue_on_error=false and any rejected, return ALL as rejected without writing
    if !params.continue_on_error && !rejected.is_empty() {
        let all_rejected: Vec<RejectedTranslation> = params
            .translations
            .iter()
            .map(|t| {
                // Find the specific rejection reason, or mark as "batch rejected"
                let reason = rejected
                    .iter()
                    .find(|r| r.key == t.key)
                    .map(|r| r.reason.clone())
                    .unwrap_or_else(|| "batch rejected due to other failures".into());
                RejectedTranslation {
                    key: t.key.clone(),
                    reason,
                }
            })
            .collect();
        let result = SubmitResult {
            accepted: 0,
            rejected: all_rejected,
            dry_run: params.dry_run,
            accepted_keys: Vec::new(),
        };
        return Ok(serde_json::to_value(result)?);
    }

    // Build set of rejected keys to filter them out
    let rejected_keys: std::collections::HashSet<&str> =
        rejected.iter().map(|r| r.key.as_str()).collect();

    let accepted_translations: Vec<&CompletedTranslation> = params
        .translations
        .iter()
        .filter(|t| !rejected_keys.contains(t.key.as_str()))
        .collect();

    let accepted_count = accepted_translations.len();

    if params.dry_run {
        let accepted_key_list: Vec<String> = accepted_translations
            .iter()
            .map(|t| t.key.clone())
            .collect();
        let result = SubmitResult {
            accepted: accepted_count,
            rejected: rejected
                .into_iter()
                .map(|r| RejectedTranslation {
                    key: r.key,
                    reason: r.reason,
                })
                .collect(),
            dry_run: true,
            accepted_keys: accepted_key_list,
        };
        return Ok(serde_json::to_value(result)?);
    }

    if accepted_count == 0 {
        let result = SubmitResult {
            accepted: 0,
            rejected,
            dry_run: false,
            accepted_keys: Vec::new(),
        };
        return Ok(serde_json::to_value(result)?);
    }

    // Acquire write lock for safe concurrent access
    let _write_guard = write_lock.lock().await;

    // Re-read from disk to get latest state and re-validate against fresh file
    let raw = store.read(&path)?;
    let mut fresh_file = parser::parse(&raw)?;

    // Re-validate against fresh file (it may have changed since initial validation)
    let fresh_rejected = validator::validate_translations(&fresh_file, &params.translations);

    // If continue_on_error=false and fresh re-validation rejects anything, abort
    if !params.continue_on_error && !fresh_rejected.is_empty() {
        let mut all_rejected = rejected;
        all_rejected.extend(fresh_rejected);
        let all_keys: Vec<String> = params.translations.iter().map(|t| t.key.clone()).collect();
        let all_rejected_out: Vec<RejectedTranslation> = all_keys
            .into_iter()
            .map(|key| {
                let reason = all_rejected
                    .iter()
                    .find(|r| r.key == key)
                    .map(|r| r.reason.clone())
                    .unwrap_or_else(|| "batch rejected due to other failures".into());
                RejectedTranslation { key, reason }
            })
            .collect();
        let result = SubmitResult {
            accepted: 0,
            rejected: all_rejected_out,
            dry_run: false,
            accepted_keys: Vec::new(),
        };
        return Ok(serde_json::to_value(result)?);
    }

    let fresh_rejected_keys: std::collections::HashSet<&str> =
        fresh_rejected.iter().map(|r| r.key.as_str()).collect();

    let owned: Vec<CompletedTranslation> = accepted_translations
        .into_iter()
        .filter(|t| !fresh_rejected_keys.contains(t.key.as_str()))
        .cloned()
        .collect();

    if owned.is_empty() {
        let mut all_rejected = rejected;
        all_rejected.extend(fresh_rejected);
        let result = SubmitResult {
            accepted: 0,
            rejected: all_rejected,
            dry_run: false,
            accepted_keys: Vec::new(),
        };
        return Ok(serde_json::to_value(result)?);
    }

    let merge_result = merger::merge_translations(&mut fresh_file, &owned);

    // Format and write
    let formatted = formatter::format_xcstrings(&fresh_file)?;
    store.write(&path, &formatted)?;

    // Update cache
    let mtime = store.modified_time(&path)?;
    let mut guard = cache.lock().await;
    guard.insert(
        path.clone(),
        CachedFile {
            path,
            content: fresh_file,
            modified: mtime,
        },
    );

    // Combine all rejections (initial validation + fresh re-validation + merge)
    let mut all_rejected = rejected;
    all_rejected.extend(fresh_rejected);
    all_rejected.extend(merge_result.rejected);

    let result = SubmitResult {
        accepted: merge_result.accepted,
        rejected: all_rejected,
        dry_run: false,
        accepted_keys: merge_result.accepted_keys,
    };

    Ok(serde_json::to_value(result)?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::translation::CompletedTranslation;
    use crate::tools::parse::{ParseParams, handle_parse};
    use crate::tools::test_helpers::{MIXED_SPECIFIER_FIXTURE, MemoryStore, SIMPLE_FIXTURE};
    use std::path::Path;

    #[tokio::test]
    async fn test_submit_dry_run() {
        let store = MemoryStore::new();
        store.add_file("/test/file.xcstrings", SIMPLE_FIXTURE);
        let cache = Mutex::new(FileCache::new());
        let write_lock = Mutex::new(());

        let parse_params = ParseParams {
            file_path: "/test/file.xcstrings".to_string(),
        };
        handle_parse(&store, &cache, parse_params).await.unwrap();

        let params = SubmitTranslationsParams {
            file_path: None,
            translations: vec![CompletedTranslation {
                key: "welcome_message".to_string(),
                locale: "de".to_string(),
                value: "Willkommen in der App".to_string(),
                plural_forms: None,
                substitution_name: None,
            }],
            dry_run: true,
            continue_on_error: true,
        };

        let result = handle_submit_translations(&store, &cache, &write_lock, params)
            .await
            .unwrap();
        assert_eq!(result["dry_run"], true);
        assert_eq!(result["accepted"], 1);

        let content = store
            .get_content(Path::new("/test/file.xcstrings"))
            .unwrap();
        assert!(!content.contains("Willkommen"));
    }

    #[tokio::test]
    async fn test_submit_writes_file() {
        let store = MemoryStore::new();
        store.add_file("/test/file.xcstrings", SIMPLE_FIXTURE);
        let cache = Mutex::new(FileCache::new());
        let write_lock = Mutex::new(());

        let parse_params = ParseParams {
            file_path: "/test/file.xcstrings".to_string(),
        };
        handle_parse(&store, &cache, parse_params).await.unwrap();

        let params = SubmitTranslationsParams {
            file_path: None,
            translations: vec![CompletedTranslation {
                key: "welcome_message".to_string(),
                locale: "de".to_string(),
                value: "Willkommen in der App".to_string(),
                plural_forms: None,
                substitution_name: None,
            }],
            dry_run: false,
            continue_on_error: true,
        };

        let result = handle_submit_translations(&store, &cache, &write_lock, params)
            .await
            .unwrap();
        assert_eq!(result["accepted"], 1);
        assert_eq!(result["dry_run"], false);

        let content = store
            .get_content(Path::new("/test/file.xcstrings"))
            .unwrap();
        assert!(content.contains("Willkommen"));
    }

    #[tokio::test]
    async fn test_submit_rejects_invalid_specifier() {
        let store = MemoryStore::new();
        store.add_file("/test/file.xcstrings", MIXED_SPECIFIER_FIXTURE);
        let cache = Mutex::new(FileCache::new());
        let write_lock = Mutex::new(());

        let parse_params = ParseParams {
            file_path: "/test/file.xcstrings".to_string(),
        };
        handle_parse(&store, &cache, parse_params).await.unwrap();

        let params = SubmitTranslationsParams {
            file_path: None,
            translations: vec![CompletedTranslation {
                key: "greeting".to_string(),
                locale: "de".to_string(),
                value: "Hallo".to_string(),
                plural_forms: None,
                substitution_name: None,
            }],
            dry_run: false,
            continue_on_error: true,
        };

        let result = handle_submit_translations(&store, &cache, &write_lock, params)
            .await
            .unwrap();
        assert_eq!(result["accepted"], 0);
        assert!(!result["rejected"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_submit_no_active_file() {
        let store = MemoryStore::new();
        let cache = Mutex::new(FileCache::new());
        let write_lock = Mutex::new(());

        let params = SubmitTranslationsParams {
            file_path: None,
            translations: vec![],
            dry_run: false,
            continue_on_error: true,
        };
        let result = handle_submit_translations(&store, &cache, &write_lock, params).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_continue_on_error_false_rejects_all() {
        let store = MemoryStore::new();
        store.add_file("/test/file.xcstrings", MIXED_SPECIFIER_FIXTURE);
        let cache = Mutex::new(FileCache::new());
        let write_lock = Mutex::new(());

        let parse_params = ParseParams {
            file_path: "/test/file.xcstrings".to_string(),
        };
        handle_parse(&store, &cache, parse_params).await.unwrap();

        let params = SubmitTranslationsParams {
            file_path: None,
            translations: vec![
                CompletedTranslation {
                    key: "greeting".to_string(),
                    locale: "de".to_string(),
                    // Missing %@ — should be rejected
                    value: "Hallo".to_string(),
                    plural_forms: None,
                    substitution_name: None,
                },
                CompletedTranslation {
                    key: "farewell".to_string(),
                    locale: "de".to_string(),
                    value: "Tschuess".to_string(),
                    plural_forms: None,
                    substitution_name: None,
                },
            ],
            dry_run: false,
            continue_on_error: false,
        };

        let result = handle_submit_translations(&store, &cache, &write_lock, params)
            .await
            .unwrap();
        assert_eq!(result["accepted"], 0);
        // All should be rejected (both greeting and farewell)
        assert_eq!(result["rejected"].as_array().unwrap().len(), 2);

        // File should NOT have been written
        let content = store
            .get_content(Path::new("/test/file.xcstrings"))
            .unwrap();
        assert!(!content.contains("Tschuess"));
    }

    #[tokio::test]
    async fn test_continue_on_error_true_writes_valid() {
        let store = MemoryStore::new();
        store.add_file("/test/file.xcstrings", MIXED_SPECIFIER_FIXTURE);
        let cache = Mutex::new(FileCache::new());
        let write_lock = Mutex::new(());

        let parse_params = ParseParams {
            file_path: "/test/file.xcstrings".to_string(),
        };
        handle_parse(&store, &cache, parse_params).await.unwrap();

        let params = SubmitTranslationsParams {
            file_path: None,
            translations: vec![
                CompletedTranslation {
                    key: "greeting".to_string(),
                    locale: "de".to_string(),
                    value: "Hallo".to_string(),
                    plural_forms: None,
                    substitution_name: None,
                },
                CompletedTranslation {
                    key: "farewell".to_string(),
                    locale: "de".to_string(),
                    value: "Tschuess".to_string(),
                    plural_forms: None,
                    substitution_name: None,
                },
            ],
            dry_run: false,
            continue_on_error: true,
        };

        let result = handle_submit_translations(&store, &cache, &write_lock, params)
            .await
            .unwrap();
        // "farewell" accepted, "greeting" rejected (missing %@)
        assert_eq!(result["accepted"], 1);
        assert!(!result["rejected"].as_array().unwrap().is_empty());

        // File should have farewell written
        let content = store
            .get_content(Path::new("/test/file.xcstrings"))
            .unwrap();
        assert!(content.contains("Tschuess"));
    }

    #[tokio::test]
    async fn test_continue_on_error_default_is_true() {
        // Test that deserialization defaults to true
        let json = r#"{
            "translations": [],
            "dry_run": true
        }"#;
        let params: SubmitTranslationsParams = serde_json::from_str(json).unwrap();
        assert!(params.continue_on_error);
    }

    #[tokio::test]
    async fn test_accepted_keys_returned() {
        let store = MemoryStore::new();
        store.add_file("/test/file.xcstrings", SIMPLE_FIXTURE);
        let cache = Mutex::new(FileCache::new());
        let write_lock = Mutex::new(());

        let parse_params = ParseParams {
            file_path: "/test/file.xcstrings".to_string(),
        };
        handle_parse(&store, &cache, parse_params).await.unwrap();

        let params = SubmitTranslationsParams {
            file_path: None,
            translations: vec![CompletedTranslation {
                key: "welcome_message".to_string(),
                locale: "de".to_string(),
                value: "Willkommen in der App".to_string(),
                plural_forms: None,
                substitution_name: None,
            }],
            dry_run: false,
            continue_on_error: true,
        };

        let result = handle_submit_translations(&store, &cache, &write_lock, params)
            .await
            .unwrap();
        let accepted_keys = result["accepted_keys"].as_array().unwrap();
        assert_eq!(accepted_keys.len(), 1);
        assert_eq!(accepted_keys[0], "welcome_message");
    }
}