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 60de1e294a3233fbc50fba836874b20d5c86235e 4710 bytes (plain)
1
use crate::prelude::*;
2
use anyhow::Context;
3
use gix::objs::tree::EntryKind;
4
use serde::Serialize;
5
6
#[derive(Clone)]
7
pub struct TreeEntry {
8
    pub name: String,
9
    pub path: String, // full path from repo root, for building links
10
    pub kind: EntryKind,
11
    pub size: Option<u64>, // only set for files
12
    pub mode: u32,
13
    pub id: String,
14
}
15
16
impl TreeEntry {
17
    pub fn size_display(&self) -> String {
18
        match self.size {
19
            Some(bytes) => format_size(bytes),
20
            None => "—".to_string(),
21
        }
22
    }
23
24
    pub fn mode_display(&self) -> String {
25
        format_mode(self.mode, &self.kind)
26
    }
27
}
28
29
impl<'repo> Commit<'repo> {
30
    pub fn tree(&self, dir_path: &str) -> anyhow::Result<Vec<TreeEntry>> {
31
        let mut entries: Vec<TreeEntry> = Vec::new();
32
33
        let base_tree = if dir_path.is_empty() {
34
            self.gix.tree().context("failed to get root tree")?
35
        } else {
36
            self.gix
37
                .tree()
38
                .context("failed to get root tree")?
39
                .lookup_entry_by_path(dir_path)
40
                .with_context(|| format!("failed lookup for path: {dir_path}"))?
41
                .with_context(|| format!("path not found: {dir_path}"))?
42
                .object()
43
                .context("failed to load object")?
44
                .try_into_tree()
45
                .context("path did not resolve to a tree")?
46
        };
47
48
        for entry in base_tree.iter() {
49
            let entry = entry.context("failed to read tree entry")?;
50
            let name = entry.filename().to_string();
51
            let full_path = if dir_path.is_empty() {
52
                name.clone()
53
            } else {
54
                format!("{dir_path}/{name}")
55
            };
56
            let id = entry.oid().to_string();
57
            let mode = entry.mode();
58
            let kind = mode.kind();
59
60
            let size = if matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
61
                self.gix
62
                    .repo
63
                    .find_header(entry.oid())
64
                    .ok()
65
                    .map(|h| h.size())
66
            } else {
67
                None
68
            };
69
70
            entries.push(TreeEntry {
71
                name,
72
                path: full_path,
73
                kind,
74
                size,
75
                mode: mode.value() as u32,
76
                id,
77
            });
78
        }
79
80
        Ok(entries)
81
    }
82
}
83
84
#[derive(Clone, Serialize)]
85
pub struct Blob {
86
    pub id: String,
87
    pub mode: u32,
88
    pub size: u64,
89
    pub lines: Option<Vec<String>>, // None => binary, can't show as text
90
}
91
92
impl Blob {
93
    pub fn mode_display(&self) -> String {
94
        format_mode(self.mode, &EntryKind::Blob)
95
    }
96
}
97
98
pub enum PathView {
99
    Tree(Vec<TreeEntry>),
100
    Blob(Blob),
101
}
102
103
#[derive(Clone, Serialize)]
104
pub struct Breadcrumb {
105
    pub name: String,
106
    pub path: String, // cumulative path up to and including this segment
107
}
108
109
pub fn build_breadcrumbs(path: &str) -> Vec<Breadcrumb> {
110
    let mut crumbs = Vec::new();
111
    let mut acc = String::new();
112
113
    for segment in path.split('/').filter(|s| !s.is_empty()) {
114
        if !acc.is_empty() {
115
            acc.push('/');
116
        }
117
        acc.push_str(segment);
118
        crumbs.push(Breadcrumb {
119
            name: segment.to_string(),
120
            path: acc.clone(),
121
        });
122
    }
123
    crumbs
124
}
125
126
pub fn parent_path(path: &str) -> Option<String> {
127
    if path.is_empty() {
128
        return None;
129
    }
130
    match path.rsplit_once('/') {
131
        Some((parent, _)) => Some(parent.to_string()),
132
        None => Some(String::new()), // one level deep -> parent is root
133
    }
134
}
135
136
pub fn format_mode(mode: u32, kind: &EntryKind) -> String {
137
    match kind {
138
        EntryKind::Tree => "drwxr-xr-x".to_string(),
139
        EntryKind::Link => "lrwxrwxrwx".to_string(),
140
        EntryKind::Commit => "m---------".to_string(), // submodule / gitlink
141
        EntryKind::Blob | EntryKind::BlobExecutable => {
142
            let perm = mode & 0o777;
143
            let mut s = String::from("-");
144
            for shift in [6, 3, 0] {
145
                let bits = (perm >> shift) & 0o7;
146
                s.push(if bits & 0o4 != 0 { 'r' } else { '-' });
147
                s.push(if bits & 0o2 != 0 { 'w' } else { '-' });
148
                s.push(if bits & 0o1 != 0 { 'x' } else { '-' });
149
            }
150
            s
151
        }
152
    }
153
}
154
155
fn format_size(bytes: u64) -> String {
156
    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
157
    let mut size = bytes as f64;
158
    let mut unit = 0;
159
    while size >= 1024.0 && unit < UNITS.len() - 1 {
160
        size /= 1024.0;
161
        unit += 1;
162
    }
163
    if unit == 0 {
164
        format!("{bytes} B")
165
    } else {
166
        format!("{size:.1} {}", UNITS[unit])
167
    }
168
}