sd-switch 0.6.2

A systemd unit reload/restart utility for Home Manager
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
use std::fmt::Write as _;
use std::{borrow::Cow, collections::BTreeMap, iter::Peekable, str::Chars};

pub const KEY_REFUSEMANUALSTART: &str = "RefuseManualStart";
pub const KEY_REFUSEMANUALSTOP: &str = "RefuseManualStop";
pub const KEY_X_RELOADIFCHANGED: &str = "X-ReloadIfChanged";
pub const KEY_X_RESTARTIFCHANGED: &str = "X-RestartIfChanged";
pub const KEY_X_STOPIFCHANGED: &str = "X-StopIfChanged";
pub const KEY_X_SWITCHMETHOD: &str = "X-SwitchMethod";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemdIni(Sections);

type Sections = BTreeMap<String, Entries>;
type Entries = BTreeMap<String, Value>;

#[derive(Debug, Clone, PartialEq, Eq)]
enum Value {
    Strings(Vec<String>),
    SwitchMethod(UnitSwitchMethod),
    Bool(bool),
}

/// How to switch a unit.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum UnitSwitchMethod {
    /// Reload the unit if it is already running, otherwise start it.
    Reload,
    /// Restart the unit if it is already running, otherwise start it.
    Restart,
    /// Stop the old unit (if it exists) and start the new unit.
    StopStart,
    /// Stop the old unit (if it exists) but do not start the new unit
    StopOnly,
    /// Leave the old unit running, ignoring the new unit. If no old unit
    /// exists, then the new unit is started.
    KeepOld,
}

impl SystemdIni {
    pub fn get_bool(&self, section: &str, key: &str) -> Option<bool> {
        self.get_value(section, key).and_then(|v| {
            if let Value::Bool(b) = v {
                Some(*b)
            } else {
                None
            }
        })
    }

    pub fn get_unit_switch_method(&self) -> Option<UnitSwitchMethod> {
        self.get_value("Unit", KEY_X_SWITCHMETHOD).and_then(|v| {
            if let Value::SwitchMethod(b) = v {
                Some(*b)
            } else {
                None
            }
        })
    }

    fn get_value(&self, section: &str, key: &str) -> Option<&Value> {
        self.0.get(section).and_then(|entries| entries.get(key))
    }

    pub fn remove(&mut self, section: &str, key: &str) {
        let _ = self.0.get_mut(section).map(|entries| entries.remove(key));
    }

    /// Merges `other` into `self`.
    ///
    /// Overlapping fields are taken from `other` and `other` is consumed in the process.
    pub fn extend(self: &mut SystemdIni, other: SystemdIni) {
        for (section, entries) in other.0 {
            self.0.entry(section).or_default().extend(entries);
        }
    }

    /// Compares `self` with `other` for equality but excluding the given
    /// options.
    pub fn eq_excluding(&self, other: &SystemdIni, excluded: &[(&str, &str)]) -> bool {
        /// Creates an iterator over all entries, excluding those entries present in `excluded`.
        fn make_eq_iter<'a>(
            ini: &'a SystemdIni,
            excluded: &'a [(&'a str, &'a str)],
        ) -> impl Iterator<Item = ((&'a str, &'a str), &'a Value)> {
            ini.0
                .iter()
                .flat_map(|(section, entries)| {
                    entries
                        .iter()
                        .map(|(key, value)| ((section.as_str(), key.as_str()), value))
                })
                .filter(|(p, _)| !excluded.contains(p))
        }

        let a = make_eq_iter(self, excluded);
        let b = make_eq_iter(other, excluded);

        a.eq(b)
    }
}

struct Parser<'a> {
    content: Peekable<Chars<'a>>,
    line: usize,
    column: usize,
}

#[derive(Debug, PartialEq, Eq)]
pub struct ParseError {
    message: Cow<'static, str>,
    line: usize,
    column: usize,
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{} at line {}, column {}",
            self.message, self.line, self.column
        )
    }
}

