1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
macro_rules! _print {
    (@$color:ident, $ptr:ident, $($args:tt)+) => {{
        use ::std::io::Write;

        let mut ptr = $crate::printer::$ptr();
        ptr.set_color($crate::printer::Color::$color);
        let _ = ::std::write!(ptr, $($args)+);
        ptr.reset();
    }};
    ($ptr:ident, $($args:tt)+) => {{
        use ::std::io::Write;

        let _ = ::std::write!($crate::printer::$ptr(), $($args)+);
    }};
}

// Print is akin to info! level messages
macro_rules! cli_print {
    (@$color:ident, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Info {
            _print!(@$color, printer, $($args)+);
        }
    }};
    ($($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Info {
            _print!(printer, $($args)+);
        }
    }};
}

// Akin to info! level messages
macro_rules! cli_println {
    (@$color:ident, $($args:tt)+) => {{
        cli_print!(@$color, $($args)+);
        cli_print!("\n");
    }};
    // TODO: change to zero or more (*)
    ($($args:tt)+) => {{
        cli_print!($($args)+);
        cli_print!("\n");
    }}
}

// akin to error! level messages
macro_rules! cli_eprint {
    (@$color:ident, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Error {
            _print!(@$color, eprinter, $($args)+);
        }
    }};
    ($($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Error {
            _print!(eprinter, $($args)+);
        }
    }}
}

// Akin to error! level messages
macro_rules! cli_eprintln {
    (@$color:ident, $($args:tt)+) => {{
        cli_eprint!(@$color, $($args)+);
        cli_eprint!("\n");
    }};
    ($($args:tt)*) => {{
        cli_eprint!($($args)+);
        cli_eprint!("\n");
    }}
}

/// Writes an error message to stderr and exits the process
#[allow(unused_macros)]
macro_rules! cli_bail {
    (@impl $prefix:expr, $status:expr, $($args:tt)*) => {{
        cli_eprint!(@Red, $prefix);
        cli_eprintln!($($args)+);
        ::std::process::exit($status);
    }};
    (@prefix $prefix:expr, @status $status:expr, $($args:tt)+) => {{
        cli_bail!(@impl $prefix, $status, $($args)+);
    }};
    (@status $status:expr, $($args:tt)+) => {{
        cli_bail!(@impl "error: ", $status, $($args)+);
    }};
    (@prefix $prefix:expr, $($args:tt)+) => {{
        cli_bail!(@impl $prefix, 1, $($args)+);
    }};
    ($($args:tt)*) => {{
        cli_bail!(@impl "error: ", 1, $($args)+);
    }};
}

// Akin to warn! level messages.
//
// The *ln variants it's more common to want a oneshot message with a
// "warn: " prefix, so that's the default. You opt out of the prefix with `@noprefix`. The non-line
// versions are the opposite, because it's more common to *not* want a prefix i.e. you're writing
// multiple portions of the same line.
macro_rules! cli_warn {
    (@prefix, @$color:ident, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Warn {
            _print!(@Yellow, printer, "warn: ");
            _print!(@$color, printer, $($args)+);
        }
    }};
    (@prefix, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Warn {
            _print!(printer, "warn: ");
            _print!(printer, $($args)+);
        }
    }};
    (@$color:ident, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Warn {
            _print!(@$color, printer, $($args)+);
        }
    }};
    ($($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Warn {
            _print!(printer, $($args)+);
        }
    }};
}

// Akin to warn! level messages.
//
// The *ln variants it's more common to want a oneshot message with a
// "warn: " prefix, so that's the default. You opt out of the prefix with `@noprefix`. The non-line
// versions are the opposite, because it's more common to *not* want a prefix i.e. you're writing
// multiple portions of the same line.
macro_rules! cli_warnln {
    (@noprefix, @$color:ident, $($args:tt)+) => {{
        cli_warn!(@$color, $($args)+);
        cli_warn!("\n");
    }};
    // TODO: change to zero or more (*)
    (@noprefix, $($args:tt)+) => {{
        cli_warn!($($args)+);
        cli_warn!("\n");
    }};
    (@$color:ident, $($args:tt)+) => {{
        cli_warn!(@prefix, @$color, $($args)+);
        cli_warn!("\n");
    }};
    // TODO: change to zero or more (*)
    ($($args:tt)+) => {{
        cli_warn!(@prefix, $($args)+);
        cli_warn!("\n");
    }}
}

// Akin to debug! level messages
//
// The *ln variants it's more common to want a oneshot message with a
// "warn: " prefix, so that's the default. You opt out of the prefix with `@noprefix`. The non-line
// versions are the opposite, because it's more common to *not* want a prefix i.e. you're writing
// multiple portions of the same line.
macro_rules! cli_debug {
    (@prefix, @$color:ident, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Debug {
            _print!(@$color, eprinter, "DEBUG: ");
            _print!(@$color, eprinter, $($args)+);
        }
    }};
    (@prefix, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Debug {
            _print!(eprinter, "DEBUG: ");
            _print!(eprinter, $($args)+);
        }
    }};
    (@$color:ident, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Debug {
            _print!(@$color, eprinter, $($args)+);
        }
    }};
    ($($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Debug {
            _print!(eprinter, $($args)+);
        }
    }};
}

