blob: d02a07967a2b4c484546e6df6c58852afa484dbd [file] [log] [blame]
Adam Snaider48a62f32023-10-02 15:49:23 -07001use std::{
2 env,
3 ffi::{CString, OsStr, OsString},
4 os::unix::prelude::OsStrExt,
5 sync::Once,
6};
7
8use clap::{
9 error::{ContextKind, ContextValue},
10 Arg, ArgAction, Error, Parser,
11};
Brian Silvermane4c79ce2022-08-15 05:57:28 -070012
13autocxx::include_cpp! (
Adam Snaider48a62f32023-10-02 15:49:23 -070014#include "aos/init_for_rust.h"
Brian Silvermane4c79ce2022-08-15 05:57:28 -070015
16safety!(unsafe)
17
18generate!("aos::InitFromRust")
Adam Snaider48a62f32023-10-02 15:49:23 -070019generate!("aos::GetCppFlags")
20generate!("aos::FlagInfo")
21generate!("aos::SetCommandLineOption")
22generate!("aos::GetCommandLineOption")
Brian Silvermane4c79ce2022-08-15 05:57:28 -070023);
24
Adam Snaiderc8b7e752023-09-14 14:27:53 -070025/// Initializes AOS.
Adam Snaider43516782023-06-26 15:14:18 -070026pub fn init() {
Brian Silvermane4c79ce2022-08-15 05:57:28 -070027 static ONCE: Once = Once::new();
28 ONCE.call_once(|| {
Adam Snaider5298f002023-11-22 11:00:31 -080029 // We leak the `CString` with `into_raw`. It's not sound for C++ to free
30 // it but `InitGoogleLogging` requries that it is long-lived.
Adam Snaider48a62f32023-10-02 15:49:23 -070031 let argv0 = std::env::args()
32 .map(|arg| CString::new(arg).expect("Arg may not have NUL"))
33 .next()
Adam Snaider5298f002023-11-22 11:00:31 -080034 .expect("Missing argv[0]?")
35 .into_raw();
Adam Snaider48a62f32023-10-02 15:49:23 -070036 // SAFETY: argv0 is a well-defined CString.
37 unsafe {
Adam Snaider5298f002023-11-22 11:00:31 -080038 ffi::aos::InitFromRust(argv0);
Adam Snaider48a62f32023-10-02 15:49:23 -070039 }
Brian Silvermane4c79ce2022-08-15 05:57:28 -070040 });
Brian Silvermane4c79ce2022-08-15 05:57:28 -070041}
Adam Snaider48a62f32023-10-02 15:49:23 -070042
43/// Trait used to append C++ gFlags to a clap CLI.
44pub trait WithCppFlags: Parser {
45 /// Parses the comannd line arguments while also setting the C++ gFlags.
46 fn parse_with_cpp_flags() -> Self {
47 Self::parse_with_cpp_flags_from(env::args_os())
48 }
49
50 /// Like [`parse_with_cpp_flags`] but read from an iterator.
51 fn parse_with_cpp_flags_from<I, T>(itr: I) -> Self
52 where
53 I: IntoIterator<Item = T>,
54 T: Into<OsString> + Clone,
55 {
56 let cxxflags = ffi::aos::GetCppFlags();
57 let cxxflags: Vec<CxxFlag> = cxxflags
58 .iter()
59 .map(|flag| CxxFlag::from(flag))
60 .filter(|flag| flag.name != "help" && flag.name != "version")
61 .collect();
62
63 let mut command = Self::command()
64 .next_help_heading("Flags from C++")
65 .args(cxxflags.iter().cloned());
66
67 let matches = command.clone().get_matches_from(itr);
68
69 for cxxflag in cxxflags {
70 let Some(mut value) = matches.get_raw(&cxxflag.name) else {
71 continue;
72 };
73 // We grab the last match as GFlags does.
74 let value = value.next_back().unwrap();
75 cxxflag.set(value).unwrap_or_else(|_| {
76 let mut error = Error::new(clap::error::ErrorKind::InvalidValue);
77
78 // Let user know how they messed up.
79 error.insert(
80 ContextKind::InvalidArg,
81 ContextValue::String(format!("--{}", cxxflag.name)),
82 );
83 error.insert(
84 ContextKind::InvalidValue,
85 ContextValue::String(
86 value
87 .to_owned()
88 .into_string()
89 .expect("Invalid UTF-8 String"),
90 ),
91 );
92 error.format(&mut command).exit()
93 })
94 }
95
96 match Self::from_arg_matches(&matches) {
97 Ok(flags) => flags,
98 Err(e) => e.format(&mut command).exit(),
99 }
100 }
101}
102
103impl<T: Parser> WithCppFlags for T {}
104
105#[derive(Clone)]
106#[allow(unused)]
107struct CxxFlag {
108 name: String,
109 ty: String,
110 description: String,
111 default_value: String,
112 filename: String,
113}
114
115struct SetFlagError;
116
117impl CxxFlag {
118 /// Sets the command gFlag to the specified value.
119 fn set(&self, value: &OsStr) -> Result<(), SetFlagError> {
120 unsafe {
121 let name = CString::new(self.name.clone()).expect("Flag name may not have NUL");
122 let value = CString::new(value.as_bytes()).expect("Arg may not have NUL");
123 if ffi::aos::SetCommandLineOption(name.as_ptr(), value.as_ptr()) {
124 Ok(())
125 } else {
126 Err(SetFlagError)
127 }
128 }
129 }
130
131 fn get_option(name: &str) -> String {
132 unsafe {
133 let name = CString::new(name).expect("Flag may not have NUL");
134 ffi::aos::GetCommandLineOption(name.as_ptr()).to_string()
135 }
136 }
137}
138
139impl From<&ffi::aos::FlagInfo> for CxxFlag {
140 fn from(value: &ffi::aos::FlagInfo) -> Self {
141 Self {
142 name: value.name().to_string(),
143 ty: value.ty().to_string(),
144 description: value.description().to_string(),
145 default_value: value.default_value().to_string(),
146 filename: value.filename().to_string(),
147 }
148 }
149}
150
151impl From<CxxFlag> for Arg {
152 fn from(value: CxxFlag) -> Self {
153 assert_ne!(&value.name, "help");
154 Arg::new(&value.name)
155 .long(&value.name)
156 .help(&value.description)
157 .default_value(&value.default_value)
158 .action(ArgAction::Set)
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use std::sync::Mutex;
165
166 use super::*;
167
168 #[derive(Parser)]
169 #[command()]
170 struct App {
171 #[arg(long)]
172 myarg: u64,
173 }
174
175 // We are sharing global state through gFlags. Use a mutex to prevent races.
176 static MUTEX: Mutex<()> = Mutex::new(());
177
178 #[test]
179 fn simple_rust() {
180 let _guard = MUTEX.lock();
181 let app = App::parse_with_cpp_flags_from(&["mytest", "--myarg", "23"]);
182 assert_eq!(app.myarg, 23);
183 }
184
185 #[test]
186 fn set_cxx_flag() {
187 let _guard = MUTEX.lock();
188 let app = App::parse_with_cpp_flags_from(&[
189 "mytest",
190 "--alsologtostderr",
191 "true",
192 "--myarg",
193 "23",
194 ]);
195 assert_eq!(app.myarg, 23);
196 assert_eq!(CxxFlag::get_option("alsologtostderr"), "true");
197 }
198}