aboutsummaryrefslogtreecommitdiffstats
path: root/src/prompt.rs
blob: 4a574a43e56eb1b48791ce1336c05354ee28e9cd (plain) (blame)
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
use chrono;
use regex;
use std;
use users;

use std::fmt::Write;
use std::os::linux::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;

use colors;
use power;
use vcs;

pub struct Prompt {
    colors: colors::Colors,
    data: PromptData,
}

pub struct PromptData {
    pub shell: colors::ShellType,
    pub error_code: u8,
    pub hostname: Option<String>,
    pub terminal_cols: Option<usize>,
    pub pwd: Option<std::path::PathBuf>,
    pub home: Option<std::path::PathBuf>,
    pub user: Option<String>,
    pub is_root: bool,
    pub time: chrono::DateTime<chrono::Local>,
    pub power_info: power::PowerInfo,
    pub vcs_info: Option<Box<vcs::VcsInfo>>,
}

impl Prompt {
    pub fn new(data: PromptData) -> Prompt {
        Prompt {
            colors: colors::Colors::new(data.shell.clone()),
            data: data,
        }
    }

    pub fn display(&self) {
        let user = self.data.user
            .clone()
            .unwrap_or_else(|| String::from("???"));
        let host = self.data.hostname
            .clone()
            .unwrap_or_else(|| String::from("???"));

        let max_vcs_len = 20; // "g*+?:mybr...nch:+1-1"
        let vcs = self.format_vcs();
        let vcs = vcs.map(|vcs| {
            compress_vcs(&vcs, max_vcs_len)
        });

        let battery_len = 10;
        let cols = self.data.terminal_cols.unwrap_or(80);

        // " (~/a/...cde|g*+?:mybr:+1-1) -- {--<=======} doy@lance [19:40:50] "
        let max_path_len = cols
            - 1                            // " "
            - vcs
                .as_ref()
                .map(|vcs| vcs.len() + 1)  // "|g*+?:mybr:+1-1"
                .unwrap_or(0) - 2          // "()"
            - 1                            // " "
            - 1                            // "-"
            - 1                            // " "
            - battery_len - 2              // "{<=========}"
            - 1                            // " "
            - user.len() - 1 - host.len()  // "doy@lance"
            - 1                            // " "
            - 10                           // "[19:40:50]"
            - 1;                           // " "

        if max_path_len < 10 {             // "~/a/...cde"
            panic!(
                "terminal too small (need at least {} cols)",
                cols + 10 - max_path_len
            );
        }

        let path = compress_path(
            &self.data.pwd,
            &self.data.home,
            max_path_len
        );

        self.colors.pad(1);
        self.display_path(
            &path,
            &path_color(&self.data.pwd),
            &vcs,
            &self.vcs_color(),
        );

        self.colors.pad(1);
        self.display_border(max_path_len - path.len() + 1);
        self.colors.pad(1);

        self.display_battery(battery_len);
        self.colors.pad(1);

        self.display_identity(&user, &host);
        self.colors.pad(1);

        self.display_time();
        self.colors.pad(1);

        self.colors.newline();

        self.display_error_code();
        self.colors.pad(1);

        self.display_prompt();
        self.colors.pad(1);
    }

    fn display_path(
        &self,
        path: &str,
        path_color: &str,
        vcs: &Option<String>,
        vcs_color: &str
    ) {
        self.colors.print_host(&self.data.hostname, "(");
        self.colors.print(path_color, path);
        if let Some(ref vcs) = *vcs {
            self.colors.print_host(&self.data.hostname, "|");
            self.colors.print(vcs_color, vcs);
        }
        self.colors.print_host(&self.data.hostname, ")");
    }

    fn display_border(&self, len: usize) {
        self.colors.print("default", &"-".repeat(len));
    }

    fn display_battery(&self, len: usize) {
        self.colors.print_host(&self.data.hostname, "{");
        if let Some(battery_usage) = self.data.power_info.battery_usage() {
            let charging = self.data.power_info.charging();
            let color = battery_discharge_color(battery_usage, charging);
            let filled = (battery_usage * (len as f64)).ceil() as usize;
            let unfilled = len - filled;
            if unfilled > 0 {
                self.colors.print(color, &"-".repeat(unfilled));
            }
            if charging {
                self.colors.print("battery_charging", "<");
            }
            else {
                self.colors.print(color, ">");
            }
            if filled > 1 {
                self.colors.print("battery_charging", &"=".repeat(filled - 1));
            }
        }
        else {
            self.colors.print("error", &"?".repeat(len));
        }
        self.colors.print_host(&self.data.hostname, "}");
    }

    fn display_identity(&self, user: &str, host: &str) {
        self.colors.print_user(&self.data.user, user);
        self.colors.print("default", "@");
        self.colors.print_host(&self.data.hostname, host);
    }

    fn display_time(&self) {
        self.colors.print_host(&self.data.hostname, "[");
        self.colors.print(
            "default",
            &format!("{}", self.data.time.format("%H:%M:%S"))
        );
        self.colors.print_host(&self.data.hostname, "]");
    }

    fn display_error_code(&self) {
        let error_code_color = if self.data.error_code == 0 {
            "default"
        }
        else {
            "error"
        };
        self.colors.print(
            error_code_color,
            &format!("{:03}", self.data.error_code)
        );
    }

    fn display_prompt(&self) {
        let prompt = if self.data.is_root { "#" } else { "$" };
        self.colors.print_user(&self.data.user, prompt);
    }

