blob: 9d52ccede82960ec7e4d108f91a09621a6dfcce1 [file] [log] [blame]
Zhi Doueb744892023-05-10 04:02:33 +00001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use anyhow::Result;
18use serde::Serialize;
19use tinytemplate::TinyTemplate;
20
21use crate::aconfig::{FlagState, Permission};
22use crate::cache::{Cache, Item};
23
24pub struct GeneratedFile {
25 pub file_content: String,
26 pub file_name: String,
27}
28
29pub fn generate_java_code(cache: &Cache) -> Result<GeneratedFile> {
30 let class_elements: Vec<ClassElement> = cache.iter().map(create_class_element).collect();
31 let readwrite = class_elements.iter().any(|item| item.readwrite);
32 let namespace = uppercase_first_letter(
33 cache.iter().find(|item| !item.namespace.is_empty()).unwrap().namespace.as_str(),
34 );
35 let context = Context { namespace: namespace.clone(), readwrite, class_elements };
36 let mut template = TinyTemplate::new();
37 template.add_template("java_code_gen", include_str!("../templates/java.template"))?;
38 let file_content = template.render("java_code_gen", &context)?;
39 Ok(GeneratedFile { file_content, file_name: format!("{}.java", namespace) })
40}
41
42#[derive(Serialize)]
43struct Context {
44 pub namespace: String,
45 pub readwrite: bool,
46 pub class_elements: Vec<ClassElement>,
47}
48
49#[derive(Serialize)]
50struct ClassElement {
51 pub method_name: String,
52 pub readwrite: bool,
53 pub default_value: String,
54 pub feature_name: String,
55 pub flag_name: String,
56}
57
58fn create_class_element(item: &Item) -> ClassElement {
59 ClassElement {
60 method_name: item.name.clone(),
61 readwrite: item.permission == Permission::ReadWrite,
62 default_value: if item.state == FlagState::Enabled {
63 "true".to_string()
64 } else {
65 "false".to_string()
66 },
67 feature_name: item.name.clone(),
68 flag_name: item.name.clone(),
69 }
70}
71
72fn uppercase_first_letter(s: &str) -> String {
73 s.chars()
74 .enumerate()
75 .map(
76 |(index, ch)| {
77 if index == 0 {
78 ch.to_ascii_uppercase()
79 } else {
80 ch.to_ascii_lowercase()
81 }
82 },
83 )
84 .collect()
85}
86
87#[cfg(test)]
88mod tests {
89 use super::*;
90 use crate::aconfig::{Flag, Value};
91 use crate::commands::Source;
92
93 #[test]
94 fn test_generate_java_code() {
95 let namespace = "TeSTFlaG";
96 let mut cache = Cache::new(1, namespace.to_string());
97 cache
98 .add_flag(
99 Source::File("test.txt".to_string()),
100 Flag {
101 name: "test".to_string(),
102 description: "buildtime enable".to_string(),
103 values: vec![Value::default(FlagState::Enabled, Permission::ReadOnly)],
104 },
105 )
106 .unwrap();
107 cache
108 .add_flag(
109 Source::File("test2.txt".to_string()),
110 Flag {
111 name: "test2".to_string(),
112 description: "runtime disable".to_string(),
113 values: vec![Value::default(FlagState::Disabled, Permission::ReadWrite)],
114 },
115 )
116 .unwrap();
117 let expect_content = "package com.android.aconfig;
118
119 import android.provider.DeviceConfig;
120
121 public final class Testflag {
122
123 public static boolean test() {
124 return true;
125 }
126
127 public static boolean test2() {
128 return DeviceConfig.getBoolean(
129 \"Testflag\",
130 \"test2__test2\",
131 false
132 );
133 }
134
135 }
136 ";
137 let expected_file_name = format!("{}.java", uppercase_first_letter(namespace));
138 let generated_file = generate_java_code(&cache).unwrap();
139 assert_eq!(expected_file_name, generated_file.file_name);
140 assert_eq!(expect_content.replace(' ', ""), generated_file.file_content.replace(' ', ""));
141 }
142}