1 // Copyright 2022 Google, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::env;
16 use std::fs::File;
17 use std::path::{Path, PathBuf};
18 use std::process::{Command, Stdio};
19
main()20 fn main() {
21 install_generated_module(
22 "lmp_packets.rs",
23 "LMP_PACKETS_PREBUILT",
24 &PathBuf::from("lmp_packets.pdl").canonicalize().unwrap(),
25 );
26 install_generated_module(
27 "llcp_packets.rs",
28 "LLCP_PACKETS_PREBUILT",
29 &PathBuf::from("llcp_packets.pdl").canonicalize().unwrap(),
30 );
31 install_generated_module(
32 "hci_packets.rs",
33 "HCI_PACKETS_PREBUILT",
34 &PathBuf::from("../packets/hci_packets.pdl").canonicalize().unwrap(),
35 );
36 }
37
install_generated_module(module_name: &str, prebuilt_var: &str, pdl_name: &PathBuf)38 fn install_generated_module(module_name: &str, prebuilt_var: &str, pdl_name: &PathBuf) {
39 let module_prebuilt = match env::var(prebuilt_var) {
40 Ok(dir) => PathBuf::from(dir),
41 Err(_) => PathBuf::from(module_name),
42 };
43
44 if Path::new(module_prebuilt.as_os_str()).exists() {
45 let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
46 std::fs::copy(
47 module_prebuilt.as_os_str().to_str().unwrap(),
48 out_dir.join(module_name).as_os_str().to_str().unwrap(),
49 )
50 .unwrap();
51 } else {
52 generate_module(pdl_name);
53 }
54 }
55
generate_module(in_file: &PathBuf)56 fn generate_module(in_file: &PathBuf) {
57 let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
58 let out_file =
59 File::create(out_dir.join(in_file.file_name().unwrap()).with_extension("rs")).unwrap();
60
61 // Find the pdl tool. Expecting it at CARGO_HOME/bin
62 let pdl = match env::var("CARGO_HOME") {
63 Ok(dir) => PathBuf::from(dir).join("bin").join("pdlc"),
64 Err(_) => PathBuf::from("pdlc"),
65 };
66
67 if !Path::new(pdl.as_os_str()).exists() {
68 panic!("pdl not found in the current environment: {:?}", pdl.as_os_str().to_str().unwrap());
69 }
70
71 println!("cargo:rerun-if-changed={}", in_file.display());
72 let output = Command::new(pdl.as_os_str().to_str().unwrap())
73 .arg("--output-format")
74 .arg("rust")
75 .arg(in_file)
76 .stdout(Stdio::from(out_file))
77 .output()
78 .unwrap();
79
80 println!(
81 "Status: {}, stderr: {}",
82 output.status,
83 String::from_utf8_lossy(output.stderr.as_slice())
84 );
85
86 assert!(output.status.success());
87 }
88