aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 0b1ec1bf24902df9aadd8a7e9912c8a3768e1d7c (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
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
use std::{env, fmt, path::Path};

use git2::{Oid, Repository, Status};
use tico::tico;

fn main() {
    let args = env::args().collect::<Vec<_>>();
    match args
        .iter()
        .map(String::as_str)
        .collect::<Vec<&str>>()
        .as_slice()
    {
        [_, "cwd", target] => print!("{}", cwd(target)),
        [_, "vcs", target] => {
            if let Some(status) = vcs(target) {
                print!("{}", status)
            }
        }
        _ => (),
    }
}

fn cwd(target: &str) -> String {
    let home = env::var("HOME").unwrap();

    let home_dir_ext = format!("{}{}", home, "/");
    if target == home.as_str() || target.starts_with(&home_dir_ext) {
        let replaced = target.replacen(home.as_str(), "~", 1);
        tico(&replaced)
    } else {
        tico(&target)
    }
}

struct VcsStatus {
    branch: Branch,
    dist: Dist,
    status: StatusSummary,
}

impl fmt::Display for VcsStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}{}{}#[fg=colour7]",
            self.branch, self.dist, self.status
        )
    }
}

enum Branch {
    Id(Oid),
    Ref(String),
    Unknown,
}

impl fmt::Display for Branch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Branch::Id(id) => write!(f, "#[fg=colour3]{:.7} ", id),
            Branch::Ref(s) => write!(f, "#[fg=colour8]{} ", s),
            Branch::Unknown => write!(f, ""),
        }
    }
}

enum Dist {
    Ahead,
    Behind,
    Both,
    Neither,
}

impl fmt::Display for Dist {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "#[fg=colour8]{}",
            match self {
                Self::Ahead => "↑ ",
                Self::Behind => "↓ ",
                Self::Both => "↑↓ ",
                Self::Neither => "",
            }
        )
    }
}

enum StatusSummary {
    WtModified,
    IdxModified,
    Conflict,
    Clean,
}

impl fmt::Display for StatusSummary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::WtModified => "#[fg=colour1]×",
                Self::IdxModified => "#[fg=colour3]±",
                Self::Conflict => "#[fg=colour5]!",
                Self::Clean => "#[fg=colour2]·",
            }
        )
    }
}

fn vcs(target: &str) -> Option<VcsStatus> {
    let repo = match Path::new(target)
        .ancestors()
        .map(Repository::open)
        .find_map(|r| r.ok())
    {
        Some(r) => r,
        None => return None,
    };

    let dist = match get_ahead_behind(&repo) {
        Some((ahead, behind)) if ahead > 0 && behind > 0 => Dist::Both,
        Some((ahead, _)) if ahead > 0 => Dist::Ahead,
        Some((_, behind)) if behind > 0 => Dist::Behind,
        _ => Dist::Neither,
    };

    let branch = match repo.head() {
        Ok(reference) if reference.is_branch() => {
            Branch::Ref(reference.shorthand().unwrap().to_string())
        }
        Ok(reference) => Branch::Id(reference.peel_to_commit().unwrap().id()),
        _ => Branch::Unknown,
    };

    let status = repo_status(&repo);

    Some(VcsStatus {
        branch,
        dist,
        status,
    })
}

fn repo_status(repo: &Repository) -> StatusSummary {
    for file in repo.statuses(None).unwrap().iter() {
        match file.status() {
            // STATE: conflicted
            Status::CONFLICTED => return StatusSummary::Conflict,
            // STATE: unstaged (working tree modified)
            Status::WT_NEW
            | Status::WT_MODIFIED
            | Status::WT_DELETED
            | Status::WT_TYPECHANGE
            | Status::WT_RENAMED => return StatusSummary::WtModified,
            // STATE: staged (changes added to index)
            Status::INDEX_NEW
            | Status::INDEX_MODIFIED
            | Status::INDEX_DELETED
            | Status::INDEX_TYPECHANGE
            | Status::INDEX_RENAMED => return StatusSummary::IdxModified,
            // STATE: committed (changes have been saved in the repo)
            _ => return StatusSummary::Clean,
        }
    }
    StatusSummary::Clean
}

fn get_ahead_behind(r: &Repository) -> Option<(usize, usize)> {
    let head = (r.head().ok())?;
    if !head.is_branch() {
        return None;
    }

    let head_name = head.shorthand()?;
    let head_branch = r.find_branch(head_name, git2::BranchType::Local).ok()?;
    let upstream = head_branch.upstream().ok()?;
    let head_oid = head.target()?;
    let upstream_oid = upstream.get().target()?;

    r.graph_ahead_behind(head_oid, upstream_oid).ok()
}