boot-loader-spec 0.1.5

Parses and manipulates Boot Loader Spec entries
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
// bls.rs
//
// Copyright 2022 Alberto Ruiz <aruiz@gnome.org>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// SPDX-License-Identifier: MPL-2.0

//! Parse and modify [Boot Loader Specification](https://uapi-group.org/specifications/specs/boot_loader_specification/) (BLS) entry files.
//!
//! This library implements the UAPI Boot Loader Specification (Type #1 entries) and
//! [Fedora/GRUB extensions](https://fedoraproject.org/wiki/Changes/BootLoaderSpecByDefault)
//! (`grub_class`, `grub_users`, `grub_hotkey`, `grub_arg`). Keys `uki`, `uki-url`, and
//! `profile` from the spec are not yet supported.
//!
//! # Usage
//!
//! Parse a BLS snippet, optionally modify it with [`BLSEntry::set`] or [`BLSEntry::clear`],
//! then serialize with [`BLSEntry::render`].
//!
//! # Compatibility
//!
//! Both hyphenated (`machine-id`, `sort-key`, `devicetree-overlay`) and underscore forms
//! are accepted when parsing. Output uses the spec’s hyphenated form for those keys.
//! An entry must contain at least one of `linux` or `efi`.
//!
//! # no_std
//!
//! Disable the default "std" feature with `--no-default-features` for a `no_std` build
//! (requires `alloc`).
//!
//! **Note:** Full-line comments are moved to the header when re-rendering; order of
//! commands and comments is not preserved.

#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
use alloc::format;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

#[cfg(not(feature = "std"))]
use alloc::str::FromStr;
#[cfg(feature = "std")]
use std::str::FromStr;

/// A BLS key value, optionally with an inline comment (text after `#` on the same line).
#[derive(Debug, PartialEq)]
pub enum BLSValue {
    /// The argument string for the BLS command.
    Value(String),
    /// The argument string and a trailing comment (e.g. `value # comment`).
    ValueWithComment(String, String),
}

/// Policy for [`BLSEntry::set`] when the key allows multiple values (e.g. `initrd`, `options`, `grub_class`).
#[derive(Debug, PartialEq)]
pub enum ValueSetPolicy {
    /// Replace all existing values with this one.
    ReplaceAll,
    /// Append after existing values.
    Append,
    /// Insert at the beginning.
    Prepend,
    /// Insert at the given index; may panic if index is out of bounds (see `Vec::insert`).
    InsertAt(usize),
}

/// BLS and Fedora/GRUB entry keys. Parse from key strings via `FromStr` (e.g. `"linux"`, `"machine-id"`).
#[derive(Debug, PartialEq)]
pub enum BLSKey {
    /// Human-readable menu title.
    Title,
    /// Version string (e.g. kernel version).
    Version,
    /// Machine ID (32 hex chars).
    MachineId,
    /// Sort key for menu ordering.
    SortKey,
    /// Linux kernel image path (required unless `efi` is set).
    Linux,
    /// EFI program path.
    Efi,
    /// Initrd path (may appear multiple times).
    Initrd,
    /// Kernel/command-line options (may appear multiple times).
    Options,
    /// Device tree path.
    Devicetree,
    /// Device tree overlay path(s).
    DevicetreeOverlay,
    /// Architecture (e.g. `x64`, `aa64`).
    Architecture,
    /// Fedora/GRUB: hotkey for the entry.
    GrubHotkey,
    /// Fedora/GRUB: users allowed to boot this entry.
    GrubUsers,
    /// Fedora/GRUB: menu class (may appear multiple times).
    GrubClass,
    /// Fedora/GRUB: extra argument.
    GrubArg,
}

impl FromStr for BLSKey {
    type Err = String;

    fn from_str(key: &str) -> Result<Self, Self::Err> {
        match key {
            "linux" => Ok(BLSKey::Linux),
            "title" => Ok(BLSKey::Title),
            "version" => Ok(BLSKey::Version),
            "machine_id" | "machine-id" => Ok(BLSKey::MachineId),
            "sort_key" | "sort-key" => Ok(BLSKey::SortKey),
            "efi" => Ok(BLSKey::Efi),
            "initrd" => Ok(BLSKey::Initrd),
            "options" => Ok(BLSKey::Options),
            "devicetree" => Ok(BLSKey::Devicetree),
            "devicetree_overlay" | "devicetree-overlay" => Ok(BLSKey::DevicetreeOverlay),
            "architecture" => Ok(BLSKey::Architecture),
            "grub_hotkey" => Ok(BLSKey::GrubHotkey),
            "grub_users" => Ok(BLSKey::GrubUsers),
            "grub_class" => Ok(BLSKey::GrubClass),
            "grub_arg" => Ok(BLSKey::GrubArg),
            _ => Err(format!("Invalid key {}", key)),
        }
    }
}