impl std::error::Error for ParseError {}

impl<'a> Parser<'a> {
    fn eof(&mut self) -> bool {
        self.content.peek().is_none()
    }

    /// Read the next character from the input stream.
    fn next(&mut self) -> Option<char> {
        let ch = self.content.next()?;

        if ch == '\n' {
            self.line += 1;
            self.column = 0;
        } else {
            self.column += 1;
        }

        Some(ch)
    }

    /// Optionally read the next character from the input stream.
    fn next_if<P>(&mut self, p: P) -> Option<char>
    where
        P: FnOnce(&char) -> bool,
    {
        let ch = self.content.next_if(p)?;

        if ch == '\n' {
            self.line += 1;
            self.column = 0;
        } else {
            self.column += 1;
        }

        Some(ch)
    }

    fn error(&self, message: Cow<'static, str>) -> ParseError {
        ParseError {
            message,
            line: self.line,
            column: self.column,
        }
    }

    fn error_unexpected<S: AsRef<str>>(&mut self, expected: S) -> ParseError {
        let message = format!(
            "expected {} but got {}",
            expected.as_ref(),
            if let Some(ch) = self.content.peek() {
                format!("'{ch}'")
            } else {
                "end of file".to_string()
            }
        );

        ParseError {
            message: message.into(),
            line: self.line,
            column: self.column,
        }
    }

    fn expect(&mut self, expected: char) -> Result<(), ParseError> {
        if let Some(ch) = self.content.peek() {
            let ch = *ch;
            if ch == expected {
                self.next();
                return Ok(());
            }
        }

        Err(self.error_unexpected(format!("'{expected}'")))
    }

    // Used by `to_unescaped_string`.
    #[allow(dead_code)]
    fn take(&mut self, n: usize) -> String {
        let mut result = String::new();

        for _ in 0..n {
            if let Some(ch) = self.next() {
                result.push(ch);
            } else {
                break;
            }
        }

        result
    }

    fn take_while<P>(&mut self, p: P) -> String
    where
        P: Fn(&char) -> bool,
    {
        let mut result = String::new();

        while let Some(ch) = self.next_if(&p) {
            result.push(ch);
        }

        result
    }

    fn skip_while<P>(&mut self, p: P)
    where
        P: Fn(&char) -> bool,
    {
        while self.next_if(&p).is_some() {}
    }

    /// Skips all whitespace characters.
    fn skip_ws(&mut self) {
        self.skip_while(|ch| ch.is_ascii_whitespace())
    }

    /// Skip only horizontal whitespace characters (' ' and '\t').
    fn skip_hs(&mut self) {
        self.skip_while(|ch| *ch == ' ' || *ch == '\t')
    }

    /// Skip comment starting with `#` or `;`, if one starts at current position.
    ///
    /// Returns `true` if comment actually was skipped, `false` otherwise.
    fn skip_comment(&mut self) -> bool {
        if self.next_if(|ch| *ch == '#' || *ch == ';').is_some() {
            self.skip_while(|ch| *ch != '\n');
            self.next();
            true
        } else {
            false
        }
    }

    fn parse_section(&mut self) -> Result<Option<(String, Entries)>, ParseError> {
        self.skip_ws();

        while self.skip_comment() {
            self.skip_ws();
        }

        // If we've reached EOF.
        if self.eof() {
            return Ok(None);
        }

        self.expect('[')?;

        let section_name = self
            .take_while(|ch| *ch != ']' && *ch != '\'' && *ch != '\"' && !ch.is_ascii_control());

        self.expect(']')?;
        self.expect('\n')?;
        self.skip_ws();

        let entries = self.parse_section_entries(&section_name)?;

        Ok(Some((section_name, entries)))
    }