// Akin to the debug! level messages.
//
// The *ln variants it's more common to want a oneshot message with a
// "DEBUG: " prefix, so that's the default. You opt out of the prefix with `@noprefix`. The non-line
// versions are the opposite, because it's more common to *not* want a prefix i.e. you're writing
// multiple portions of the same line.
macro_rules! cli_debugln {
    (@prefix, @$color:ident, $($args:tt)+) => {{
        cli_debug!(@prefix, @$color, $($args)+);
        cli_debug!("\n");
    }};
    // TODO: change to zero or more (*)
    (@prefix, $($args:tt)+) => {{
        cli_debug!(@prefix, $($args)+);
        cli_debug!("\n");
    }};
    (@$color:ident, $($args:tt)+) => {{
        cli_debug!(@$color, $($args)+);
        cli_debug!("\n");
    }};
    // TODO: change to zero or more (*)
    ($($args:tt)+) => {{
        cli_debug!($($args)+);
        cli_debug!("\n");
    }}
}

// Akin to trace! level messages
//
// The *ln variants it's more common to want a oneshot message with a
// "warn: " prefix, so that's the default. You opt out of the prefix with `@noprefix`. The non-line
// versions are the opposite, because it's more common to *not* want a prefix i.e. you're writing
// multiple portions of the same line.
macro_rules! cli_trace {
    (@prefix, @$color:ident, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Trace {
            _print!(@$color, eprinter, "TRACE: ");
            _print!(@$color, eprinter, $($args)+);
        }
    }};
    (@prefix, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Trace {
            _print!(eprinter, "TRACE: ");
            _print!(eprinter, $($args)+);
        }
    }};
    (@$color:ident, $($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Trace {
            _print!(@$color, eprinter, $($args)+);
        }
    }};
    ($($args:tt)+) => {{
        if $crate::log::log_level() <= &$crate::log::LogLevel::Trace {
            _print!(eprinter, $($args)+);
        }
    }};
}

// Akin to the trace! level messages.
//
// The *ln variants it's more common to want a oneshot message with a
// "DEBUG: " prefix, so that's the default. You opt out of the prefix with `@noprefix`. The non-line
// versions are the opposite, because it's more common to *not* want a prefix i.e. you're writing
// multiple portions of the same line.
macro_rules! cli_traceln {
    (@prefix, @$color:ident, $($args:tt)+) => {{
        cli_trace!(@prefix, @$color, $($args)+);
        cli_trace!("\n");
    }};
    // TODO: change to zero or more (*)
    (@prefix, $($args:tt)+) => {{
        cli_trace!(@prefix, $($args)+);
        cli_trace!("\n");
    }};
    (@$color:ident, $($args:tt)+) => {{
        cli_trace!(@$color, $($args)+);
        cli_trace!("\n");
    }};
    // TODO: change to zero or more (*)
    ($($args:tt)+) => {{
        cli_trace!($($args)+);
        cli_trace!("\n");
    }}
}

// Helper macros to make some CLI aspects a little less verbose

