Skip to main content

git_su/
switcher.rs

1// Switcher: request switch, print current, list, add, clear, edit
2
3use crate::config_repository::ConfigRepository;
4use crate::git::{Git, Scope};
5use crate::user::User;
6use crate::user_list::UserList;
7use std::path::Path;
8
9pub struct Switcher<'a> {
10    user_list: &'a UserList,
11}
12
13impl<'a> Switcher<'a> {
14    pub fn new(user_list: &'a UserList) -> Self {
15        Switcher { user_list }
16    }
17
18    pub fn request(&self, scope: Scope, user_strings: &[String], output: &mut impl std::io::Write) {
19        let (parsed, not_parsed): (Vec<User>, Vec<String>) = user_strings
20            .iter()
21            .map(|s| {
22                User::parse(s)
23                    .map(|u| (Some(u), None))
24                    .unwrap_or_else(|_| (None, Some(s.clone())))
25            })
26            .fold(
27                (vec![], vec![]),
28                |(mut parsed, mut not_parsed), (p, n)| {
29                    if let Some(u) = p {
30                        parsed.push(u);
31                    }
32                    if let Some(s) = n {
33                        not_parsed.push(s);
34                    }
35                    (parsed, not_parsed)
36                },
37            );
38
39        let found = match self.user_list.find(&not_parsed) {
40            Ok(users) => users,
41            Err(e) => {
42                let _ = writeln!(output, "{}", crate::color::error(&e.to_string()));
43                return;
44            }
45        };
46
47        let group_email = ConfigRepository::group_email_address();
48        let all_users: Vec<User> = parsed
49            .iter()
50            .chain(found.iter())
51            .cloned()
52            .collect();
53        let combined = all_users
54            .iter()
55            .fold(User::none(), |acc, u| acc.combine(u, &group_email));
56
57        let actual_scope = if scope == Scope::Default || scope == Scope::Derived {
58            ConfigRepository::default_select_scope()
59        } else {
60            scope
61        };
62
63        if Git::select_user(&combined, actual_scope) {
64            let _ = writeln!(
65                output,
66                "{}",
67                crate::color::success(&format!(
68                    "Switched {} user to {}",
69                    actual_scope.display_name(),
70                    Git::render(&combined)
71                ))
72            );
73        }
74
75        for u in &parsed {
76            if !u.is_none() && !self.user_list.list().iter().any(|l| l == u) {
77                self.user_list.add(u);
78            }
79        }
80    }
81
82    pub fn print_current(&self, scopes: &[Scope], output: &mut impl std::io::Write) {
83        const LABEL_WIDTH: usize = 6; // Local, Global, System
84        let show_all = scopes.is_empty();
85        if show_all {
86            let _ = writeln!(
87                output,
88                "{} {}",
89                crate::color::label("Current user:"),
90                Git::render(&Git::selected_user(Scope::Derived))
91            );
92            let _ = writeln!(output);
93            for (scope_label, scope) in [
94                ("Local", Scope::Local),
95                ("Global", Scope::Global),
96                ("System", Scope::System),
97            ] {
98                let padded = format!("{:>1$}", scope_label, LABEL_WIDTH);
99                let _ = writeln!(
100                    output,
101                    "{}: {}",
102                    crate::color::label(&padded),
103                    Git::render(&Git::selected_user(scope))
104                );
105            }
106        } else {
107            for scope in scopes {
108                let label = scope.display_name();
109                let w = label.len().max(LABEL_WIDTH);
110                let u = Git::selected_user(*scope);
111                if !u.is_none() {
112                    let padded = format!("{:<1$}", label, w);
113                    let _ = writeln!(
114                        output,
115                        "{}: {}",
116                        crate::color::label(&padded),
117                        Git::render(&u)
118                    );
119                }
120            }
121        }
122    }
123
124    pub fn clear(&self, scopes: &[Scope], output: &mut impl std::io::Write) {
125        let scopes: Vec<Scope> = if scopes.is_empty() {
126            vec![Scope::Local, Scope::Global, Scope::System]
127        } else {
128            scopes.to_vec()
129        };
130        let scope_names: Vec<&str> = scopes.iter().map(|s| s.as_flag()).collect();
131        let _ = writeln!(
132            output,
133            "{}",
134            crate::color::dim(&format!(
135                "Clearing Git user in {} scope(s)",
136                scope_names.join(", ")
137            ))
138        );
139        for scope in scopes {
140            Git::clear_user(scope);
141        }
142    }
143
144    pub fn list(&self, output: &mut impl std::io::Write) {
145        for u in self.user_list.list() {
146            let _ = writeln!(output, "{}", Git::render(&u));
147        }
148    }
149
150    pub fn add(&self, user_string: &str, output: &mut impl std::io::Write) {
151        let user = match User::parse(user_string) {
152            Ok(u) => u,
153            Err(e) => {
154                let _ = writeln!(output, "{}", crate::color::error(&e.to_string()));
155                return;
156            }
157        };
158        if self.user_list.list().iter().any(|u| u == &user) {
159            let _ = writeln!(
160                output,
161                "{}",
162                crate::color::dim(&format!(
163                    "User '{}' already in user list (try switching to them with 'git su {}')",
164                    user,
165                    user.initials()
166                ))
167            );
168        } else {
169            self.user_list.add(&user);
170            let _ = writeln!(
171                output,
172                "{}",
173                crate::color::success(&format!("User '{}' added to users", user))
174            );
175        }
176    }
177
178    pub fn edit_config(&self, path: &Path) -> bool {
179        Git::edit_gitsu_config(path)
180    }
181}