/// A parsed Boot Loader Spec (Type #1) entry. Holds all standard and Fedora/GRUB keys.
///
/// Use [`BLSEntry::parse`] to parse from text and [`BLSEntry::render`] to serialize.
#[derive(Debug)]
pub struct BLSEntry {
    /// Optional title (e.g. from `PRETTY_NAME`).
    pub title: Option<BLSValue>,
    /// Optional version (e.g. kernel version).
    pub version: Option<BLSValue>,
    /// Optional machine ID.
    pub machine_id: Option<BLSValue>,
    /// Optional sort key.
    pub sort_key: Option<BLSValue>,
    /// Kernel image path; always present (empty if entry is efi-only).
    pub linux: BLSValue,
    /// Optional EFI program path.
    pub efi: Option<BLSValue>,
    /// Initrd paths (multiple allowed).
    pub initrd: Vec<BLSValue>,
    /// Kernel/command-line options (multiple allowed).
    pub options: Vec<BLSValue>,
    /// Optional devicetree path.
    pub devicetree: Option<BLSValue>,
    /// Optional devicetree overlay path(s).
    pub devicetree_overlay: Option<BLSValue>,
    /// Optional architecture.
    pub architecture: Option<BLSValue>,
    /// Fedora/GRUB: optional hotkey.
    pub grub_hotkey: Option<BLSValue>,
    /// Fedora/GRUB: optional users.
    pub grub_users: Option<BLSValue>,
    /// Fedora/GRUB: menu classes (multiple allowed).
    pub grub_class: Vec<BLSValue>,
    /// Fedora/GRUB: optional extra argument.
    pub grub_arg: Option<BLSValue>,
    /// Full-line comments; when rendering they are output at the top.
    pub comments: Vec<String>,
}

impl BLSEntry {
    /// Creates an empty entry. Optional fields are `None`; `linux` is an empty string.
    pub fn new() -> BLSEntry {
        BLSEntry {
            title: None,
            version: None,
            machine_id: None,
            sort_key: None,
            linux: BLSValue::Value(String::new()),
            efi: None,
            initrd: Vec::new(),
            options: Vec::new(),
            devicetree: None,
            devicetree_overlay: None,
            architecture: None,
            grub_hotkey: None,
            grub_users: None,
            grub_class: Vec::new(),
            grub_arg: None,
            comments: Vec::new(),
        }
    }
}

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

impl BLSEntry {
    /// Parses a BLS entry from UTF-8 text. The entry must contain at least one of `linux` or `efi`.
    /// Returns an error if required keys are missing or an unknown key is encountered.
    /// Comment lines are collected in `comments` and output at the header when rendering.
    ///
    /// # Examples
    ///
    /// ```
    /// use boot_loader_spec::{BLSEntry, BLSValue};
    ///
    /// let text = "title Fedora\nlinux /vmlinuz\noptions root=/dev/sda1";
    /// let entry = BLSEntry::parse(text).unwrap();
    /// assert_eq!(entry.title.as_ref().and_then(|v| match v { BLSValue::Value(s) => Some(s.as_str()), _ => None }).unwrap(), "Fedora");
    /// assert!(matches!(&entry.linux, BLSValue::Value(p) if p == "/vmlinuz"));
    /// ```
    pub fn parse(buffer: &str) -> Result<BLSEntry, String> {
        let mut entry = BLSEntry::new();
        let mut has_linux = false;
        let mut has_efi = false;

        for line in buffer.lines() {
            let mut comment = None;
            // Extract the comment string from the line
            let line = if line.contains("#") {
                let split: Vec<_> = line.splitn(2, "#").collect();
                comment = Some(String::from(split[1]));
                split[0]
            } else {
                line
            };

            // NOTE: For now we put all comment lines in the header
            if line.trim().contains(" ") {
                let key_value: Vec<&str> = line.trim().splitn(2, " ").collect();

                let key = BLSKey::from_str(key_value[0])?;
                if key == BLSKey::Linux {
                    has_linux = true;
                } else if key == BLSKey::Efi {
                    has_efi = true;
                }
                entry.set(
                    key,
                    String::from(key_value[1]),
                    comment,
                    ValueSetPolicy::Append,
                );
            } else if let Some(comment) = comment {
                entry.comments.push(comment);
            }
        }

        if has_linux || has_efi {
            Ok(entry)
        } else {
            Err(String::from("No 'linux' or 'efi' command found."))
        }
    }

