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