summaryrefslogtreecommitdiffstats
path: root/src/modules/directory.rs
blob: 9b5b8195911f1776cbc1678306cfce50d8e59636 (plain)
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
use super::Segment;
use ansi_term::{Color, Style};
use clap::ArgMatches;
use dirs;
use git2::Repository;
use std::env;
use std::path::PathBuf;

/// Creates a segment with the current directory
pub fn segment(_: &ArgMatches) -> Segment {
    const COLOR_DIR: Color = Color::Cyan;
    const DIR_TRUNCATION_LENGTH: usize = 3;
    const HOME_SYMBOL: &str = "~";

    let current_path = env::current_dir()
        .expect("Unable to identify current directory")
        .canonicalize()
        .expect("Unable to canonicalize current directory");

    let dir_string;
    if let Ok(repo) = git2::Repository::discover(&current_path) {
        let repo_root = get_repo_root(repo);

        // The folder name is the last component to the repo path
        let repo_folder_name = repo_root
            .components()
            .last()
            .unwrap()
            .as_os_str()
            .to_str()
            .unwrap();

        dir_string = truncate_path(
            &DIR_TRUNCATION_LENGTH,
            &current_path,
            &repo_root,
            &repo_folder_name,
        );
    } else {
        let home_dir = dirs::home_dir().unwrap();

        dir_string = truncate_path(
            &DIR_TRUNCATION_LENGTH,
            &current_path,
            &home_dir,
            HOME_SYMBOL,
        );
    }

    Segment {
        value: dir_string,
        style: Style::from(COLOR_DIR).bold(),
        ..Default::default()
    }
}

/// Get the root directory of a git repo
fn get_repo_root(repo: Repository) -> PathBuf {
    if repo.is_bare() {
        // Bare repos will return the repo root
        repo.path().to_path_buf()
    } else {
        // Non-bare repos will return the path of `.git`
        repo.path().parent().unwrap().to_path_buf()
    }
}

/// Truncate a path to a predefined number of path components
/// 
/// Trim the path in the prompt to only have the last few paths, set by `length`.
/// This function also serves to replace the top-level path of the prompt.
/// This can be used to replace the path to a git repo with only the repo
/// directory name.
fn truncate_path(
    length: &usize,
    full_path: &PathBuf,
    top_level_path: &PathBuf,
    top_level_replacement: &str,
) -> String {
    if full_path == top_level_path {
        return top_level_replacement.to_string();
    }

    let full_path_depth = full_path.components().count();
    let top_level_path_depth = top_level_path.components().count();

    // Don't bother with replacing top level path if length is long enough
    if full_path_depth - top_level_path_depth >= *length {
        return full_path
            .iter()
            .skip(full_path_depth - length)
            .collect::<PathBuf>()
            .to_str()
            .unwrap()
            .to_string();
    }

    format!(
        "{replacement}{separator}{path}",
        replacement = top_level_replacement,
        separator = std::path::MAIN_SEPARATOR,
        path = full_path
            .iter()
            .skip(top_level_path_depth)
            .collect::<PathBuf>()
            .to_str()
            .unwrap()
    )
}

#[cfg(test)]
mod tests {
    // TODO: Look into stubbing `env` so that tests can be run in parallel
    use super::*;
    use clap::{App, Arg};
    use std::path::Path;

    #[test]
    fn truncate_home_dir() {
        let args = App::new("starship")
            .arg(Arg::with_name("status_code"))
            .get_matches_from(vec!["starship", "0"]);

        let home_dir = dirs::home_dir().unwrap();
        env::set_current_dir(&home_dir).unwrap();

        let segment = segment(&args);
        assert_eq!(segment.value, "~");
    }

    #[test]
    fn dont_truncate_non_home_dir() {
        let args = App::new("starship")
            .arg(Arg::with_name("status_code"))
            .get_matches_from(vec!["starship", "0"]);

        let root_dir = Path::new("/");
        env::set_current_dir(&root_dir).unwrap();

        let segment = segment(&args);
        assert_eq!(segment.value, "/");
    }
}