    /// Serializes the entry to BLS text (UTF-8, newline-separated lines). Comments are output first.
    ///
    /// # Examples
    ///
    /// ```
    /// use boot_loader_spec::{BLSEntry, BLSKey, ValueSetPolicy};
    ///
    /// let mut entry = BLSEntry::new();
    /// entry.set(BLSKey::Linux, "/vmlinuz".into(), None, ValueSetPolicy::ReplaceAll);
    /// entry.set(BLSKey::Title, "My OS".into(), None, ValueSetPolicy::ReplaceAll);
    /// let out = entry.render();
    /// assert!(out.contains("linux /vmlinuz"));
    /// assert!(out.contains("title My OS"));
    /// ```
    pub fn render(&self) -> String {
        let mut content = String::new();

        fn render_value(content: &mut String, key: &str, value: &BLSValue) {
            content.push_str(key);
            content.push(' ');
            match value {
                BLSValue::Value(value) => content.push_str(value),
                BLSValue::ValueWithComment(value, comment) => {
                    content.push_str(value);
                    content.push_str(" #");
                    content.push_str(comment);
                }
            }
            content.push('\n');
        }

        fn render_single_value(content: &mut String, key: &str, value: &Option<BLSValue>) {
            if let Some(value) = value {
                render_value(content, key, value)
            }
        }

        fn render_multiple_values(content: &mut String, key: &str, values: &Vec<BLSValue>) {
            for val in values {
                render_value(content, key, val)
            }
        }

        // We push all comments in the header
        for comment in &self.comments {
            content.push('#');
            content.push_str(comment);
            content.push('\n');
        }

        // Mandatory commands
        render_value(&mut content, "linux", &self.linux);

        // Optional commands
        render_single_value(&mut content, "title", &self.title);
        render_single_value(&mut content, "version", &self.version);
        render_single_value(&mut content, "machine-id", &self.machine_id);
        render_single_value(&mut content, "sort-key", &self.sort_key);
        render_single_value(&mut content, "efi", &self.efi);
        render_single_value(&mut content, "devicetree", &self.devicetree);
        render_single_value(&mut content, "devicetree-overlay", &self.devicetree_overlay);
        render_single_value(&mut content, "architecture", &self.architecture);
        render_single_value(&mut content, "grub_hotkey", &self.grub_hotkey);
        render_single_value(&mut content, "grub_users", &self.grub_users);
        render_single_value(&mut content, "grub_arg", &self.grub_arg);

        // Commands with multiple values
        render_multiple_values(&mut content, "initrd", &self.initrd);
        render_multiple_values(&mut content, "options", &self.options);
        render_multiple_values(&mut content, "grub_class", &self.grub_class);

        content
    }