    fn parse_section_entries(&mut self, section_name: &str) -> Result<Entries, ParseError> {
        let mut entries = Entries::new();

        while let Some(ch) = self.content.peek() {
            // Have reached start of a new INI section.
            if *ch == '[' {
                break;
            }

            if self.skip_comment() {
                self.skip_ws();
                continue;
            }

            let key = self.parse_entry_key()?;

            if key.is_empty() {
                return Err(self.error_unexpected("entry key name"));
            }

            self.skip_hs();

            self.expect('=')?;

            self.skip_hs();

            let value = self.parse_entry_value()?;

            // Convert the raw string value into the expected INI value.
            match section_name {
                "Unit" => {
                    if [
                        KEY_REFUSEMANUALSTART,
                        KEY_REFUSEMANUALSTOP,
                        KEY_X_RELOADIFCHANGED,
                        KEY_X_RESTARTIFCHANGED,
                        KEY_X_STOPIFCHANGED,
                    ]
                    .contains(&key.as_str())
                    {
                        let value = to_bool(value).map_err(|s| self.error(s.into()))?;
                        entries.insert(key, value);
                    } else if [KEY_X_SWITCHMETHOD].contains(&key.as_str()) {
                        let value =
                            to_unit_switch_method(&value).map_err(|s| self.error(s.into()))?;
                        entries.insert(key, value);
                    } else {
                        let e = entries.entry(key).or_insert_with(|| Value::Strings(vec![]));
                        match e {
                            Value::Strings(items) => items.push(value),
                            _ => panic!("inconsistent key value type"),
                        };
                    }
                }
                _ => {
                    let e = entries.entry(key).or_insert_with(|| Value::Strings(vec![]));
                    match e {
                        Value::Strings(items) => items.push(value),
                        _ => panic!("inconsistent key value type"),
                    };
                }
            };

            self.skip_ws();
        }

        Ok(entries)
    }

    fn parse_entry_key(&mut self) -> Result<String, ParseError> {
        Ok(self.take_while(|c| c.is_ascii_alphanumeric() || *c == '-'))
    }

    /// Parses a entry value.
    ///
    /// Handles line continuations, comments, and escaped characters.
    ///
    /// Additionally, leading and trailing whitespaces are trimmed from the returned
    /// string.
    fn parse_entry_value(&mut self) -> Result<String, ParseError> {
        let mut value = String::with_capacity(16);

        while let Some(ch) = self.next() {
            if ch == '\n' {
                break;
            } else if ch == '\\' {
                let Some(ch) = self.next() else {
                    return Err(self.error("invalid character escape: '\\'".into()));
                };

                match ch {
                    // We are in a line continuation.
                    '\n' => {
                        // Skip whitespace after the \ and replace it with a
                        // single ' '. Also skip any intermediate comment lines.
                        value.push(' ');
                        self.skip_hs();
                        while self.skip_comment() {
                            self.skip_hs();
                        }
                    }
                    // Unknown escapes are passed on verbatim.
                    ch => {
                        value.push('\\');
                        value.push(ch);
                    }
                }
            } else {
                value.push(ch);
            }
        }

        Ok(value.trim().to_string())
    }
}

/// Converts a string to a Boolean using systemd's rules.
///
/// As defined in `systemd.syntax(7)`:
///
/// > Boolean arguments used in configuration files can be written in
/// > various formats. For positive settings the strings 1, yes, true and on
/// > are equivalent. For negative settings, the strings 0, no, false and
/// > off are equivalent.
///
/// Additionally, 'y'/'n' and 't'/'f' seem to be respected by systemd.
fn to_bool(mut value: String) -> Result<Value, String> {
    value.make_ascii_lowercase();
    match value.as_str() {
        "1" | "yes" | "y" | "true" | "t" | "on" => Ok(Value::Bool(true)),
        "0" | "no" | "n" | "false" | "f" | "off" => Ok(Value::Bool(false)),
        _ => Err(format!("invalid Boolean value \"{value}\"")),
    }
}

