1use clap::{ArgAction, ArgGroup, Args};
24use log::debug;
25use std::cell::RefCell;
26use std::os::fd::RawFd;
27use std::path::PathBuf;
28
29use crate::say::Say;
30
31thread_local! {
32 pub static GLOBALS: RefCell<GlobalValues> = RefCell::new(Default::default());
33}
34
35#[derive(Default)]
36pub struct GlobalValues {
37 pub verbose: u8,
38 pub say: Say,
39 pub password_source: PasswordSource,
40}
41
42impl GlobalValues {
43 fn init_password_source(&mut self, args: &GlobalArgs) {
44 if let Some(fd) = args.password_from_fd {
45 debug!("read password from fd {fd}");
46 self.password_source = PasswordSource::Fd(fd);
47 } else if let Some(path) = args.password_from_file.as_ref() {
48 debug!("read password from path {}", path.display());
49 self.password_source = PasswordSource::Path(path.clone());
50 } else {
51 debug!("read password from console");
52 self.password_source = PasswordSource::Console;
53 }
54 }
55}
56
57pub enum PasswordSource {
58 Fd(RawFd),
59 Path(PathBuf),
60 Console,
61}
62
63impl PasswordSource {
64 pub fn new(fd: Option<RawFd>, path: Option<PathBuf>) -> PasswordSource {
65 if let Some(fd) = fd {
66 Self::Fd(fd)
67 } else if let Some(path) = path {
68 Self::Path(path)
69 } else {
70 Self::Console
71 }
72 }
73}
74
75impl Default for PasswordSource {
76 fn default() -> Self {
77 Self::Console
78 }
79}
80
81#[derive(Args, Clone, Debug)]
82#[clap(group(ArgGroup::new("password").required(false).multiple(false)))]
83pub struct GlobalArgs {
84 #[clap(short, long, action = ArgAction::Count, global = true)]
86 pub verbose: u8,
87
88 #[clap(short, long, action = ArgAction::SetTrue, global = true)]
90 pub quiet: bool,
91
92 #[clap(long, group = "password", global = true, value_name = "FD")]
95 pub password_from_fd: Option<RawFd>,
96
97 #[clap(long, group = "password", global = true, value_name = "PATH")]
100 pub password_from_file: Option<PathBuf>,
101}
102
103impl GlobalArgs {
104 pub fn init(&self) {
105 GLOBALS.with_borrow_mut(|g| {
106 g.verbose = self.verbose;
107 g.say.set_quiet(self.quiet);
108 g.init_password_source(self);
109 });
110 }
111}