aboutsummaryrefslogtreecommitdiff
path: root/tools/aconfig/aconfig_protos/src/lib.rs
blob: 64b82d6796d927857e6320e4e7bec43ecd3042a9 (plain)
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
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! `aconfig_protos` is a crate for the protos defined for aconfig
// When building with the Android tool-chain
//
//   - an external crate `aconfig_protos` will be generated
//   - the feature "cargo" will be disabled
//
// When building with cargo
//
//   - a local sub-module will be generated in OUT_DIR and included in this file
//   - the feature "cargo" will be enabled
//
// This module hides these differences from the rest of aconfig.

// ---- When building with the Android tool-chain ----
#[cfg(not(feature = "cargo"))]
mod auto_generated {
    pub use aconfig_rust_proto::aconfig::flag_metadata::Flag_purpose as ProtoFlagPurpose;
    pub use aconfig_rust_proto::aconfig::Flag_declaration as ProtoFlagDeclaration;
    pub use aconfig_rust_proto::aconfig::Flag_declarations as ProtoFlagDeclarations;
    pub use aconfig_rust_proto::aconfig::Flag_metadata as ProtoFlagMetadata;
    pub use aconfig_rust_proto::aconfig::Flag_permission as ProtoFlagPermission;
    pub use aconfig_rust_proto::aconfig::Flag_state as ProtoFlagState;
    pub use aconfig_rust_proto::aconfig::Flag_value as ProtoFlagValue;
    pub use aconfig_rust_proto::aconfig::Flag_values as ProtoFlagValues;
    pub use aconfig_rust_proto::aconfig::Parsed_flag as ProtoParsedFlag;
    pub use aconfig_rust_proto::aconfig::Parsed_flags as ProtoParsedFlags;
    pub use aconfig_rust_proto::aconfig::Tracepoint as ProtoTracepoint;
}

// ---- When building with cargo ----
#[cfg(feature = "cargo")]
mod auto_generated {
    // include! statements should be avoided (because they import file contents verbatim), but
    // because this is only used during local development, and only if using cargo instead of the
    // Android tool-chain, we allow it
    include!(concat!(env!("OUT_DIR"), "/aconfig_proto/mod.rs"));
    pub use aconfig::flag_metadata::Flag_purpose as ProtoFlagPurpose;
    pub use aconfig::Flag_declaration as ProtoFlagDeclaration;
    pub use aconfig::Flag_declarations as ProtoFlagDeclarations;
    pub use aconfig::Flag_metadata as ProtoFlagMetadata;
    pub use aconfig::Flag_permission as ProtoFlagPermission;
    pub use aconfig::Flag_state as ProtoFlagState;
    pub use aconfig::Flag_value as ProtoFlagValue;
    pub use aconfig::Flag_values as ProtoFlagValues;
    pub use aconfig::Parsed_flag as ProtoParsedFlag;
    pub use aconfig::Parsed_flags as ProtoParsedFlags;
    pub use aconfig::Tracepoint as ProtoTracepoint;
}

// ---- Common for both the Android tool-chain and cargo ----
pub use auto_generated::*;

use anyhow::Result;
use paste::paste;

/// Path to proto file
const ACONFIG_PROTO_PATH: &str = "//build/make/tools/aconfig/aconfig_protos/protos/aconfig.proto";

/// Check if the name identifier is valid
pub fn is_valid_name_ident(s: &str) -> bool {
    // Identifiers must match [a-z][a-z0-9_]*, except consecutive underscores are not allowed
    if s.contains("__") {
        return false;
    }
    let mut chars = s.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !first.is_ascii_lowercase() {
        return false;
    }
    chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
}

/// Check if the package identifier is valid
pub fn is_valid_package_ident(s: &str) -> bool {
    if !s.contains('.') {
        return false;
    }
    s.split('.').all(is_valid_name_ident)
}

/// Check if the container identifier is valid
pub fn is_valid_container_ident(s: &str) -> bool {
    s.split('.').all(is_valid_name_ident)
}

fn try_from_text_proto<T>(s: &str) -> Result<T>
where
    T: protobuf::MessageFull,
{
    protobuf::text_format::parse_from_str(s).map_err(|e| e.into())
}

