rspolib 0.1.2

PO and MO files manipulation library.
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
use std::borrow::Cow;
use std::fmt;

use unicode_width::UnicodeWidthStr;

use crate::escaping::escape;
use crate::twrapper::wrap;

pub mod moentry;
pub mod poentry;

pub use moentry::MOEntry;
pub use poentry::POEntry;

/// Provides a function `translated` to represent
/// if an entry struct is translated
pub trait Translated {
    fn translated(&self) -> bool;
}

/// Concatenates `msgid` + `EOT` + `msgctxt`
///
/// The MO files spec indicates:
///
/// > Contexts are stored (in MO files) by storing
/// > the concatenation of the context, a EOT byte,
/// > and the original string.
///
/// This trait provides a way to get the string
/// representation of `msgid` + `EOT` + `msgctxt`.
///
/// Function required to generate MO files as
/// the returned value is used as key on the
/// translations table.
pub trait MsgidEotMsgctxt {
    /// Returns `msgid` + (optionally: `EOT` + `msgctxt`)
    fn msgid_eot_msgctxt(&self) -> String;
}

pub(crate) fn maybe_msgid_msgctxt_eot_split<'a>(
    msgid: &'a str,
    msgctxt: &Option<String>,
) -> Cow<'a, str> {
    if let Some(ctx) = msgctxt {
        let mut ret = String::from(ctx);
        ret.reserve(msgid.len() + 1);
        ret.push('\u{4}');
        ret.push_str(msgid);
        ret.into()
    } else {
        msgid.into()
    }
}

fn metadata_msgstr_formatter(
    msgstr: &str,
    _: &str,
    _: usize,
) -> String {
    let mut ret = String::from("msgstr \"\"\n");
    for line in msgstr.lines() {
        ret.push('"');
        ret.push_str(&escape(line));
        ret.push_str(r"\n");
        ret.push('"');
        ret.push('\n');
    }
    ret
}

fn default_mo_entry_msgstr_formatter(
    msgstr: &str,
    delflag: &str,
    wrapwidth: usize,
) -> String {
    POStringField::new(
        "msgstr",
        delflag,
        msgstr.trim_end(),
        "",
        wrapwidth,
    )
    .to_string()
}

fn mo_entry_to_string_with_msgstr_formatter(
    entry: &MOEntry,
    wrapwidth: usize,
    delflag: &str,
    msgstr_formatter: &dyn Fn(&str, &str, usize) -> String,
) -> String {
    let mut ret = String::new();

    if let Some(msgctxt) = &entry.msgctxt {
        ret.push_str(
            &POStringField::new(
                "msgctxt", delflag, msgctxt, "", wrapwidth,
            )
            .to_string(),
        );
    }

    ret.push_str(
        &POStringField::new(
            "msgid",
            delflag,
            &entry.msgid,
            "",
            wrapwidth,
        )
        .to_string(),
    );

    if let Some(msgid_plural) = &entry.msgid_plural {
        ret.push_str(
            &POStringField::new(
                "msgid_plural",
                delflag,
                msgid_plural,
                "",
                wrapwidth,
            )
            .to_string(),
        );
    }

    if entry.msgstr_plural.is_empty() {
        let msgstr = match &entry.msgstr {
            Some(msgstr) => msgstr,
            None => "",
        };
        let formatted_msgstr =
            msgstr_formatter(msgstr, delflag, wrapwidth);
        ret.push_str(&formatted_msgstr);
    } else {
        for (i, msgstr_plural) in
            entry.msgstr_plural.iter().enumerate()
        {
            ret.push_str(
                &POStringField::new(
                    "msgstr",
                    delflag,
                    msgstr_plural,
                    &i.to_string(),
                    wrapwidth,
                )
                .to_string(),
            );
        }
    }

    ret
}

pub(crate) fn mo_entry_to_string(
    entry: &MOEntry,
    wrapwidth: usize,
    delflag: &str,
) -> String {
    mo_entry_to_string_with_msgstr_formatter(
        entry,
        wrapwidth,
        delflag,
        &default_mo_entry_msgstr_formatter,
    )
}

/// Converts a metadata wrapped by a [MOEntry] to a string
/// representation.
///
/// ```rust
/// use rspolib::{
///     mofile,
///     mo_metadata_entry_to_string,
/// };
///
/// let file = mofile("tests-data/all.mo").unwrap();
/// let entry = file.metadata_as_entry();
/// let entry_str = mo_metadata_entry_to_string(&entry);
///
/// assert!(entry_str.starts_with("msgid \"\"\nmsgstr \"\""));
/// ```
pub fn mo_metadata_entry_to_string(entry: &MOEntry) -> String {
    mo_entry_to_string_with_msgstr_formatter(
        entry,
        78,
        "",
        &metadata_msgstr_formatter,
    )
}

/// Converts a metadata wrapped by a [POEntry] to a string
/// representation.
///
/// ```rust
/// use rspolib::{
///     pofile,
///     po_metadata_entry_to_string,
/// };
///
/// let file = pofile("tests-data/all.po").unwrap();
/// let entry = file.metadata_as_entry();
/// let entry_str = po_metadata_entry_to_string(&entry, true);
///
/// assert!(
///     entry_str.starts_with("#, fuzzy\nmsgid \"\"\nmsgstr \"\"")
/// );
/// ```
pub fn po_metadata_entry_to_string(
    entry: &POEntry,
    metadata_is_fuzzy: bool,
) -> String {
    let mut ret = String::new();
    if metadata_is_fuzzy {
        ret.push_str("#, fuzzy\n");
    }
    ret.push_str(&mo_metadata_entry_to_string(&MOEntry::from(entry)));
    ret
}