    /// Sets a value for the given key. For multi-value keys (`initrd`, `options`, `grub_class`),
    /// `set_policy` controls append, prepend, replace, or insert-at-index.
    ///
    /// # Panics
    ///
    /// May panic if `ValueSetPolicy::InsertAt(i)` is used with an index out of range.
    pub fn set(
        &mut self,
        key: BLSKey,
        value: String,
        comment: Option<String>,
        set_policy: ValueSetPolicy,
    ) {
        fn value_generator(value: String, comment: Option<String>) -> BLSValue {
            match comment {
                Some(comment) => BLSValue::ValueWithComment(value, comment),
                None => BLSValue::Value(value),
            }
        }

        fn push_value(values: &mut Vec<BLSValue>, val: BLSValue, policy: ValueSetPolicy) {
            match policy {
                ValueSetPolicy::Append => values.push(val),
                ValueSetPolicy::InsertAt(i) => values.insert(i, val),
                ValueSetPolicy::Prepend => values.insert(0, val),
                ValueSetPolicy::ReplaceAll => {
                    values.clear();
                    values.push(val);
                }
            }
        }

        match key {
            BLSKey::Title => self.title = Some(value_generator(value, comment)),
            BLSKey::Version => self.version = Some(value_generator(value, comment)),
            BLSKey::MachineId => self.machine_id = Some(value_generator(value, comment)),
            BLSKey::SortKey => self.sort_key = Some(value_generator(value, comment)),
            BLSKey::Linux => self.linux = value_generator(value, comment),
            BLSKey::Efi => self.efi = Some(value_generator(value, comment)),
            BLSKey::Devicetree => self.devicetree = Some(value_generator(value, comment)),
            BLSKey::DevicetreeOverlay => {
                self.devicetree_overlay = Some(value_generator(value, comment))
            }
            BLSKey::Architecture => self.architecture = Some(value_generator(value, comment)),
            BLSKey::GrubHotkey => self.grub_hotkey = Some(value_generator(value, comment)),
            BLSKey::GrubUsers => self.grub_users = Some(value_generator(value, comment)),
            BLSKey::GrubArg => self.grub_arg = Some(value_generator(value, comment)),

            BLSKey::Initrd => push_value(
                &mut self.initrd,
                value_generator(value, comment),
                set_policy,
            ),
            BLSKey::Options => push_value(
                &mut self.options,
                value_generator(value, comment),
                set_policy,
            ),
            BLSKey::GrubClass => push_value(
                &mut self.grub_class,
                value_generator(value, comment),
                set_policy,
            ),
        }
    }

    /// Clears the given key. For `BLSKey::Linux`, sets the value to an empty string (key remains present). Other keys become `None` or empty.
    pub fn clear(&mut self, key: BLSKey) {
        match key {
            BLSKey::Linux => self.linux = BLSValue::Value(String::from("")),
            BLSKey::Title => self.title = None,
            BLSKey::Version => self.version = None,
            BLSKey::MachineId => self.machine_id = None,
            BLSKey::SortKey => self.sort_key = None,
            BLSKey::Efi => self.efi = None,
            BLSKey::Devicetree => self.devicetree = None,
            BLSKey::DevicetreeOverlay => self.devicetree_overlay = None,
            BLSKey::Architecture => self.architecture = None,
            BLSKey::GrubHotkey => self.grub_hotkey = None,
            BLSKey::GrubUsers => self.grub_users = None,
            BLSKey::GrubArg => self.grub_arg = None,

            BLSKey::Initrd => self.initrd.clear(),
            BLSKey::Options => self.options.clear(),
            BLSKey::GrubClass => self.grub_class.clear(),
        }
    }
}

#[cfg(test)]
mod bls_tests {
    use core::str::FromStr;

    #[cfg(not(feature = "std"))]
    use alloc::string::String;
    #[cfg(not(feature = "std"))]
    use alloc::vec;

    use super::BLSEntry;
    use super::BLSKey;
    use super::BLSValue;
    use super::ValueSetPolicy;

    #[test]
    fn bls_key_from_str() {
        assert!(BLSKey::from_str("linux").is_ok());
        assert!(BLSKey::from_str("title").is_ok());
        assert!(BLSKey::from_str("version").is_ok());
        assert!(BLSKey::from_str("machine_id").is_ok());
        assert!(BLSKey::from_str("machine-id").is_ok());
        assert!(BLSKey::from_str("sort_key").is_ok());
        assert!(BLSKey::from_str("sort-key").is_ok());
        assert!(BLSKey::from_str("efi").is_ok());
        assert!(BLSKey::from_str("initrd").is_ok());
        assert!(BLSKey::from_str("options").is_ok());
        assert!(BLSKey::from_str("devicetree").is_ok());
        assert!(BLSKey::from_str("devicetree_overlay").is_ok());
        assert!(BLSKey::from_str("devicetree-overlay").is_ok());
        assert!(BLSKey::from_str("architecture").is_ok());
        assert!(BLSKey::from_str("grub_hotkey").is_ok());
        assert!(BLSKey::from_str("grub_users").is_ok());
        assert!(BLSKey::from_str("grub_class").is_ok());
        assert!(BLSKey::from_str("grub_arg").is_ok());
        assert!(BLSKey::from_str("invalid_key").is_err());
    }