macro_rules! ensure_required_fields {
    ($type:expr, $struct:expr, $($field:expr),+) => {
        $(
        paste! {
            ensure!($struct.[<has_ $field>](), "bad {}: missing {}", $type, $field);
        }
        )+
    };
}

/// Utility module for flag_declaration proto
pub mod flag_declaration {
    use super::*;
    use anyhow::ensure;

    /// Ensure the proto instance is valid by checking its fields
    pub fn verify_fields(pdf: &ProtoFlagDeclaration) -> Result<()> {
        ensure_required_fields!("flag declaration", pdf, "name", "namespace", "description");

        ensure!(
            is_valid_name_ident(pdf.name()),
            "bad flag declaration: bad name {} expected snake_case string; \
        see {ACONFIG_PROTO_PATH} for details",
            pdf.name()
        );
        ensure!(
            is_valid_name_ident(pdf.namespace()),
            "bad flag declaration: bad namespace {} expected snake_case string; \
        see {ACONFIG_PROTO_PATH} for details",
            pdf.namespace()
        );
        ensure!(!pdf.description().is_empty(), "bad flag declaration: empty description");
        ensure!(pdf.bug.len() == 1, "bad flag declaration: exactly one bug required");

        Ok(())
    }
}

/// Utility module for flag_declarations proto
pub mod flag_declarations {
    use super::*;
    use anyhow::ensure;

    /// Construct a proto instance from a textproto string content
    pub fn try_from_text_proto(s: &str) -> Result<ProtoFlagDeclarations> {
        let pdf: ProtoFlagDeclarations = super::try_from_text_proto(s)?;
        verify_fields(&pdf)?;
        Ok(pdf)
    }

    /// Ensure the proto instance is valid by checking its fields
    pub fn verify_fields(pdf: &ProtoFlagDeclarations) -> Result<()> {
        ensure_required_fields!("flag declarations", pdf, "package");
        // TODO(b/312769710): Make the container field required.
        ensure!(
            is_valid_package_ident(pdf.package()),
            "bad flag declarations: bad package {} expected snake_case strings delimited by dots; \
        see {ACONFIG_PROTO_PATH} for details",
            pdf.package()
        );
        ensure!(
            !pdf.has_container() || is_valid_container_ident(pdf.container()),
            "bad flag declarations: bad container"
        );
        for flag_declaration in pdf.flag.iter() {
            super::flag_declaration::verify_fields(flag_declaration)?;
        }

        Ok(())
    }
}

/// Utility module for flag_value proto
pub mod flag_value {
    use super::*;
    use anyhow::ensure;

    /// Ensure the proto instance is valid by checking its fields
    pub fn verify_fields(fv: &ProtoFlagValue) -> Result<()> {
        ensure_required_fields!("flag value", fv, "package", "name", "state", "permission");

        ensure!(
            is_valid_package_ident(fv.package()),
            "bad flag value: bad package {} expected snake_case strings delimited by dots; \
        see {ACONFIG_PROTO_PATH} for details",
            fv.package()
        );
        ensure!(
            is_valid_name_ident(fv.name()),
            "bad flag value: bad name {} expected snake_case string; \
        see {ACONFIG_PROTO_PATH} for details",
            fv.name()
        );

        Ok(())
    }
}

/// Utility module for flag_values proto
pub mod flag_values {
    use super::*;

    /// Construct a proto instance from a textproto string content
    pub fn try_from_text_proto(s: &str) -> Result<ProtoFlagValues> {
        let pfv: ProtoFlagValues = super::try_from_text_proto(s)?;
        verify_fields(&pfv)?;
        Ok(pfv)
    }

    /// Ensure the proto instance is valid by checking its fields
    pub fn verify_fields(pfv: &ProtoFlagValues) -> Result<()> {
        for flag_value in pfv.flag_value.iter() {
            super::flag_value::verify_fields(flag_value)?;
        }
        Ok(())
    }
}

/// Utility module for flag_permission proto enum
pub mod flag_permission {
    use super::*;
    use anyhow::bail;