    fn format_vcs(&self) -> Option<String> {
        self.data.vcs_info.as_ref().map(|vcs_info| {
            let mut vcs = String::new();

            write!(vcs, "{}", vcs_id(vcs_info.vcs())).unwrap();

            if vcs_info.has_modified_files() {
                write!(vcs, "*").unwrap();
            }
            if vcs_info.has_staged_files() {
                write!(vcs, "+").unwrap();
            }
            if vcs_info.has_new_files() {
                write!(vcs, "?").unwrap();
            }
            if !vcs_info.has_commits() {
                write!(vcs, "!").unwrap();
            }

            let branch = vcs_info.branch().map(|branch| {
                if branch == "master" {
                    String::new()
                }
                else {
                    branch
                }
            }).unwrap_or_else(|| String::from("???"));
            if branch != "" {
                write!(vcs, ":").unwrap();
            }
            write!(vcs, "{}", branch).unwrap();

            if let Some((local, remote)) = vcs_info.remote_branch_diff() {
                if local > 0 || remote > 0 {
                    write!(vcs, ":").unwrap();
                }
                if local > 0 {
                    write!(vcs, "+{}", local).unwrap();
                }
                if remote > 0 {
                    write!(vcs, "-{}", remote).unwrap();
                }
            }
            else {
                write!(vcs, ":-").unwrap();
            }

            match vcs_info.active_operation() {
                vcs::ActiveOperation::None => {},
                op => {
                    write!(vcs, "({})", active_operation_id(op)).unwrap();
                }
            }

            vcs
        })
    }

    fn vcs_color(&self) -> String {
        self.data.vcs_info.as_ref().map(|vcs_info| {
            if vcs_info.is_error() {
                String::from("vcs_error")
            }
            else if vcs_info.is_dirty() {
                String::from("vcs_dirty")
            }
            else {
                String::from("default")
            }
        }).unwrap_or_else(|| String::from("vcs_error"))
    }
}

fn battery_discharge_color(usage: f64, charging: bool) -> &'static str {
    if usage >= 0.8 {
        "battery_full"
    }
    else if charging {
        "default"
    }
    else if usage >= 0.4 {
        "default"
    }
    else if usage >= 0.15 {
        "battery_warn"
    }
    else if usage >= 0.05 {
        "battery_crit"
    }
    else {
        "battery_emerg"
    }
}

fn path_color<T>(path: &Option<T>) -> String
    where T: AsRef<std::path::Path>
{
    path.as_ref().and_then(|path| {
        std::fs::metadata(path)
            .map(|stat| {
                // XXX there really has to be a better option here
                let euid = users::get_effective_uid();
                let egid = users::get_effective_gid();
                let file_uid = stat.st_uid();
                let file_gid = stat.st_gid();
                let file_mode = stat.permissions().mode();

                if euid == 0 {
                    String::from("default")
                }
                else if (file_uid == euid) && (file_mode & 0o200 != 0) {
                    String::from("default")
                }
                else if (file_gid == egid) && (file_mode & 0o020 != 0) {
                    String::from("default")
                }
                else if file_mode & 0o002 != 0 {
                    String::from("default")
                }
                else {
                    String::from("path_not_writable")
                }
            }).ok()
    }).unwrap_or_else(|| String::from("path_not_exist"))
}

fn compress_path<T, U>(
    path: &Option<T>,
    home: &Option<U>,
    len: usize
) -> String
    where T: AsRef<std::path::Path>,
          U: AsRef<std::path::Path>
{
    if let Some(ref path) = *path {
        let mut path_str = path.as_ref().to_string_lossy().into_owned();

        if let Some(ref home) = *home {
            let home_str = home.as_ref().to_string_lossy().into_owned();
            let home_re = regex::Regex::new(
                &(String::from(r"^") + &regex::escape(&home_str))
            ).unwrap();

            path_str = home_re.replace(&path_str, "~").into_owned();
        }

        let path_compress_re = regex::Regex::new(
            r"/([^/])[^/]+/"
        ).unwrap();

        while path_str.len() > len {
            let prev_len = path_str.len();
            path_str = path_compress_re.replace(&path_str, "/$1/").into_owned();
            if prev_len == path_str.len() {
                break;
            }
        }

        if path_str.len() > len {
            path_str = String::from(&path_str[..len - 6])
                + "..."
                + &path_str[len - 3..len]
        }

        path_str
    }
    else {
        String::from("???")
    }
}

fn compress_vcs(vcs: &str, len: usize) -> String {
    if vcs.len() > len {
        let vcs_parts_re = regex::Regex::new(
            r"^([^:]+):.*:([^:])$"
        ).unwrap();
        vcs_parts_re
            .captures(vcs)
            .map(|cap| {
                let prefix_len = cap.get(1)
                    .map(|mat| mat.end() - mat.start())
                    .unwrap_or(0);
                let suffix_len = cap.get(2)
                    .map(|mat| mat.end() - mat.start())
                    .unwrap_or(0);
                let branch_len = len - prefix_len - suffix_len - 2;
                let branch_re = regex::Regex::new(
                    &format!(
                        r"(:[^:]{{{}}})[^:]*([^:]{{3}}:)",
                        (branch_len - 6).to_string()
                    )
                ).unwrap();
                branch_re.replace(vcs, "$1...$2").into_owned()
            })
            .unwrap_or_else(|| vcs.to_string())
    }
    else {
        vcs.to_string()
    }
}

fn vcs_id(vcs: vcs::VcsType) -> String {
    match vcs {
        vcs::VcsType::Git => String::from("g"),
    }
}

fn active_operation_id(op: vcs::ActiveOperation) -> String {
    match op {
        vcs::ActiveOperation::None => String::new(),
        vcs::ActiveOperation::Merge => String::from("m"),
        vcs::ActiveOperation::Revert => String::from("v"),
        vcs::ActiveOperation::CherryPick => String::from("c"),
        vcs::ActiveOperation::Bisect => String::from("b"),
        vcs::ActiveOperation::Rebase => String::from("r"),
    }
}