/// Makes declaring *consistent* arguments less verbose and less tedious.
///
/// The available syntax is:
///
/// - `--STRING` or `--("STRING-WITH-HYPHENS")` will make an `Arg` where *both* the name and long
/// are the same. Due to Rust syntax, if the argument should have hyphens, one must use
/// `--("foo-bar-baz")`
/// - `-('f')` sets the Short value. (Due to Rust syntax rules)
/// - Visible aliases can be set with using `|` along with the similar Long value rules. I.e. `|foo`
///   or
/// `|("foo-with-hyphens"). When combined the Long/name it actually looks good `--foo|bar`, etc.
/// - A value name can be set with `=["STRING"]` optionally also setting a default value
///   `=["STRING"=>"default"]`
/// - Setting multiple values can be done with `...` Note that this sets multiple
/// values/occurrences in a consistent manner for this application. If you need arguments with
/// different semantics you'll have to set those manually. `...` is equivalent to setting
/// `Arg::new("foo").action(ArgAction::Append).multiple_values(true).number_of_values(1).
/// value_delimiter(',')`
/// - Setting any boolean value to `true` can be done by just the function name i.e. `required`
/// - Setting any boolean value to `false` can be done by prefixing the function with `!` i.e.
/// `!required`
///
/// ```rust
/// # use clap::{ArgAction, Arg};
/// # use seaplane_cli::arg;
/// # let _ =
/// arg!(--foo|foos =["NUM"=>"2"]... global !allow_hyphen_values);
///
/// // is equivalent to (with the macro syntax in the comment to the right)...
/// # let _ =
/// Arg::new("foo")                // --foo
///   .long("foo")                 // --foo
///   .visible_alias("foos")       // |foos
///   .value_name("NUM")           // =["NUM"]
///   .default_value("2")          // =[..=>"2"]
///   .action(ArgAction::Append)   // ...
///   .multiple_values(true)       // ...
///   .value_delimiter(',')        // ...
///   .number_of_values(1)         // ...
///   .global(true)                // global
///   .allow_hyphen_values(false); // !allow_hyphen_values
/// ```
#[macro_export]
macro_rules! arg {
    (@arg ($arg:expr) ) => { $arg };
    (@arg ($arg:expr) --$long:ident $($tail:tt)*) => {
        arg!(@arg ($arg.long(stringify!($long))) $($tail)* )
    };
    (@arg ($arg:expr) -($short:expr) $($tail:tt)*) => {
        arg!(@arg ($arg.short($short)) $($tail)* )
    };
    (@arg ($arg:expr) | ($alias:expr) $($tail:tt)*) => {
        arg!(@arg ($arg.visible_alias($alias)) $($tail)* )
    };
    (@arg ($arg:expr) | $alias:ident $($tail:tt)*) => {
        arg!(@arg ($arg.visible_alias(stringify!($alias))) $($tail)* )
    };
    (@arg ($arg:expr) ... $($tail:tt)*) => {
        arg!(@arg ({
            let arg = $arg.value_delimiter(',').action(::clap::ArgAction::Append);
            if arg.get_long().is_some() || arg.get_short().is_some() {
                arg.number_of_values(1)
            } else {
                arg
            }
        }) multiple_values $($tail)* )
    };
    (@arg ($arg:expr) =[$var:expr$(=>$default:expr)?] $($tail:tt)*) => {
        arg!(@arg ({
            #[allow(unused_mut)]
            let mut a = $arg.value_name($var);
            $(
                a = a.default_value($default);
            )?
            a
            }) $($tail)*)
    };
    // !foo -> .foo(false)
    (@arg ($arg:expr) !$ident:ident $($tail:tt)*) => {
        arg!(@arg ($arg.$ident(false)) $($tail)*)
    };
    // +foo -> .foo(true)
    (@arg ($arg:expr) $ident:ident $($tail:tt)*) => {
        arg!(@arg ($arg.$ident(true)) $($tail)*)
    };
    ($name:ident $($tail:tt)*) => {
        arg!(@arg (::clap::Arg::new(stringify!($name))) $($tail)* )
    };
    (--($name:expr) $($tail:tt)*) => {
        arg!(@arg (::clap::Arg::new($name).long($name)) $($tail)* )
    };
    (--$name:ident $($tail:tt)*) => {
        arg!(@arg (::clap::Arg::new(stringify!($name)).long(stringify!($name))) $($tail)* )
    };
}

/// Shorthand for checking if an argument in the CLI commands was base64 or not, and doing
/// the conversion if necessary
macro_rules! maybe_base64_arg {
    ($m:expr, $arg:expr, $is_base64:expr) => {
        if let Some(raw_key) = $m.get_one::<String>($arg) {
            if $is_base64 {
                let _ = ::base64::decode_config(raw_key, ::base64::URL_SAFE_NO_PAD)?;
                Some(raw_key.to_string())
            } else {
                Some(::base64::encode_config(raw_key, ::base64::URL_SAFE_NO_PAD))
            }
        } else {
            None
        }
    };
}

/// Remove items from a Vec matching some predicate, returning the removed items as a new Vec
macro_rules! vec_remove_if {
    ($v:expr, $f:expr) => {{
        let idx: Vec<_> = $v
            .iter()
            .enumerate()
            .rev()
            .filter_map(|(i, item)| if $f(item) { Some(i) } else { None })
            .collect();
        let mut ret = Vec::new();
        for i in idx {
            ret.push($v.swap_remove(i));
        }
        ret
    }};
}

/// Performs the wrapped method request against the SDK API. If the response is that the access
/// token is expired, it will refresh the access token and try again. All other errors are mapped
/// to the CliError type.
macro_rules! maybe_retry {
    ($this:ident . $fn:ident ( $($arg:expr),* ) ) => {{
        if $this.inner.is_none() {
            $this.refresh_inner()?;
        }
        let req = &mut $this.inner.as_mut().unwrap();

        let res = match req.$fn($( $arg ),*) {
            Ok(ret) => Ok(ret),
            Err(SeaplaneError::ApiResponse(ae))
                if ae.kind == ApiErrorKind::Unauthorized =>
            {
                $this.token = Some(request_token(
                        &$this.api_key,
                        $this.identity_url.as_ref(),
                        $this.insecure_urls,
                        $this.invalid_certs)?);
                Ok(req.$fn($( $arg ,)*)?)
            }
            Err(e) => Err(e),
        };
        res.map_err(CliError::from)
    }};
}

/// Same as maybe_retry but will clone the function arguments
macro_rules! maybe_retry_cloned {
    ($this:ident . $fn:ident ( $($arg:expr),* ) ) => {{
        maybe_retry!($this.$fn($( $arg.clone() ),*))
    }};
}