fn to_unit_switch_method(value: &str) -> Result<Value, String> {
    let value = match value {
        "reload" => Ok(UnitSwitchMethod::Reload),
        "restart" => Ok(UnitSwitchMethod::Restart),
        "stop-start" => Ok(UnitSwitchMethod::StopStart),
        "keep-old" => Ok(UnitSwitchMethod::KeepOld),
        unknown => Err(format!("unknown unit switch method \"{unknown}\"")),
    }?;

    Ok(Value::SwitchMethod(value))
}

/// Unescapes the given string according to the systemd escape rules.
///
/// Specifically, the supported escapes match what is in
/// `systemd.syntax(7)`:
///
/// | Literal    | Actual value                                        |
/// |------------|-----------------------------------------------------|
/// | \a         | bell                                                |
/// | \b         | backspace                                           |
/// | \f         | form feed                                           |
/// | \n         | newline                                             |
/// | \r         | carriage return                                     |
/// | \t         | tab                                                 |
/// | \v         | vertical tab                                        |
/// | \\\\       | backslash                                           |
/// | \\"        | double quotation mark                               |
/// | \\'        | single quotation mark                               |
/// | \s         | space                                               |
/// | \xxx       | character number xx in hexadecimal encoding         |
/// | \nnn       | character number nnn in octal encoding              |
/// | \unnnn     | unicode code point nnnn in hexadecimal encoding     |
/// | \Unnnnnnnn | unicode code point nnnnnnnn in hexadecimal encoding |
///
/// Note, not actually used anywhere but maybe it will be useful in the
/// future?
#[allow(dead_code)]
fn to_unescaped_string(value: &str) -> Result<String, String> {
    let mut result = String::with_capacity(value.len());

    // Current character being escaped (for use of \xxx and \nnn escapes of multi-byte UTF-8 characters).
    let mut cur_escape: Vec<u8> = Vec::with_capacity(4);

    let mut it = value.chars();

    while let Some(ch) = it.next() {
        if ch == '\\' {
            let Some(ch) = it.next() else {
                return Err("invalid character escape: '\\'".into());
            };

            match ch {
                'a' => result.push('\x07'),
                'b' => result.push('\x08'),
                'f' => result.push('\x0C'),
                'n' => result.push('\n'),
                'r' => result.push('\r'),
                't' => result.push('\t'),
                'v' => result.push('\x0B'),
                '\\' => result.push('\\'),
                '"' => result.push('\"'),
                '\'' => result.push('\''),
                's' => result.push(' '),
                'x' => {
                    let hex: String = it.by_ref().take(2).collect();
                    match (hex.len(), u8::from_str_radix(&hex, 16)) {
                        (2, Ok(char_num)) => {
                            cur_escape.push(char_num);
                            match std::str::from_utf8(&cur_escape) {
                                Ok(s) => {
                                    result.push_str(s);
                                    cur_escape.clear();
                                }
                                Err(e) if e.error_len().is_none() => {}
                                Err(_) => {
                                    return Err(format!(
                                        "invalid escaped UTF-8 code point '{}'",
                                        to_hex_string(&cur_escape)
                                    ))
                                }
                            }
                        }
                        _ => return Err(format!("invalid character escape: '\\x{hex}'")),
                    }
                }
                n if ('0'..='7').contains(&n) => {
                    let mut oct = String::with_capacity(3);
                    oct.push(n);
                    oct.push_str(it.by_ref().take(2).collect::<String>().as_str());
                    let oct = oct;

                    match (oct.len(), u16::from_str_radix(&oct, 8)) {
                        (3, Ok(char_num)) if char_num <= 255 => {
                            cur_escape.push(char_num as u8);
                            match std::str::from_utf8(&cur_escape) {
                                Ok(s) => {
                                    result.push_str(s);
                                    cur_escape.clear();
                                }
                                Err(e) if e.error_len().is_none() => {}
                                Err(_) => {
                                    return Err(format!(
                                        "invalid escaped UTF-8 code point '{}'",
                                        to_hex_string(&cur_escape)
                                    ))
                                }
                            }
                        }
                        _ => return Err(format!("invalid character escape: '\\{oct}'")),
                    }
                }
                'u' => {
                    let hex: String = it.by_ref().take(4).collect();
                    match (hex.len(), u32::from_str_radix(&hex, 16).map(char::from_u32)) {
                        (4, Ok(Some(ch))) => result.push(ch),
                        _ => return Err(format!("invalid character escape: '\\u{hex}'")),
                    }
                }
                'U' => {
                    let hex: String = it.by_ref().take(8).collect();
                    match (hex.len(), u32::from_str_radix(&hex, 16).map(char::from_u32)) {
                        (8, Ok(Some(ch))) => result.push(ch),
                        _ => return Err(format!("invalid character escape: '\\U{hex}'")),
                    }
                }
                // Unknown escapes are passed on verbatim.
                ch => {
                    result.push('\\');
                    result.push(ch);
                }
            }
        } else {
            result.push(ch);
        }
    }

    Ok(result)
}

