GITv
master
tree.rs170 lines, 7.3 KB
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
//! Folder listings, with the latest change to each entry and the README.

use std::ffi::OsStr;

use gitv_core::config;
use gitv_web::render;

use super::{Entry, PAGE, Repo, SHOW_LIMIT, entry};
use crate::cache::cached;
use crate::html::{ago, icon, plural, size, subject_or_placeholder};
use crate::urls::{Q, clean_path, encode, join, lossy, param, parent_of, spec};
use crate::{View, templates};

pub(crate) fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
    let reference = repo.reference(q);
    let path = clean_path(q.get("path").map_or(&[][..], Vec::as_slice))?;
    let Some(commit) = repo.reader.resolve(&reference) else {
        if !repo.reader.heads().is_empty() {
            return None;
        }
        let page = templates::Empty {
            title: format!("{}/{}", repo.owner, repo.name),
            signed_in: repo.signed_in,
            masthead: repo.masthead("tree", &reference, None),
            host: config::host(),
            owner: &repo.owner,
            name: &repo.name,
        };
        return Some(View::Html(page.to_string()));
    };
    let listing = [OsStr::new("ls-tree"), OsStr::new("-l"), OsStr::new("-z"), &spec(&commit, &path)];
    let Some(listing) = repo.reader.git_bytes(&listing) else {
        // A file path: show it in the file view instead.
        return entry(repo, &commit, &path)
            .filter(|e| e.kind == "blob")
            .map(|_| View::Redirect(repo.url_at("blob", &reference, &path, "")));
    };
    let mut entries = Entry::list(&listing);
    // Folders first, then files and submodules, each alphabetically.
    entries.sort_by_cached_key(|e| (e.kind != "tree", e.name.to_ascii_lowercase()));

    let page: usize = param(q, "page").and_then(|n| n.parse().ok()).unwrap_or(0);
    let offset = page.checked_mul(PAGE)?;
    if page != 0 && offset >= entries.len() {
        return None;
    }
    let mut rows = Vec::new();
    let visible = &entries[offset..entries.len().min(offset + PAGE)];
    let names: Vec<_> = visible.iter().map(|item| item.name.as_slice()).collect();
    let histories = repo.reader.entry_histories(&commit, &path, &names);
    for (item, record) in visible.iter().zip(histories) {
        let path = join(&path, &item.name);
        let (view, class, glyph) = match item.kind.as_str() {
            "tree" => (Some("tree"), "entry dir", "dir"),
            "commit" => (None, "entry sub", "module"),
            _ => (Some("blob"), "entry", "file"),
        };
        let row = templates::TreeRow {
            name: lossy(&item.name),
            class,
            icon: icon(glyph),
            href: view.map(|view| repo.url_at(view, &reference, &path, "")),
            short_id: &item.oid[..item.oid.len().min(7)],
            commit: record.as_deref().and_then(|record| repo.entry_commit(record)),
        };
        rows.push(row);
    }
    let page_url = |number| repo.url_at("tree", &reference, &path, &format!("page={number}"));
    // README.md over README or README.txt, as people expect.
    let readmes = entries.iter().filter(|e| e.kind == "blob" && e.name.to_ascii_lowercase().starts_with(b"readme"));
    let readme = readmes.clone().find(|e| render::is_markdown(&lossy(&e.name))).or_else(|| readmes.clone().next());
    let readme = readme.filter(|e| e.size <= SHOW_LIMIT).map(|readme| {
        let name = lossy(&readme.name);
        let as_code = !render::is_markdown(&name);
        let rendered = render_file(repo, &readme.oid, readme.size, &name, &path, &reference, as_code, None);
        let content =
            rendered.map_or_else(|| r#"<p class="note">This README couldn't be read.</p>"#.to_string(), |r| r.html);
        (name.into_owned(), content)
    });
    let title = if path.is_empty() {
        format!("{}/{}", repo.owner, repo.name)
    } else {
        format!("{} at {}", lossy(&path), lossy(&reference))
    };
    let head = repo.reader.latest(&commit, &path).map(|head| templates::TreeHead {
        url: repo.url("commit", &[("id", &head.oid)]),
        sha_link: repo.sha_link(&head.oid),
        subject: subject_or_placeholder(&head.subject).to_string(),
        author: head.author,
        when: ago(&head.stamp, &head.date),
        history: repo.url_at("log", &reference, &path, ""),
    });
    Some(View::Html(
        templates::Tree {
            title,
            signed_in: repo.signed_in,
            masthead: repo.masthead("tree", &reference, Some(&commit)),
            locator: repo.locator("tree", &reference, &path),
            head,
            up: (!path.is_empty()).then(|| repo.url_at("tree", &reference, parent_of(&path), "")),
            rows,
            previous: page.checked_sub(1).map(page_url),
            next: (entries.len() - offset > PAGE).then(|| page_url(page + 1)),
            readme,
        }
        .to_string(),
    ))
}

/// A file rendered for display: a summary (`facts`) and its HTML.
pub(crate) struct Rendered {
    pub(crate) facts: String,
    pub(crate) html: String,
}

/// A file rendered for display: highlighted code, or Markdown with links into this repository
/// at `reference` (the file lives in `dir`). The file view and the README panel both use this,
/// so they share one cached value per rendering instead of storing different shapes under one
/// key. The facts and the rendering are cached together, so a repeat view reads no blob at all.
///
/// Code is cached as `facts` 0x1f `line count` 0x1f `highlighted`, and its gutter is built per
/// request, because only the gutter depends on which lines a link selects. Anything else is
/// cached as `facts` 0x1f 0x1f `html`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn render_file(
    repo: &Repo,
    oid: &str,
    file_size: usize,
    name: &str,
    dir: &[u8],
    reference: &[u8],
    as_code: bool,
    selected: Option<(usize, usize)>,
) -> Option<Rendered> {
    let key = if as_code {
        // Highlighting depends only on the content and the file's type, so it's shared.
        format!("code:{oid}:{name}")
    } else {
        // Links depend on the repository, folder and ref too.
        repo.key("md", oid, &format!("{}:{}", encode(dir), encode(reference)))
    };
    let value = cached(key, || {
        let data = repo.reader.git_bytes(&["cat-file", "blob", oid])?;
        if data.iter().take(8000).any(|b| *b == 0) {
            let note = r#"<p class="note">This is a binary file. Use Raw to download it.</p>"#;
            return Some(format!("{}\x1f\x1f{note}", size(file_size)));
        }
        let text = String::from_utf8_lossy(&data);
        let lines = text.lines().count();
        let facts = format!("{}, {}", plural(lines, "line", "lines"), size(file_size));
        Some(if as_code {
            format!("{facts}\x1f{}\x1f{}", lines.max(1), render::highlight(name, &text))
        } else {
            let html = repo.markdown(&text, dir, reference);
            format!("{facts}\x1f\x1f<article class=\"markdown\">{html}</article>")
        })
    })?;
    let mut parts = value.splitn(3, '\x1f');
    let (facts, lines, html) = (parts.next()?, parts.next()?, parts.next()?);
    let html = match lines.parse() {
        Ok(lines) => code_view(lines, html, selected),
        Err(_) => html.to_string(),
    };
    Some(Rendered { facts: facts.to_string(), html })
}

/// Highlighted source with its line-number gutter.
pub(crate) fn code_view(lines: usize, code: &str, selected: Option<(usize, usize)>) -> String {
    templates::Code { lines, selected, code }.to_string()
}