pub(crate) struct POStringField<'a> {
    fieldname: &'a str,
    delflag: &'a str,
    value: &'a str,
    plural_index: &'a str,
    wrapwidth: usize,
}

impl<'a> POStringField<'a> {
    pub fn new(
        fieldname: &'a str,
        delflag: &'a str,
        value: &'a str,
        plural_index: &'a str,
        wrapwidth: usize,
    ) -> Self {
        Self {
            fieldname,
            delflag,
            value,
            plural_index,
            wrapwidth,
        }
    }
}

#[allow(clippy::needless_lifetimes)]
impl<'a> fmt::Display for POStringField<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut lines = vec!["".to_string()];
        let escaped_value = escape(self.value);

        let repr_plural_index = match self.plural_index.is_empty() {
            false => format!("[{}]", self.plural_index),
            true => "".to_string(),
        };

        // +1 here because of the space between fieldname and value
        let real_width =
            UnicodeWidthStr::width(escaped_value.as_ref())
                + UnicodeWidthStr::width(self.fieldname)
                + 1;
        if real_width > self.wrapwidth {
            let new_lines = wrap(&escaped_value, self.wrapwidth);
            lines.extend(new_lines);
        } else {
            lines = vec![escaped_value.into_owned()];
        }

        // format first line
        let mut ret = format!(
            "{}{}{} \"{}\"\n",
            self.delflag,
            self.fieldname,
            repr_plural_index,
            &lines.remove(0),
        );

        // format other lines
        for line in lines {
            ret.push_str(&format!("{}\"{}\"\n", self.delflag, &line));
        }

        write!(f, "{ret}")
    }
}

/// A struct to compare two entries.
///
/// ```rust
/// use std::cmp::Ordering;
/// use rspolib::{POEntry, EntryCmpByOptions};
///
/// let mut entry1 = POEntry::from("msgid 1");
/// let entry2 = POEntry::from("msgid 2");
///
/// let compare_by_all_fields = EntryCmpByOptions::new();
/// let compare_by_msgid_only = EntryCmpByOptions::new()
///     .by_all(false)
///     .by_msgid(true);
///
/// assert_eq!(entry1.cmp_by(&entry2, &compare_by_msgid_only), Ordering::Less);
/// assert_eq!(entry2.cmp_by(&entry1, &compare_by_msgid_only), Ordering::Greater);
///
/// entry1.msgid = "msgid 2".to_string();
/// assert_eq!(entry1.cmp_by(&entry2, &compare_by_msgid_only), Ordering::Equal);
///
/// entry1.msgstr = Some("msgstr 1".to_string());
/// assert_eq!(entry1.cmp_by(&entry2, &compare_by_msgid_only), Ordering::Equal);
/// assert_eq!(entry1.cmp_by(&entry2, &compare_by_all_fields), Ordering::Greater);
/// ```
pub struct EntryCmpByOptions {
    by_msgid: bool,
    by_msgstr: bool,
    by_msgctxt: bool,
    by_obsolete: bool,
    by_occurrences: bool,
    by_msgid_plural: bool,
    by_msgstr_plural: bool,
    by_flags: bool,
}

impl EntryCmpByOptions {
    /// Creates a instance of [EntryCmpByOptions] with comparisons for all fields enabled
    pub fn new() -> Self {
        Self {
            by_msgid: true,
            by_msgstr: true,
            by_msgctxt: true,
            by_obsolete: true,
            by_occurrences: true,
            by_msgid_plural: true,
            by_msgstr_plural: true,
            by_flags: true,
        }
    }

    pub fn by_msgid(mut self, by_msgid: bool) -> Self {
        self.by_msgid = by_msgid;
        self
    }

    pub fn by_msgstr(mut self, by_msgstr: bool) -> Self {
        self.by_msgstr = by_msgstr;
        self
    }

    pub fn by_msgctxt(mut self, by_msgctxt: bool) -> Self {
        self.by_msgctxt = by_msgctxt;
        self
    }

    pub fn by_obsolete(mut self, by_obsolete: bool) -> Self {
        self.by_obsolete = by_obsolete;
        self
    }

    pub fn by_occurrences(mut self, by_occurrences: bool) -> Self {
        self.by_occurrences = by_occurrences;
        self
    }

    pub fn by_msgid_plural(mut self, by_msgid_plural: bool) -> Self {
        self.by_msgid_plural = by_msgid_plural;
        self
    }

    pub fn by_msgstr_plural(
        mut self,
        by_msgstr_plural: bool,
    ) -> Self {
        self.by_msgstr_plural = by_msgstr_plural;
        self
    }

    pub fn by_flags(mut self, by_flags: bool) -> Self {
        self.by_flags = by_flags;
        self
    }

    pub fn by_all(mut self, by_all: bool) -> Self {
        self.by_msgid = by_all;
        self.by_msgstr = by_all;
        self.by_msgctxt = by_all;
        self.by_obsolete = by_all;
        self.by_occurrences = by_all;
        self.by_msgid_plural = by_all;
        self.by_msgstr_plural = by_all;
        self.by_flags = by_all;
        self
    }
}

impl Default for EntryCmpByOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl From<&Vec<(String, bool)>> for EntryCmpByOptions {
    fn from(options: &Vec<(String, bool)>) -> Self {
        let mut ret = Self::new();
        for (key, value) in options {
            match key.as_str() {
                "msgid" => ret.by_msgid = *value,
                "msgstr" => ret.by_msgstr = *value,
                "msgctxt" => ret.by_msgctxt = *value,
                "obsolete" => ret.by_obsolete = *value,
                "occurrences" => ret.by_occurrences = *value,
                "msgid_plural" => ret.by_msgid_plural = *value,
                "msgstr_plural" => ret.by_msgstr_plural = *value,
                "flags" => ret.by_flags = *value,
                _ => {}
            }
        }
        ret
    }
}