    #[test]
    fn new_entry() {
        let entry = BLSEntry::new();
        match &entry.linux {
            BLSValue::Value(linux) => assert_eq!(linux, ""),
            _ => panic!("Invalid 'linux' value {:?}", entry.linux),
        }
        assert!(entry.title.is_none());
        assert!(entry.version.is_none());
        assert!(entry.machine_id.is_none());
        assert!(entry.sort_key.is_none());
        assert!(entry.efi.is_none());
        assert_eq!(entry.initrd.len(), 0);
        assert_eq!(entry.options.len(), 0);
        assert!(entry.devicetree.is_none());
        assert!(entry.devicetree_overlay.is_none());
        assert!(entry.architecture.is_none());
        assert!(entry.grub_hotkey.is_none());
        assert!(entry.grub_users.is_none());
        assert_eq!(entry.grub_class.len(), 0);
        assert!(entry.grub_arg.is_none());
        assert!(entry.comments.is_empty());
    }

    #[test]
    fn parse_entry() {
        let entry_txt = "#Comment\n\
                     linux foobar-2.4\n\
                     options foo=bar #Another Comment";
        let entry = BLSEntry::parse(entry_txt);

        assert!(entry.is_ok());
        let entry = entry.unwrap();
        assert_eq!(entry.comments.len(), 1);
        assert_eq!(entry.comments[0], "Comment");

        if let BLSValue::Value(linux) = entry.linux {
            assert_eq!(linux, "foobar-2.4");
        }

        assert_eq!(entry.options.len(), 1);
        match &entry.options[0] {
            BLSValue::ValueWithComment(option, comment) => {
                assert_eq!(option, "foo=bar");
                assert_eq!(comment, "Another Comment");
            }
            _ => {
                panic!("Invalid 'options' value {:?}", entry.options[0])
            }
        }
    }

    #[test]
    fn parse_errors() {
        // Missing both 'linux' and 'efi'
        let entry_txt = "options foo=bar";
        let entry = BLSEntry::parse(entry_txt);
        assert!(entry.is_err());

        // Invalid command
        let entry_txt = "linux asdasdasdas\n\
                     invalid_command foo=bar";
        let entry = BLSEntry::parse(entry_txt);
        assert!(entry.is_err());
    }

    #[test]
    fn parse_efi_only() {
        let entry_txt = "title EFI App\nefi /EFI/app.efi";
        let entry = BLSEntry::parse(entry_txt).expect("efi-only entry should parse");
        assert!(entry.efi.is_some());
        if let Some(BLSValue::Value(ref path)) = entry.efi {
            assert_eq!(path, "/EFI/app.efi");
        }
    }

    #[test]
    fn parse_hyphenated_keys() {
        let entry_txt = "title Fedora\nmachine-id 6a9857a393724b7a981ebb5b8495b9ea\nsort-key fedora\ndevicetree-overlay /overlay.dtbo\nlinux /vmlinuz";
        let entry = BLSEntry::parse(entry_txt).expect("hyphenated keys should parse");
        assert_eq!(
            entry.title.as_ref().map(|v| match v {
                BLSValue::Value(s) => s.as_str(),
                _ => "",
            }),
            Some("Fedora")
        );
        assert!(entry.machine_id.is_some());
        assert!(entry.sort_key.is_some());
        assert!(entry.devicetree_overlay.is_some());
    }

    #[test]
    fn parse_multiple_initrd_options() {
        let entry_txt =
            "linux /vmlinuz\ninitrd /initrd1\ninitrd /initrd2\noptions a=1\noptions b=2";
        let entry = BLSEntry::parse(entry_txt).unwrap();
        assert_eq!(entry.initrd.len(), 2);
        assert_eq!(entry.options.len(), 2);
    }