    /// Construct a flag permission proto enum from string
    pub fn parse_from_str(permission: &str) -> Result<ProtoFlagPermission> {
        match permission.to_ascii_lowercase().as_str() {
            "read_write" => Ok(ProtoFlagPermission::READ_WRITE),
            "read_only" => Ok(ProtoFlagPermission::READ_ONLY),
            _ => bail!("Permission needs to be read_only or read_write."),
        }
    }

    /// Serialize flag permission proto enum to string
    pub fn to_string(permission: &ProtoFlagPermission) -> &str {
        match permission {
            ProtoFlagPermission::READ_WRITE => "read_write",
            ProtoFlagPermission::READ_ONLY => "read_only",
        }
    }
}

/// Utility module for tracepoint proto
pub mod tracepoint {
    use super::*;
    use anyhow::ensure;

    /// Ensure the proto instance is valid by checking its fields
    pub fn verify_fields(tp: &ProtoTracepoint) -> Result<()> {
        ensure_required_fields!("tracepoint", tp, "source", "state", "permission");

        ensure!(!tp.source().is_empty(), "bad tracepoint: empty source");

        Ok(())
    }
}

/// Utility module for parsed_flag proto
pub mod parsed_flag {
    use super::*;
    use anyhow::ensure;

    /// Ensure the proto instance is valid by checking its fields
    pub fn verify_fields(pf: &ProtoParsedFlag) -> Result<()> {
        ensure_required_fields!(
            "parsed flag",
            pf,
            "package",
            "name",
            "namespace",
            "description",
            "state",
            "permission"
        );

        ensure!(
            is_valid_package_ident(pf.package()),
            "bad parsed flag: bad package {} expected snake_case strings delimited by dots; \
        see {ACONFIG_PROTO_PATH} for details",
            pf.package()
        );
        ensure!(
            !pf.has_container() || is_valid_container_ident(pf.container()),
            "bad parsed flag: bad container"
        );
        ensure!(
            is_valid_name_ident(pf.name()),
            "bad parsed flag: bad name {} expected snake_case string; \
        see {ACONFIG_PROTO_PATH} for details",
            pf.name()
        );
        ensure!(
            is_valid_name_ident(pf.namespace()),
            "bad parsed flag: bad namespace {} expected snake_case string; \
        see {ACONFIG_PROTO_PATH} for details",
            pf.namespace()
        );
        ensure!(!pf.description().is_empty(), "bad parsed flag: empty description");
        ensure!(!pf.trace.is_empty(), "bad parsed flag: empty trace");
        for tp in pf.trace.iter() {
            super::tracepoint::verify_fields(tp)?;
        }
        ensure!(pf.bug.len() == 1, "bad flag declaration: exactly one bug required");
        if pf.is_fixed_read_only() {
            ensure!(
                pf.permission() == ProtoFlagPermission::READ_ONLY,
                "bad parsed flag: flag is is_fixed_read_only but permission is not READ_ONLY"
            );
            for tp in pf.trace.iter() {
                ensure!(tp.permission() == ProtoFlagPermission::READ_ONLY,
                "bad parsed flag: flag is is_fixed_read_only but a tracepoint's permission is not READ_ONLY"
                );
            }
        }

        Ok(())
    }

    /// Get the file path of the corresponding flag declaration
    pub fn path_to_declaration(pf: &ProtoParsedFlag) -> &str {
        debug_assert!(!pf.trace.is_empty());
        pf.trace[0].source()
    }
}

/// Utility module for parsed_flags proto
pub mod parsed_flags {
    use super::*;
    use anyhow::bail;
    use std::cmp::Ordering;

    /// Construct a proto instance from a binary proto bytes
    pub fn try_from_binary_proto(bytes: &[u8]) -> Result<ProtoParsedFlags> {
        let message: ProtoParsedFlags = protobuf::Message::parse_from_bytes(bytes)?;
        verify_fields(&message)?;
        Ok(message)
    }

