index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / git / repository.rs
-rw-r--r-- blob 9fc99b1923e44bada2fe0345dea24b021a71d8bc 6962 bytes (plain)
1
use std::{
2
    ffi::OsStr,
3
    path::{Path, PathBuf},
4
};
5
6
use anyhow::Context;
7
use flate2::{Compression, write::GzEncoder};
8
use gix::objs::tree::EntryKind;
9
use tar::Builder;
10
11
use crate::{
12
    error::Error,
13
    git::{
14
        refs::Ref,
15
        tree::{self, Blob, PathView},
16
    },
17
};
18
19
#[derive(Clone)]
20
pub struct Repository {
21
    pub name: String,
22
    pub description: String,
23
    pub owner: Option<String>,
24
    pub path: PathBuf,
25
    pub gix: gix::ThreadSafeRepository,
26
}
27
28
impl Repository {
29
    pub fn open(path: &Path) -> Result<Self, Error> {
30
        let name = path
31
            .file_name()
32
            .and_then(OsStr::to_str)
33
            .ok_or(Error::Failed)?;
34
35
        let raw_desc = std::fs::read(path.join("description")).unwrap_or_default();
36
        let description = match String::from_utf8(raw_desc) {
37
            Ok(s) if !s.is_empty() => s,
38
            Ok(_) => "There is no description!".to_string(),
39
            Err(_) => "Failed to get the description!".to_string(),
40
        };
41
42
        let gix = gix::ThreadSafeRepository::open(path).map_err(|_| Error::Failed)?;
43
        let owner = gix
44
            .to_thread_local()
45
            .config_snapshot()
46
            .string("gitweb.owner")
47
            .map(|v| v.to_string());
48
49
        Ok(Self {
50
            name: name.to_string(),
51
            description,
52
            owner,
53
            path: path.to_path_buf(),
54
            gix,
55
        })
56
    }
57
58
    pub fn gix(&self) -> gix::Repository {
59
        self.gix.to_thread_local()
60
    }
61
62
    pub fn readme(&self) -> Option<String> {
63
        let gix_repo = self.gix();
64
        let tree = gix_repo.head().ok()?.peel_to_commit().ok()?.tree().ok()?;
65
66
        for entry in tree.iter().flatten() {
67
            if entry
68
                .filename()
69
                .to_string()
70
                .to_ascii_lowercase()
71
                .starts_with("readme")
72
            {
73
                let blob = entry.object().ok()?.into_blob();
74
                return Some(String::from_utf8_lossy(&blob.data).into_owned());
75
            }
76
        }
77
        None
78
    }
79
80
    pub fn archive(
81
        &self,
82
        current_ref: &Ref,
83
        commit: &Option<String>,
84
    ) -> Result<(Vec<u8>, String), anyhow::Error> {
85
        let gix_repo = self.gix();
86
        let (tree, filename) = if let Some(commit) = commit {
87
            (
88
                self.find_commit(&gix_repo, commit)?.gix.tree()?,
89
                format!("{commit}.tar.gz"),
90
            )
91
        } else {
92
            (
93
                Self::root_tree(&gix_repo, current_ref)?,
94
                format!("{}.tar.gz", current_ref.name.replace('/', "-")),
95
            )
96
        };
97
98
        let encoder = GzEncoder::new(Vec::new(), Compression::default());
99
        let mut builder = Builder::new(encoder);
100
101
        Self::add_tree_to_archive(&tree, "", &mut builder)?;
102
103
        let bytes = builder.into_inner()?.finish()?;
104
        Ok((bytes, filename))
105
    }
106
107
    fn add_tree_to_archive(
108
        tree: &gix::Tree<'_>,
109
        prefix: &str,
110
        builder: &mut Builder<GzEncoder<Vec<u8>>>,
111
    ) -> anyhow::Result<()> {
112
        for entry in tree.iter() {
113
            let entry = entry?;
114
            let mode = entry.mode();
115
            let name = entry.filename().to_string();
116
            let path = if prefix.is_empty() {
117
                name
118
            } else {
119
                format!("{prefix}/{name}")
120
            };
121
122
            if mode.is_tree() {
123
                let subtree = entry.object()?.into_tree();
124
                Self::add_tree_to_archive(&subtree, &path, builder)?;
125
            } else if mode.is_blob() || mode.is_executable() {
126
                let blob = entry.object()?.into_blob();
127
                let data = &blob.data;
128
129
                let mut header = tar::Header::new_gnu();
130
                header.set_size(data.len() as u64);
131
                header.set_mode(if mode.is_executable() { 0o755 } else { 0o644 });
132
                header.set_cksum();
133
134
                builder.append_data(&mut header, &path, &data[..])?;
135
            }
136
        }
137
        Ok(())
138
    }
139
140
    pub fn resolve_path(&self, current_ref: &Ref, path: &str) -> anyhow::Result<PathView> {
141
        let gix_repo = self.gix();
142
        let root_tree = Self::root_tree(&gix_repo, current_ref)?;
143
        let path = path.trim_matches('/');
144
145
        if path.is_empty() {
146
            return Ok(PathView::Tree(tree::read_entries(&root_tree, "")?));
147
        }
148
149
        let entry = Self::lookup_entry(&root_tree, path)?;
150
        let mode = entry.mode();
151
152
        match mode.kind() {
153
            EntryKind::Tree => {
154
                let subtree = entry.object()?.into_tree();
155
                Ok(PathView::Tree(tree::read_entries(&subtree, path)?))
156
            }
157
            EntryKind::Blob | EntryKind::BlobExecutable => {
158
                let blob = entry.object()?.into_blob();
159
                let lines = std::str::from_utf8(&blob.data)
160
                    .ok()
161
                    .map(|s| crate::syntax_highlight::highlight_lines(s, path));
162
163
                Ok(PathView::Blob(Blob {
164
                    id: entry.oid().to_string(),
165
                    mode: mode.value() as u32,
166
                    size: blob.data.len() as u64,
167
                    lines,
168
                }))
169
            }
170
            EntryKind::Link => anyhow::bail!("symlinks are not yet supported for direct viewing"),
171
            EntryKind::Commit => {
172
                anyhow::bail!("path resolves to a submodule, not a viewable file/dir")
173
            }
174
        }
175
    }
176
177
    pub fn read_raw_blob(&self, current_ref: &Ref, path: &str) -> anyhow::Result<Option<Vec<u8>>> {
178
        let path = path.trim_matches('/');
179
        if path.is_empty() {
180
            return Ok(None);
181
        }
182
183
        let gix_repo = self.gix();
184
        let root_tree = Self::root_tree(&gix_repo, current_ref)?;
185
        let entry = Self::lookup_entry(&root_tree, path)?;
186
187
        match entry.mode().kind() {
188
            EntryKind::Tree => Ok(None),
189
            EntryKind::Blob | EntryKind::BlobExecutable => {
190
                let blob = entry.object()?.into_blob();
191
                Ok(Some(blob.detach().data))
192
            }
193
            EntryKind::Link => anyhow::bail!("symlinks are not yet supported for direct viewing"),
194
            EntryKind::Commit => {
195
                anyhow::bail!("path resolves to a submodule, not a viewable file/dir")
196
            }
197
        }
198
    }
199
200
    fn root_tree<'a>(
201
        gix_repo: &'a gix::Repository,
202
        current_ref: &Ref,
203
    ) -> anyhow::Result<gix::Tree<'a>> {
204
        gix_repo
205
            .find_reference(&current_ref.name)?
206
            .peel_to_tree()
207
            .context("failed to get root tree")
208
    }
209
210
    fn lookup_entry<'a>(
211
        root_tree: &gix::Tree<'a>,
212
        path: &str,
213
    ) -> anyhow::Result<gix::object::tree::Entry<'a>> {
214
        root_tree
215
            .lookup_entry_by_path(path)
216
            .with_context(|| format!("failed lookup for path: {path}"))?
217
            .with_context(|| format!("path not found: {path}"))
218
    }
219
}