    #[test]
    fn parse_round_trip() {
        let entry_txt = "title Fedora 19\nsort-key fedora\nmachine-id 6a9857a393724b7a981ebb5b8495b9ea\nversion 3.8.0-2.fc19.x86_64\noptions root=UUID=abc quiet\narchitecture x64\nlinux /6a9857a393724b7a981ebb5b8495b9ea/3.8.0-2.fc19.x86_64/linux\ninitrd /6a9857a393724b7a981ebb5b8495b9ea/3.8.0-2.fc19.x86_64/initrd";
        let entry = BLSEntry::parse(entry_txt).unwrap();
        let rendered = entry.render();
        let entry2 = BLSEntry::parse(&rendered).unwrap();
        assert_eq!(entry.title, entry2.title);
        assert_eq!(entry.version, entry2.version);
        assert_eq!(entry.machine_id, entry2.machine_id);
        assert_eq!(entry.sort_key, entry2.sort_key);
        assert_eq!(entry.linux, entry2.linux);
        assert_eq!(entry.initrd, entry2.initrd);
        assert_eq!(entry.options, entry2.options);
        assert_eq!(entry.architecture, entry2.architecture);
    }

    #[test]
    fn render_all_keys_including_grub() {
        let mut entry = BLSEntry::new();
        entry.set(
            BLSKey::Linux,
            String::from("/vmlinuz"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Title,
            String::from("Test"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubHotkey,
            String::from("t"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubUsers,
            String::from("root"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubArg,
            String::from("--debug"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubClass,
            String::from("recovery"),
            None,
            ValueSetPolicy::Append,
        );
        let out = entry.render();
        assert!(out.contains("grub_hotkey t"));
        assert!(out.contains("grub_users root"));
        assert!(out.contains("grub_arg --debug"));
        assert!(out.contains("grub_class recovery"));
    }

    #[test]
    fn set_every_key() {
        let mut entry = BLSEntry::new();
        entry.set(
            BLSKey::Linux,
            String::from("/vmlinuz"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Title,
            String::from("T"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Version,
            String::from("1.0"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::MachineId,
            String::from("abc"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::SortKey,
            String::from("x"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Efi,
            String::from("/efi.efi"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Initrd,
            String::from("/i1"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::Options,
            String::from("opt"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::Devicetree,
            String::from("/dtb"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::DevicetreeOverlay,
            String::from("/overlay"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Architecture,
            String::from("x64"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubHotkey,
            String::from("h"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubUsers,
            String::from("u"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubClass,
            String::from("c"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::GrubArg,
            String::from("a"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        assert!(entry.title.is_some());
        assert!(entry.version.is_some());
        assert!(entry.machine_id.is_some());
        assert!(entry.sort_key.is_some());
        assert!(entry.efi.is_some());
        assert_eq!(entry.initrd.len(), 1);
        assert_eq!(entry.options.len(), 1);
        assert!(entry.devicetree.is_some());
        assert!(entry.devicetree_overlay.is_some());
        assert!(entry.architecture.is_some());
        assert!(entry.grub_hotkey.is_some());
        assert!(entry.grub_users.is_some());
        assert_eq!(entry.grub_class.len(), 1);
        assert!(entry.grub_arg.is_some());
    }

    #[test]
    fn set_value_policies_initrd_grub_class() {
        let mut entry = BLSEntry::new();
        entry.set(
            BLSKey::Linux,
            String::from("/vmlinuz"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Initrd,
            String::from("a"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::Initrd,
            String::from("b"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::Initrd,
            String::from("mid"),
            None,
            ValueSetPolicy::InsertAt(1),
        );
        assert_eq!(entry.initrd.len(), 3);
        entry.set(
            BLSKey::Initrd,
            String::from("first"),
            None,
            ValueSetPolicy::Prepend,
        );
        assert!(matches!(entry.initrd.first(), Some(BLSValue::Value(s)) if s == "first"));
        entry.set(
            BLSKey::Initrd,
            String::from("only"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        assert_eq!(entry.initrd.len(), 1);
        entry.set(
            BLSKey::GrubClass,
            String::from("class1"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::GrubClass,
            String::from("class2"),
            None,
            ValueSetPolicy::Append,
        );
        assert_eq!(entry.grub_class.len(), 2);
    }

    #[test]
    fn clear_every_key() {
        let mut entry = BLSEntry::new();
        entry.set(
            BLSKey::Linux,
            String::from("/vmlinuz"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Title,
            String::from("T"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Version,
            String::from("1"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::MachineId,
            String::from("m"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::SortKey,
            String::from("s"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Efi,
            String::from("e"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Initrd,
            String::from("i"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::Options,
            String::from("o"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::Devicetree,
            String::from("d"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::DevicetreeOverlay,
            String::from("do"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::Architecture,
            String::from("a"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubHotkey,
            String::from("g"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubUsers,
            String::from("u"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.set(
            BLSKey::GrubClass,
            String::from("c"),
            None,
            ValueSetPolicy::Append,
        );
        entry.set(
            BLSKey::GrubArg,
            String::from("ga"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        entry.clear(BLSKey::Title);
        entry.clear(BLSKey::Version);
        entry.clear(BLSKey::MachineId);
        entry.clear(BLSKey::SortKey);
        entry.clear(BLSKey::Efi);
        entry.clear(BLSKey::Initrd);
        entry.clear(BLSKey::Options);
        entry.clear(BLSKey::Devicetree);
        entry.clear(BLSKey::DevicetreeOverlay);
        entry.clear(BLSKey::Architecture);
        entry.clear(BLSKey::GrubHotkey);
        entry.clear(BLSKey::GrubUsers);
        entry.clear(BLSKey::GrubClass);
        entry.clear(BLSKey::GrubArg);
        entry.clear(BLSKey::Linux);
        assert!(entry.title.is_none());
        assert!(entry.version.is_none());
        assert!(entry.machine_id.is_none());
        assert!(entry.sort_key.is_none());
        assert!(entry.efi.is_none());
        assert!(entry.initrd.is_empty());
        assert!(entry.options.is_empty());
        assert!(entry.devicetree.is_none());
        assert!(entry.devicetree_overlay.is_none());
        assert!(entry.architecture.is_none());
        assert!(entry.grub_hotkey.is_none());
        assert!(entry.grub_users.is_none());
        assert!(entry.grub_class.is_empty());
        assert!(entry.grub_arg.is_none());
        assert!(matches!(&entry.linux, BLSValue::Value(s) if s.is_empty()));
    }

    #[test]
    fn bls_value_value_with_comment() {
        let v = BLSValue::Value(String::from("arg"));
        let vc = BLSValue::ValueWithComment(String::from("arg"), String::from("comment"));
        assert!(matches!(&v, BLSValue::Value(s) if s == "arg"));
        assert!(matches!(&vc, BLSValue::ValueWithComment(a, c) if a == "arg" && c == "comment"));
    }

    #[test]
    fn set_value_policies() {
        // Append
        let mut entry = BLSEntry::new();
        let _ = entry.set(
            BLSKey::Options,
            String::from("foo"),
            None,
            ValueSetPolicy::Append,
        );
        let _ = entry.set(
            BLSKey::Options,
            String::from("bar"),
            None,
            ValueSetPolicy::Append,
        );
        let _ = entry.set(
            BLSKey::Options,
            String::from("baz"),
            None,
            ValueSetPolicy::Append,
        );

        assert_eq!(
            entry.options,
            vec![
                BLSValue::Value(String::from("foo")),
                BLSValue::Value(String::from("bar")),
                BLSValue::Value(String::from("baz"))
            ]
        );

        // InsertAt
        let _ = entry.set(
            BLSKey::Options,
            String::from("lol"),
            None,
            ValueSetPolicy::InsertAt(1),
        );
        assert_eq!(
            entry.options,
            vec![
                BLSValue::Value(String::from("foo")),
                BLSValue::Value(String::from("lol")),
                BLSValue::Value(String::from("bar")),
                BLSValue::Value(String::from("baz"))
            ]
        );

        // ReplaceAll
        let _ = entry.set(
            BLSKey::Options,
            String::from("wtf"),
            None,
            ValueSetPolicy::ReplaceAll,
        );
        assert_eq!(entry.options, vec![BLSValue::Value(String::from("wtf"))]);

        // Prepend
        let _ = entry.set(
            BLSKey::Options,
            String::from("uwu"),
            None,
            ValueSetPolicy::Prepend,
        );
        assert_eq!(
            entry.options,
            vec![
                BLSValue::Value(String::from("uwu")),
                BLSValue::Value(String::from("wtf"))
            ]
        );

        // Clear
        entry.clear(BLSKey::Options);
        assert_eq!(entry.options, vec![]);

        entry.set(
            BLSKey::Title,
            String::from("foobar"),
            None,
            ValueSetPolicy::Append,
        );
        assert_eq!(entry.title, Some(BLSValue::Value(String::from("foobar"))));

        entry.clear(BLSKey::Title);
        assert_eq!(entry.title, None);
    }
}