    /// Ensure the proto instance is valid by checking its fields
    pub fn verify_fields(pf: &ProtoParsedFlags) -> Result<()> {
        use crate::parsed_flag::path_to_declaration;

        let mut previous: Option<&ProtoParsedFlag> = None;
        for parsed_flag in pf.parsed_flag.iter() {
            if let Some(prev) = previous {
                let a = create_sorting_key(prev);
                let b = create_sorting_key(parsed_flag);
                match a.cmp(&b) {
                    Ordering::Less => {}
                    Ordering::Equal => bail!(
                        "bad parsed flags: duplicate flag {} (defined in {} and {})",
                        a,
                        path_to_declaration(prev),
                        path_to_declaration(parsed_flag)
                    ),
                    Ordering::Greater => {
                        bail!("bad parsed flags: not sorted: {} comes before {}", a, b)
                    }
                }
            }
            super::parsed_flag::verify_fields(parsed_flag)?;
            previous = Some(parsed_flag);
        }
        Ok(())
    }

    /// Merge multipe parsed_flags proto
    pub fn merge(parsed_flags: Vec<ProtoParsedFlags>, dedup: bool) -> Result<ProtoParsedFlags> {
        let mut merged = ProtoParsedFlags::new();
        for mut pfs in parsed_flags.into_iter() {
            merged.parsed_flag.append(&mut pfs.parsed_flag);
        }
        merged.parsed_flag.sort_by_cached_key(create_sorting_key);
        if dedup {
            // Deduplicate identical protobuf messages.  Messages with the same sorting key but
            // different fields (including the path to the original source file) will not be
            // deduplicated and trigger an error in verify_fields.
            merged.parsed_flag.dedup();
        }
        verify_fields(&merged)?;
        Ok(merged)
    }

    /// Sort parsed flags
    pub fn sort_parsed_flags(pf: &mut ProtoParsedFlags) {
        pf.parsed_flag.sort_by_key(create_sorting_key);
    }

    fn create_sorting_key(pf: &ProtoParsedFlag) -> String {
        pf.fully_qualified_name()
    }
}

/// ParsedFlagExt trait
pub trait ParsedFlagExt {
    /// Return the fully qualified name
    fn fully_qualified_name(&self) -> String;
}

