index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / git / tree.rs
-rw-r--r-- blob 4b8680a152c7b57d907f8730f004f2e9574026f7 4374 bytes (plain)
1
use anyhow::Context;
2
use gix::objs::tree::EntryKind;
3
use serde::Serialize;
4
5
#[derive(Clone)]
6
pub struct TreeEntry {
7
    pub name: String,
8
    pub path: String,
9
    pub kind: EntryKind,
10
    pub size: Option<u64>,
11
    pub mode: u32,
12
    pub id: String,
13
}
14
15
impl TreeEntry {
16
    pub fn size_display(&self) -> String {
17
        match self.size {
18
            Some(bytes) => format_size(bytes),
19
            None => "—".to_string(),
20
        }
21
    }
22
23
    pub fn mode_display(&self) -> String {
24
        format_entry_mode(self.mode, &self.kind)
25
    }
26
}
27
28
#[derive(Clone, Serialize)]
29
pub struct Blob {
30
    pub id: String,
31
    pub mode: u32,
32
    pub size: u64,
33
    pub lines: Option<Vec<String>>,
34
}
35
36
impl Blob {
37
    pub fn mode_display(&self) -> String {
38
        format_entry_mode(self.mode, &EntryKind::Blob)
39
    }
40
}
41
42
pub enum PathView {
43
    Tree(Vec<TreeEntry>),
44
    Blob(Blob),
45
}
46
47
#[derive(Clone, Serialize)]
48
pub struct Breadcrumb {
49
    pub name: String,
50
    pub path: String,
51
}
52
53
pub fn read_entries(base_tree: &gix::Tree<'_>, dir_path: &str) -> anyhow::Result<Vec<TreeEntry>> {
54
    let mut entries = Vec::new();
55
56
    for entry in base_tree.iter() {
57
        let entry = entry.context("failed to read tree entry")?;
58
        let name = entry.filename().to_string();
59
        let path = if dir_path.is_empty() {
60
            name.clone()
61
        } else {
62
            format!("{dir_path}/{name}")
63
        };
64
        let mode = entry.mode();
65
        let kind = mode.kind();
66
67
        let size = if matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
68
            base_tree
69
                .repo
70
                .find_header(entry.oid())
71
                .ok()
72
                .map(|h| h.size())
73
        } else {
74
            None
75
        };
76
77
        entries.push(TreeEntry {
78
            name,
79
            path,
80
            kind,
81
            size,
82
            mode: mode.value() as u32,
83
            id: entry.oid().to_string(),
84
        });
85
    }
86
87
    // Directories first (right under `..`), then alphabetical by name
88
    entries.sort_by(|a, b| {
89
        let a_is_dir = matches!(a.kind, EntryKind::Tree);
90
        let b_is_dir = matches!(b.kind, EntryKind::Tree);
91
        b_is_dir
92
            .cmp(&a_is_dir)
93
            .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
94
            .then_with(|| a.name.cmp(&b.name))
95
    });
96
97
    Ok(entries)
98
}
99
100
pub fn build_breadcrumbs(path: &str) -> Vec<Breadcrumb> {
101
    let mut crumbs = Vec::new();
102
    let mut acc = String::new();
103
104
    for segment in path.split('/').filter(|s| !s.is_empty()) {
105
        if !acc.is_empty() {
106
            acc.push('/');
107
        }
108
        acc.push_str(segment);
109
        crumbs.push(Breadcrumb {
110
            name: segment.to_string(),
111
            path: acc.clone(),
112
        });
113
    }
114
    crumbs
115
}
116
117
pub fn parent_path(path: &str) -> Option<String> {
118
    if path.is_empty() {
119
        return None;
120
    }
121
    match path.rsplit_once('/') {
122
        Some((parent, _)) => Some(parent.to_string()),
123
        None => Some(String::new()),
124
    }
125
}
126
127
pub fn format_entry_mode(mode: u32, kind: &EntryKind) -> String {
128
    match kind {
129
        EntryKind::Tree => "drwxr-xr-x".to_string(),
130
        EntryKind::Link => "lrwxrwxrwx".to_string(),
131
        EntryKind::Commit => "m---------".to_string(),
132
        EntryKind::Blob | EntryKind::BlobExecutable => format_rwx('-', mode),
133
    }
134
}
135
136
pub fn format_mode(mode: u32) -> String {
137
    let file_type = match mode & 0o170000 {
138
        0o040000 => 'd',
139
        0o120000 => 'l',
140
        0o160000 => 'm',
141
        0o100000 => '-',
142
        _ => '?',
143
    };
144
    format_rwx(file_type, mode)
145
}
146
147
fn format_rwx(file_type: char, mode: u32) -> String {
148
    let perms = mode & 0o777;
149
    let mut out = String::with_capacity(10);
150
    out.push(file_type);
151
152
    for shift in [6, 3, 0] {
153
        let bits = (perms >> shift) & 0o7;
154
        out.push(if bits & 0o4 != 0 { 'r' } else { '-' });
155
        out.push(if bits & 0o2 != 0 { 'w' } else { '-' });
156
        out.push(if bits & 0o1 != 0 { 'x' } else { '-' });
157
    }
158
    out
159
}
160
161
fn format_size(bytes: u64) -> String {
162
    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
163
    let mut size = bytes as f64;
164
    let mut unit = 0;
165
    while size >= 1024.0 && unit < UNITS.len() - 1 {
166
        size /= 1024.0;
167
        unit += 1;
168
    }
169
    if unit == 0 {
170
        format!("{bytes} B")
171
    } else {
172
        format!("{size:.1} {}", UNITS[unit])
173
    }
174
}