Adam Snaider | 48a62f3 | 2023-10-02 15:49:23 -0700 | [diff] [blame^] | 1 | use std::{ |
| 2 | env, |
| 3 | ffi::{CString, OsStr, OsString}, |
| 4 | os::unix::prelude::OsStrExt, |
| 5 | sync::Once, |
| 6 | }; |
| 7 | |
| 8 | use clap::{ |
| 9 | error::{ContextKind, ContextValue}, |
| 10 | Arg, ArgAction, Error, Parser, |
| 11 | }; |
Brian Silverman | e4c79ce | 2022-08-15 05:57:28 -0700 | [diff] [blame] | 12 | |
| 13 | autocxx::include_cpp! ( |
Adam Snaider | 48a62f3 | 2023-10-02 15:49:23 -0700 | [diff] [blame^] | 14 | #include "aos/init_for_rust.h" |
Brian Silverman | e4c79ce | 2022-08-15 05:57:28 -0700 | [diff] [blame] | 15 | |
| 16 | safety!(unsafe) |
| 17 | |
| 18 | generate!("aos::InitFromRust") |
Adam Snaider | 48a62f3 | 2023-10-02 15:49:23 -0700 | [diff] [blame^] | 19 | generate!("aos::GetCppFlags") |
| 20 | generate!("aos::FlagInfo") |
| 21 | generate!("aos::SetCommandLineOption") |
| 22 | generate!("aos::GetCommandLineOption") |
Brian Silverman | e4c79ce | 2022-08-15 05:57:28 -0700 | [diff] [blame] | 23 | ); |
| 24 | |
Adam Snaider | c8b7e75 | 2023-09-14 14:27:53 -0700 | [diff] [blame] | 25 | /// Initializes AOS. |
Adam Snaider | 4351678 | 2023-06-26 15:14:18 -0700 | [diff] [blame] | 26 | pub fn init() { |
Brian Silverman | e4c79ce | 2022-08-15 05:57:28 -0700 | [diff] [blame] | 27 | static ONCE: Once = Once::new(); |
| 28 | ONCE.call_once(|| { |
Adam Snaider | 48a62f3 | 2023-10-02 15:49:23 -0700 | [diff] [blame^] | 29 | 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 Silverman | e4c79ce | 2022-08-15 05:57:28 -0700 | [diff] [blame] | 37 | }); |
Brian Silverman | e4c79ce | 2022-08-15 05:57:28 -0700 | [diff] [blame] | 38 | } |
Adam Snaider | 48a62f3 | 2023-10-02 15:49:23 -0700 | [diff] [blame^] | 39 | |
| 40 | /// Trait used to append C++ gFlags to a clap CLI. |
| 41 | pub 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 | |
| 100 | impl<T: Parser> WithCppFlags for T {} |
| 101 | |
| 102 | #[derive(Clone)] |
| 103 | #[allow(unused)] |
| 104 | struct CxxFlag { |
| 105 | name: String, |
| 106 | ty: String, |
| 107 | description: String, |
| 108 | default_value: String, |
| 109 | filename: String, |
| 110 | } |
| 111 | |
| 112 | struct SetFlagError; |
| 113 | |
| 114 | impl 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 | |
| 136 | impl 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 | |
| 148 | impl 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)] |
| 160 | mod 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 | } |