impl ParsedFlagExt for ProtoParsedFlag {
    fn fully_qualified_name(&self) -> String {
        format!("{}.{}", self.package(), self.name())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_flag_declarations_try_from_text_proto() {
        // valid input
        let flag_declarations = flag_declarations::try_from_text_proto(
            r#"
package: "com.foo.bar"
container: "system"
flag {
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: "123"
    is_exported: true
}
flag {
    name: "second"
    namespace: "second_ns"
    description: "This is the description of the second flag."
    bug: "abc"
    is_fixed_read_only: true
}
"#,
        )
        .unwrap();
        assert_eq!(flag_declarations.package(), "com.foo.bar");
        assert_eq!(flag_declarations.container(), "system");
        let first = flag_declarations.flag.iter().find(|pf| pf.name() == "first").unwrap();
        assert_eq!(first.name(), "first");
        assert_eq!(first.namespace(), "first_ns");
        assert_eq!(first.description(), "This is the description of the first flag.");
        assert_eq!(first.bug, vec!["123"]);
        assert!(!first.is_fixed_read_only());
        assert!(first.is_exported());
        let second = flag_declarations.flag.iter().find(|pf| pf.name() == "second").unwrap();
        assert_eq!(second.name(), "second");
        assert_eq!(second.namespace(), "second_ns");
        assert_eq!(second.description(), "This is the description of the second flag.");
        assert_eq!(second.bug, vec!["abc"]);
        assert!(second.is_fixed_read_only());
        assert!(!second.is_exported());

        // valid input: missing container in flag declarations is supported
        let flag_declarations = flag_declarations::try_from_text_proto(
            r#"
package: "com.foo.bar"
flag {
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: "123"
}
"#,
        )
        .unwrap();
        assert_eq!(flag_declarations.container(), "");
        assert!(!flag_declarations.has_container());

        // bad input: missing package in flag declarations
        let error = flag_declarations::try_from_text_proto(
            r#"
container: "system"
flag {
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
}
flag {
    name: "second"
    namespace: "second_ns"
    description: "This is the description of the second flag."
}
"#,
        )
        .unwrap_err();
        assert_eq!(format!("{:?}", error), "bad flag declarations: missing package");

        // bad input: missing namespace in flag declaration
        let error = flag_declarations::try_from_text_proto(
            r#"
package: "com.foo.bar"
container: "system"
flag {
    name: "first"
    description: "This is the description of the first flag."
}
flag {
    name: "second"
    namespace: "second_ns"
    description: "This is the description of the second flag."
}
"#,
        )
        .unwrap_err();
        assert_eq!(format!("{:?}", error), "bad flag declaration: missing namespace");

        // bad input: bad package name in flag declarations
        let error = flag_declarations::try_from_text_proto(
            r#"
package: "_com.FOO__BAR"
container: "system"
flag {
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
}
flag {
    name: "second"
    namespace: "second_ns"
    description: "This is the description of the second flag."
}
"#,
        )
        .unwrap_err();
        assert!(format!("{:?}", error).contains("bad flag declarations: bad package"));

        // bad input: bad name in flag declaration
        let error = flag_declarations::try_from_text_proto(
            r#"
package: "com.foo.bar"
container: "system"
flag {
    name: "FIRST"
    namespace: "first_ns"
    description: "This is the description of the first flag."
}
flag {
    name: "second"
    namespace: "second_ns"
    description: "This is the description of the second flag."
}
"#,
        )
        .unwrap_err();
        assert!(format!("{:?}", error).contains("bad flag declaration: bad name"));

        // bad input: no bug entries in flag declaration
        let error = flag_declarations::try_from_text_proto(
            r#"
package: "com.foo.bar"
container: "system"
flag {
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
}
"#,
        )
        .unwrap_err();
        assert!(format!("{:?}", error).contains("bad flag declaration: exactly one bug required"));

        // bad input: multiple bug entries in flag declaration
        let error = flag_declarations::try_from_text_proto(
            r#"
package: "com.foo.bar"
container: "system"
flag {
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: "123"
    bug: "abc"
}
"#,
        )
        .unwrap_err();
        assert!(format!("{:?}", error).contains("bad flag declaration: exactly one bug required"));

        // bad input: invalid container name in flag declaration
        let error = flag_declarations::try_from_text_proto(
            r#"
package: "com.foo.bar"
container: "__bad_bad_container.com"
flag {
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: "123"
    bug: "abc"
}
"#,
        )
        .unwrap_err();
        assert!(format!("{:?}", error).contains("bad flag declarations: bad container"));

        // TODO(b/312769710): Verify error when container is missing.
    }

    #[test]
    fn test_flag_values_try_from_text_proto() {
        // valid input
        let flag_values = flag_values::try_from_text_proto(
            r#"
flag_value {
    package: "com.first"
    name: "first"
    state: DISABLED
    permission: READ_ONLY
}
flag_value {
    package: "com.second"
    name: "second"
    state: ENABLED
    permission: READ_WRITE
}
"#,
        )
        .unwrap();
        let first = flag_values.flag_value.iter().find(|fv| fv.name() == "first").unwrap();
        assert_eq!(first.package(), "com.first");
        assert_eq!(first.name(), "first");
        assert_eq!(first.state(), ProtoFlagState::DISABLED);
        assert_eq!(first.permission(), ProtoFlagPermission::READ_ONLY);
        let second = flag_values.flag_value.iter().find(|fv| fv.name() == "second").unwrap();
        assert_eq!(second.package(), "com.second");
        assert_eq!(second.name(), "second");
        assert_eq!(second.state(), ProtoFlagState::ENABLED);
        assert_eq!(second.permission(), ProtoFlagPermission::READ_WRITE);

        // bad input: bad package in flag value
        let error = flag_values::try_from_text_proto(
            r#"
flag_value {
    package: "COM.FIRST"
    name: "first"
    state: DISABLED
    permission: READ_ONLY
}
"#,
        )
        .unwrap_err();
        assert!(format!("{:?}", error).contains("bad flag value: bad package"));

        // bad input: bad name in flag value
        let error = flag_values::try_from_text_proto(
            r#"
flag_value {
    package: "com.first"
    name: "FIRST"
    state: DISABLED
    permission: READ_ONLY
}
"#,
        )
        .unwrap_err();
        assert!(format!("{:?}", error).contains("bad flag value: bad name"));

        // bad input: missing state in flag value
        let error = flag_values::try_from_text_proto(
            r#"
flag_value {
    package: "com.first"
    name: "first"
    permission: READ_ONLY
}
"#,
        )
        .unwrap_err();
        assert_eq!(format!("{:?}", error), "bad flag value: missing state");

        // bad input: missing permission in flag value
        let error = flag_values::try_from_text_proto(
            r#"
flag_value {
    package: "com.first"
    name: "first"
    state: DISABLED
}
"#,
        )
        .unwrap_err();
        assert_eq!(format!("{:?}", error), "bad flag value: missing permission");
    }

    fn try_from_binary_proto_from_text_proto(text_proto: &str) -> Result<ProtoParsedFlags> {
        use protobuf::Message;

        let parsed_flags: ProtoParsedFlags = try_from_text_proto(text_proto)?;
        let mut binary_proto = Vec::new();
        parsed_flags.write_to_vec(&mut binary_proto)?;
        parsed_flags::try_from_binary_proto(&binary_proto)
    }

    #[test]
    fn test_parsed_flags_try_from_text_proto() {
        // valid input
        let text_proto = r#"
parsed_flag {
    package: "com.first"
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: "SOME_BUG"
    state: DISABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
parsed_flag {
    package: "com.second"
    name: "second"
    namespace: "second_ns"
    description: "This is the description of the second flag."
    bug: "SOME_BUG"
    state: ENABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    trace {
        source: "flags.values"
        state: ENABLED
        permission: READ_ONLY
    }
    is_fixed_read_only: true
    container: "system"
}
"#;
        let parsed_flags = try_from_binary_proto_from_text_proto(text_proto).unwrap();
        assert_eq!(parsed_flags.parsed_flag.len(), 2);
        let second = parsed_flags.parsed_flag.iter().find(|fv| fv.name() == "second").unwrap();
        assert_eq!(second.package(), "com.second");
        assert_eq!(second.name(), "second");
        assert_eq!(second.namespace(), "second_ns");
        assert_eq!(second.description(), "This is the description of the second flag.");
        assert_eq!(second.bug, vec!["SOME_BUG"]);
        assert_eq!(second.state(), ProtoFlagState::ENABLED);
        assert_eq!(second.permission(), ProtoFlagPermission::READ_ONLY);
        assert_eq!(2, second.trace.len());
        assert_eq!(second.trace[0].source(), "flags.declarations");
        assert_eq!(second.trace[0].state(), ProtoFlagState::DISABLED);
        assert_eq!(second.trace[0].permission(), ProtoFlagPermission::READ_ONLY);
        assert_eq!(second.trace[1].source(), "flags.values");
        assert_eq!(second.trace[1].state(), ProtoFlagState::ENABLED);
        assert_eq!(second.trace[1].permission(), ProtoFlagPermission::READ_ONLY);
        assert!(second.is_fixed_read_only());

        // valid input: empty
        let parsed_flags = try_from_binary_proto_from_text_proto("").unwrap();
        assert!(parsed_flags.parsed_flag.is_empty());

        // bad input: empty trace
        let text_proto = r#"
parsed_flag {
    package: "com.first"
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    state: DISABLED
    permission: READ_ONLY
    container: "system"
}
"#;
        let error = try_from_binary_proto_from_text_proto(text_proto).unwrap_err();
        assert_eq!(format!("{:?}", error), "bad parsed flag: empty trace");

        // bad input: missing namespace in parsed_flag
        let text_proto = r#"
parsed_flag {
    package: "com.first"
    name: "first"
    description: "This is the description of the first flag."
    state: DISABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
"#;
        let error = try_from_binary_proto_from_text_proto(text_proto).unwrap_err();
        assert_eq!(format!("{:?}", error), "bad parsed flag: missing namespace");

        // bad input: parsed_flag not sorted by package
        let text_proto = r#"
parsed_flag {
    package: "bbb.bbb"
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: ""
    state: DISABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
parsed_flag {
    package: "aaa.aaa"
    name: "second"
    namespace: "second_ns"
    description: "This is the description of the second flag."
    bug: ""
    state: ENABLED
    permission: READ_WRITE
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
"#;
        let error = try_from_binary_proto_from_text_proto(text_proto).unwrap_err();
        assert_eq!(
            format!("{:?}", error),
            "bad parsed flags: not sorted: bbb.bbb.first comes before aaa.aaa.second"
        );

        // bad input: parsed_flag not sorted by name
        let text_proto = r#"
parsed_flag {
    package: "com.foo"
    name: "bbb"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: ""
    state: DISABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
parsed_flag {
    package: "com.foo"
    name: "aaa"
    namespace: "second_ns"
    description: "This is the description of the second flag."
    bug: ""
    state: ENABLED
    permission: READ_WRITE
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
"#;
        let error = try_from_binary_proto_from_text_proto(text_proto).unwrap_err();
        assert_eq!(
            format!("{:?}", error),
            "bad parsed flags: not sorted: com.foo.bbb comes before com.foo.aaa"
        );

        // bad input: duplicate flags
        let text_proto = r#"
parsed_flag {
    package: "com.foo"
    name: "bar"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: ""
    state: DISABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
parsed_flag {
    package: "com.foo"
    name: "bar"
    namespace: "second_ns"
    description: "This is the description of the second flag."
    bug: ""
    state: ENABLED
    permission: READ_WRITE
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
"#;
        let error = try_from_binary_proto_from_text_proto(text_proto).unwrap_err();
        assert_eq!(format!("{:?}", error), "bad parsed flags: duplicate flag com.foo.bar (defined in flags.declarations and flags.declarations)");
    }

    #[test]
    fn test_parsed_flag_path_to_declaration() {
        let text_proto = r#"
parsed_flag {
    package: "com.foo"
    name: "bar"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: "b/12345678"
    state: DISABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    trace {
        source: "flags.values"
        state: ENABLED
        permission: READ_ONLY
    }
    container: "system"
}
"#;
        let parsed_flags = try_from_binary_proto_from_text_proto(text_proto).unwrap();
        let parsed_flag = &parsed_flags.parsed_flag[0];
        assert_eq!(crate::parsed_flag::path_to_declaration(parsed_flag), "flags.declarations");
    }

    #[test]
    fn test_parsed_flags_merge() {
        let text_proto = r#"
parsed_flag {
    package: "com.first"
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: "a"
    state: DISABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
parsed_flag {
    package: "com.second"
    name: "second"
    namespace: "second_ns"
    description: "This is the description of the second flag."
    bug: "b"
    state: ENABLED
    permission: READ_WRITE
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
"#;
        let expected = try_from_binary_proto_from_text_proto(text_proto).unwrap();

        let text_proto = r#"
parsed_flag {
    package: "com.first"
    name: "first"
    namespace: "first_ns"
    description: "This is the description of the first flag."
    bug: "a"
    state: DISABLED
    permission: READ_ONLY
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
"#;
        let first = try_from_binary_proto_from_text_proto(text_proto).unwrap();

        let text_proto = r#"
parsed_flag {
    package: "com.second"
    name: "second"
    namespace: "second_ns"
    bug: "b"
    description: "This is the description of the second flag."
    state: ENABLED
    permission: READ_WRITE
    trace {
        source: "flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
    container: "system"
}
"#;
        let second = try_from_binary_proto_from_text_proto(text_proto).unwrap();

        let text_proto = r#"
parsed_flag {
    package: "com.second"
    name: "second"
    namespace: "second_ns"
    bug: "b"
    description: "This is the description of the second flag."
    state: ENABLED
    permission: READ_WRITE
    trace {
        source: "duplicate/flags.declarations"
        state: DISABLED
        permission: READ_ONLY
    }
}
"#;
        let second_duplicate = try_from_binary_proto_from_text_proto(text_proto).unwrap();

        // bad cases

        // two of the same flag with dedup disabled
        let error = parsed_flags::merge(vec![first.clone(), first.clone()], false).unwrap_err();
        assert_eq!(format!("{:?}", error), "bad parsed flags: duplicate flag com.first.first (defined in flags.declarations and flags.declarations)");

        // two conflicting flags with dedup disabled
        let error =
            parsed_flags::merge(vec![second.clone(), second_duplicate.clone()], false).unwrap_err();
        assert_eq!(format!("{:?}", error), "bad parsed flags: duplicate flag com.second.second (defined in flags.declarations and duplicate/flags.declarations)");

        // two conflicting flags with dedup enabled
        let error =
            parsed_flags::merge(vec![second.clone(), second_duplicate.clone()], true).unwrap_err();
        assert_eq!(format!("{:?}", error), "bad parsed flags: duplicate flag com.second.second (defined in flags.declarations and duplicate/flags.declarations)");

        // valid cases
        assert!(parsed_flags::merge(vec![], false).unwrap().parsed_flag.is_empty());
        assert!(parsed_flags::merge(vec![], true).unwrap().parsed_flag.is_empty());
        assert_eq!(first, parsed_flags::merge(vec![first.clone()], false).unwrap());
        assert_eq!(first, parsed_flags::merge(vec![first.clone()], true).unwrap());
        assert_eq!(
            expected,
            parsed_flags::merge(vec![first.clone(), second.clone()], false).unwrap()
        );
        assert_eq!(
            expected,
            parsed_flags::merge(vec![first.clone(), second.clone()], true).unwrap()
        );
        assert_eq!(
            expected,
            parsed_flags::merge(vec![second.clone(), first.clone()], false).unwrap()
        );
        assert_eq!(
            expected,
            parsed_flags::merge(vec![second.clone(), first.clone()], true).unwrap()
        );

        // two identical flags with dedup enabled
        assert_eq!(first, parsed_flags::merge(vec![first.clone(), first.clone()], true).unwrap());
    }

    #[test]
    fn test_is_valid_name_ident() {
        assert!(is_valid_name_ident("foo"));
        assert!(is_valid_name_ident("foo_bar_123"));
        assert!(is_valid_name_ident("foo_"));

        assert!(!is_valid_name_ident(""));
        assert!(!is_valid_name_ident("123_foo"));
        assert!(!is_valid_name_ident("foo-bar"));
        assert!(!is_valid_name_ident("foo-b\u{00e5}r"));
        assert!(!is_valid_name_ident("foo__bar"));
        assert!(!is_valid_name_ident("_foo"));
    }

    #[test]
    fn test_is_valid_package_ident() {
        assert!(is_valid_package_ident("foo.bar"));
        assert!(is_valid_package_ident("foo.bar_baz"));
        assert!(is_valid_package_ident("foo.bar.a123"));

        assert!(!is_valid_package_ident("foo_bar_123"));
        assert!(!is_valid_package_ident("foo"));
        assert!(!is_valid_package_ident("foo._bar"));
        assert!(!is_valid_package_ident(""));
        assert!(!is_valid_package_ident("123_foo"));
        assert!(!is_valid_package_ident("foo-bar"));
        assert!(!is_valid_package_ident("foo-b\u{00e5}r"));
        assert!(!is_valid_package_ident("foo.bar.123"));
        assert!(!is_valid_package_ident(".foo.bar"));
        assert!(!is_valid_package_ident("foo.bar."));
        assert!(!is_valid_package_ident("."));
        assert!(!is_valid_package_ident(".."));
        assert!(!is_valid_package_ident("foo..bar"));
        assert!(!is_valid_package_ident("foo.__bar"));
    }

    #[test]
    fn test_is_valid_container_ident() {
        assert!(is_valid_container_ident("foo.bar"));
        assert!(is_valid_container_ident("foo.bar_baz"));
        assert!(is_valid_container_ident("foo.bar.a123"));
        assert!(is_valid_container_ident("foo"));
        assert!(is_valid_container_ident("foo_bar_123"));

        assert!(!is_valid_container_ident(""));
        assert!(!is_valid_container_ident("foo._bar"));
        assert!(!is_valid_container_ident("_foo"));
        assert!(!is_valid_container_ident("123_foo"));
        assert!(!is_valid_container_ident("foo-bar"));
        assert!(!is_valid_container_ident("foo-b\u{00e5}r"));
        assert!(!is_valid_container_ident("foo.bar.123"));
        assert!(!is_valid_container_ident(".foo.bar"));
        assert!(!is_valid_container_ident("foo.bar."));
        assert!(!is_valid_container_ident("."));
        assert!(!is_valid_container_ident(".."));
        assert!(!is_valid_container_ident("foo..bar"));
        assert!(!is_valid_container_ident("foo.__bar"));
    }
}