fn to_hex_string(bytes: &[u8]) -> String {
    bytes
        .iter()
        .fold(String::with_capacity(4 * bytes.len()), |mut acc, n| {
            let _ = write!(acc, "\\x{n:02x}");
            acc
        })
}

/// Parses a given string as a systemd INI file.
///
/// The expected format is as described in [XDG Desktop Entry
/// Specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/basic-format.html)
/// and `systemd.syntax(7)`.
pub fn parse(content: &str) -> Result<SystemdIni, ParseError> {
    let mut parser = Parser {
        content: content.chars().peekable(),
        line: 0,
        column: 0,
    };

    let mut sections = BTreeMap::new();

    while let Some((key, entries)) = parser.parse_section()? {
        sections.insert(key, entries);
    }

    Ok(SystemdIni(sections))
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;

    fn test_data_path(file_name: &str) -> PathBuf {
        PathBuf::from("testdata/unit_file").join(file_name)
    }

    fn systemd_ini<S: Into<Sections>>(sections: S) -> SystemdIni {
        SystemdIni(sections.into())
    }

    fn section<M: Into<Entries>>(name: &str, entries: M) -> (String, Entries) {
        (name.to_string(), entries.into())
    }

    fn entry(key: &str, value: Value) -> (String, Value) {
        (key.to_string(), value)
    }

    fn entry_str(key: &str, value: &str) -> (String, Value) {
        entry(key, Value::Strings(vec![value.to_string()]))
    }

    fn entry_bool(key: &str, value: bool) -> (String, Value) {
        entry(key, Value::Bool(value))
    }

    #[test]
    fn can_remove_with_empty_section() {
        let mut actual = systemd_ini([section("Section", [])]);
        let expected = actual.clone();

        actual.remove("Missing", "missing");

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_remove_with_missing_key() {
        let mut actual = systemd_ini([section("Section", [entry_str("entry", "value")])]);
        let expected = actual.clone();

        actual.remove("Section", "missing");

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_remove_with_existing_key() {
        let mut actual = systemd_ini([section(
            "Section",
            [entry_str("entry", "value"), entry_str("existing", "value")],
        )]);
        let expected = systemd_ini([section("Section", [entry_str("entry", "value")])]);

        actual.remove("Section", "existing");

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_extend_empty_with_non_empty() {
        let mut actual = systemd_ini([]);
        let mergee = systemd_ini([section("Section", [entry_str("entry", "value")])]);

        let expected = mergee.clone();

        actual.extend(mergee);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_extend_non_empty_with_empty() {
        let mut actual = systemd_ini([section("Section", [entry_str("entry", "value")])]);
        let mergee = systemd_ini([]);

        let expected = actual.clone();

        actual.extend(mergee);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_extend_non_empty_section_with_empty_section() {
        let mut actual = systemd_ini([section("Section", [entry_str("entry", "value")])]);
        let mergee = systemd_ini([section("Section", [])]);

        let expected = actual.clone();

        actual.extend(mergee);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_extend_empty_section_with_non_empty_section() {
        let mut actual = systemd_ini([section("Section", [])]);
        let mergee = systemd_ini([section("Section", [entry_str("entry", "value")])]);

        let expected = mergee.clone();

        actual.extend(mergee);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_extend_non_empty_section_with_non_empty_section() {
        let mut actual = systemd_ini([section(
            "Section",
            [entry_str("entry1", "value1"), entry_str("entry2", "value2")],
        )]);
        let mergee = systemd_ini([section(
            "Section",
            [entry_str("entry1", "value2"), entry_str("entry3", "value3")],
        )]);

        let expected = systemd_ini([section(
            "Section",
            [
                entry_str("entry1", "value2"),
                entry_str("entry2", "value2"),
                entry_str("entry3", "value3"),
            ],
        )]);

        actual.extend(mergee);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_eq_excluding_nothing() {
        let a = systemd_ini([section(
            "Section",
            [entry_str("entry1", "value1"), entry_str("entry2", "value2")],
        )]);

        let same = systemd_ini([section(
            "Section",
            [entry_str("entry1", "value1"), entry_str("entry2", "value2")],
        )]);

        let different_value = systemd_ini([section(
            "Section",
            [
                entry_str("entry1", "value1"),
                entry_str("entry2", "value2'"),
            ],
        )]);

        let different_entry = systemd_ini([section(
            "Section",
            [entry_str("entry1", "value1"), entry_str("entry3", "value3")],
        )]);

        assert!(a.eq_excluding(&same, &[]));
        assert!(!a.eq_excluding(&different_value, &[]));
        assert!(!a.eq_excluding(&different_entry, &[]));
    }

    #[test]
    fn can_eq_excluding_one() {
        let a = systemd_ini([section(
            "Section",
            [entry_str("entry1", "value1"), entry_str("entry2", "value2")],
        )]);

        let same = systemd_ini([section(
            "Section",
            [entry_str("entry1", "value1"), entry_str("entry2", "value2")],
        )]);

        let different_value = systemd_ini([section(
            "Section",
            [
                entry_str("entry1", "value1"),
                entry_str("entry2", "value2'"),
            ],
        )]);

        let different_entry = systemd_ini([section(
            "Section",
            [entry_str("entry1", "value1"), entry_str("entry3", "value3")],
        )]);

        assert!(a.eq_excluding(&same, &[("Section", "entry2")]));
        assert!(a.eq_excluding(&different_value, &[("Section", "entry2")]));
        assert!(!a.eq_excluding(&different_entry, &[("Section", "entry2")]));
    }

    #[test]
    fn can_parse_empty_file() {
        let actual = parse("").unwrap();

        let expected = systemd_ini([]);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_parse_file_with_only_comments() {
        let actual = parse(
            r#"
# comment1

; comment2
;
# comment3
"#,
        )
        .unwrap();

        let expected = systemd_ini([]);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_parse_empty_section() {
        let actual = parse(
            r#"
[abcde]
"#,
        )
        .unwrap();

        let expected = systemd_ini([section("abcde", [])]);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_parse_file_with_comment_on_last_line() {
        let actual = parse(
            r#"
[abcde]
foo = bar
# comment1
; comment2"#,
        )
        .unwrap();

        let expected = systemd_ini([section("abcde", [entry_str("foo", "bar")])]);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_parse_section() {
        let ini_no_new_line = r#"
[abcde]
foo = bar
baz = boo"#;
        let ini_new_line = {
            let mut s = String::from(ini_no_new_line);
            s.push('\n');
            s
        };

        let actual_no_new_line = parse(ini_no_new_line).unwrap();
        let actual_new_line = parse(&ini_new_line).unwrap();

        let expected = systemd_ini([section(
            "abcde",
            [entry_str("foo", "bar"), entry_str("baz", "boo")],
        )]);

        assert_eq!(actual_no_new_line, expected);
        assert_eq!(actual_new_line, expected);
    }

    #[test]
    fn fails_for_entry_without_equals() {
        let actual = parse(
            r#"
[abcde]
foo bar
"#,
        );

        let expected = Err(ParseError {
            message: "expected '=' but got 'b'".into(),
            line: 2,
            column: 4,
        });

        assert_eq!(actual, expected);
        assert_eq!(
            format!("{}", actual.unwrap_err()),
            "expected '=' but got 'b' at line 2, column 4"
        );
    }

    #[test]
    fn fails_for_entry_without_key() {
        let actual = parse(
            r#"
[abcde]
 = bar
"#,
        );

        let expected = Err(ParseError {
            message: "expected entry key name but got '='".into(),
            line: 2,
            column: 1,
        });

        assert_eq!(actual, expected);
        assert_eq!(
            format!("{}", actual.unwrap_err()),
            "expected entry key name but got '=' at line 2, column 1"
        );
    }

    #[test]
    fn fails_for_entry_with_bad_boolean() {
        let actual = parse(
            r#"
[Unit]
RefuseManualStart = nonsense
"#,
        );

        let expected = Err(ParseError {
            message: "invalid Boolean value \"nonsense\"".into(),
            line: 3,
            column: 0,
        });

        assert_eq!(actual, expected);
        assert_eq!(
            format!("{}", actual.unwrap_err()),
            "invalid Boolean value \"nonsense\" at line 3, column 0"
        );
    }

    #[test]
    fn fails_for_entry_with_bad_unit_switch_method() {
        let actual = parse(
            r#"
[Unit]
X-SwitchMethod = nonsense
"#,
        );

        let expected = Err(ParseError {
            message: "unknown unit switch method \"nonsense\"".into(),
            line: 3,
            column: 0,
        });

        assert_eq!(actual, expected);
        assert_eq!(
            format!("{}", actual.unwrap_err()),
            "unknown unit switch method \"nonsense\" at line 3, column 0"
        );
    }

    #[test]
    fn can_parse_section_with_list() {
        let actual = parse(
            r#"
[abcde]
foo = bar
foo = baz
"#,
        )
        .unwrap();

        let expected = systemd_ini([section(
            "abcde",
            [entry(
                "foo",
                Value::Strings(vec!["bar".to_string(), "baz".to_string()]),
            )],
        )]);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_parse_section_with_line_continuation() {
        let actual1 = parse(
            r#"
[abcde]
foo = bar\
      baz
"#,
        )
        .unwrap();

        let actual2 = parse(
            r#"
[abcde]
foo = bar\
    # An intervening comment should be ignored.
    ; This comment should also be ignored.
      baz
"#,
        )
        .unwrap();

        let expected = systemd_ini([section("abcde", [entry_str("foo", "bar baz")])]);

        assert_eq!(actual1, expected);
        assert_eq!(actual2, expected);
    }

    #[test]
    fn can_unescape_strings() {
        assert_eq!(to_unescaped_string("plain"), Ok("plain".to_string()));

        // Test each escape style bracketed by '<' and '>' to avoid triggering
        // string trimming.
        assert_eq!(to_unescaped_string("<\\a>"), Ok("<\x07>".to_string()));
        assert_eq!(to_unescaped_string("<\\b>"), Ok("<\x08>".to_string()));
        assert_eq!(to_unescaped_string("<\\f>"), Ok("<\x0C>".to_string()));
        assert_eq!(to_unescaped_string("<\\n>"), Ok("<\n>".to_string()));
        assert_eq!(to_unescaped_string("<\\r>"), Ok("<\r>".to_string()));
        assert_eq!(to_unescaped_string("<\\t>"), Ok("<\t>".to_string()));
        assert_eq!(to_unescaped_string("<\\v>"), Ok("<\x0B>".to_string()));
        assert_eq!(to_unescaped_string("<\\\\>"), Ok("<\\>".to_string()));
        assert_eq!(to_unescaped_string("<\\\">"), Ok("<\">".to_string()));
        assert_eq!(to_unescaped_string("<\\'>"), Ok("<\'>".to_string()));
        assert_eq!(to_unescaped_string("<\\s>"), Ok("< >".to_string()));

        assert_eq!(to_unescaped_string("<\\x52>"), Ok("<R>".to_string()));
        assert_eq!(to_unescaped_string("<\\122>"), Ok("<R>".to_string()));
        assert_eq!(to_unescaped_string("<\\u0052>"), Ok("<R>".to_string()));
        assert_eq!(to_unescaped_string("<\\U00000052>"), Ok("<R>".to_string()));

        // Unknown escape is passed on as-is.
        assert_eq!(to_unescaped_string("<\\h>"), Ok("<\\h>".to_string()));

        // Technically the below are more strict than systemd in relaxed mode but
        // probably good to error out for invalid escapes anyway.
        assert_eq!(
            to_unescaped_string("<\\x1>"),
            Err("invalid character escape: '\\x1>'".into())
        );
        assert_eq!(
            to_unescaped_string("<\\199>"),
            Err("invalid character escape: '\\199'".into())
        );
        assert_eq!(
            to_unescaped_string("<\\u123>"),
            Err("invalid character escape: '\\u123>'".into())
        );
        assert_eq!(
            to_unescaped_string("<\\U1234>"),
            Err("invalid character escape: '\\U1234>'".into())
        );
        assert_eq!(
            to_unescaped_string("<\\"),
            Err("invalid character escape: '\\'".into())
        );
        assert_eq!(
            to_unescaped_string("<\\xf0\\xff>"),
            Err("invalid escaped UTF-8 code point '\\xf0\\xff'".into())
        );
        assert_eq!(
            to_unescaped_string("<\\360\\377>"),
            Err("invalid escaped UTF-8 code point '\\xf0\\xff'".into())
        );
    }

    #[test]
    fn can_parse_complicated_systemd_unit() {
        let content = std::fs::read_to_string(test_data_path("escaped-values.service")).unwrap();
        let actual = parse(&content).unwrap();

        let expected = systemd_ini([
            section("Install", [entry_str("WantedBy", "default.target")]),
            section(
                "Service",
                [
                    entry_str(
                        "ExecStart",
                        "/bin/sh -c 'systemd\\x2Dnotify READY=1; /run/current\\x2dsystem/sw/bin/sleep 10s'",
                    ),
                    entry_str("NotifyAccess", "all"),
                    entry_str("Type", "notify"),
                ],
            ),
            section(
                "Unit",
                [
                    entry_str(
                        "Description",
                        "Successful simple service with X-RestartIfChanged = false\\x20\\xf0\\x9f\\x99\\x82",
                    ),
                    entry_bool("RefuseManualStart", false),
                    entry_bool("RefuseManualStop", true),
                    entry("X-SwitchMethod", Value::SwitchMethod(UnitSwitchMethod::Restart)),
                ],
            ),
        ]);

        assert_eq!(actual, expected);
    }

    #[test]
    fn can_parse_upstream_systemd_unit() {
        let content =
            std::fs::read_to_string(test_data_path("systemd-tmpfiles-setup.service")).unwrap();
        let actual = parse(&content).unwrap();

        let expected = systemd_ini([
            section("Install", [entry_str("WantedBy", "basic.target")]),
            section(
                "Service",
                [
                    entry_str("Type", "oneshot"),
                    entry_str(
                        "ExecStart",
                        "systemd-tmpfiles --user --create --remove --boot",
                    ),
                    entry_str("RemainAfterExit", "yes"),
                    entry_str("SuccessExitStatus", "DATAERR"),
                ],
            ),
            section(
                "Unit",
                [
                    entry_str("Description", "Create User Files and Directories"),
                    entry_str("Documentation", "man:tmpfiles.d(5) man:systemd-tmpfiles(8)"),
                    entry_str("DefaultDependencies", "no"),
                    entry_str("Conflicts", "shutdown.target"),
                    entry_str("Before", "basic.target shutdown.target"),
                    entry_bool("RefuseManualStop", true),
                ],
            ),
        ]);

        assert_eq!(actual, expected);
    }
}