GITv
master
index.rs219 lines, 9.7 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//! The repository index.

use std::cmp::Reverse;
use std::ffi::OsStr;
use std::fmt::Write as _;
use std::os::fd::{AsFd, OwnedFd};
use std::sync::Arc;
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use gitv_core::{RepoDir, config, entries, open_dir_at, open_owner, open_root, repo_in, try_subdirs};

use super::Repo;
use crate::cache::cached;
use crate::html::{ago, icon, plural, subject_or_placeholder};
use crate::repository::Head;
use crate::urls::{Q, param};
use crate::{View, templates};

/// The names in an open directory, sorted, skipping hidden ones and any that aren't UTF-8
/// (no valid owner or repository name is).
pub(crate) fn sorted_names(dir: &impl AsFd) -> Vec<String> {
    let mut names: Vec<String> =
        entries(dir).into_iter().filter_map(|n| n.into_string().ok()).filter(|n| !n.starts_with('.')).collect();
    names.sort();
    names
}

/// A fingerprint of a repository's branches, for caching its row on the index. Git updates a
/// ref by renaming a file into place (a loose ref under `refs/heads`, or `packed-refs` and
/// `HEAD` in the repository directory, or a table under `reftable`), and a rename changes the
/// directory's modification time. So the times of those directories change whenever a branch
/// or HEAD does. It reads them through the repository's open handle, the same directory git
/// reads, never through a path. The current minute is included too, which bounds staleness
/// should two pushes land within the filesystem's timestamp granularity.
pub(crate) fn refs_fingerprint(repo: &RepoDir) -> Option<String> {
    /// Append a directory's modification time.
    pub(crate) fn note(stamp: &mut String, dir: &impl AsFd) -> Option<()> {
        let meta = nix::sys::stat::fstat(dir.as_fd()).ok()?;
        let _ = write!(stamp, ":{}.{}", meta.st_mtime, meta.st_mtime_nsec);
        Some(())
    }
    /// Note `dir` and every directory under it, depth first, holding open only the directories
    /// on the current path, never all the siblings at once. Any directory that can't be read
    /// makes the whole fingerprint `None`, so a partial one is never trusted.
    pub(crate) fn walk(stamp: &mut String, dir: &OwnedFd) -> Option<()> {
        note(stamp, dir)?;
        let mut names = try_subdirs(dir).ok()?;
        names.sort();
        // Ref files (and entries deleted since the listing) are covered by their directory's
        // time; only subdirectories need visiting.
        for name in names {
            stamp.push('/');
            walk(stamp, &open_dir_at(dir, &name).ok()?)?;
        }
        Some(())
    }
    /// A directory that may legitimately be absent: absent is a fact, unreadable is not.
    pub(crate) fn optional(parent: &impl AsFd, name: &str) -> Option<Option<OwnedFd>> {
        match open_dir_at(parent, OsStr::new(name)) {
            Ok(dir) => Some(Some(dir)),
            Err(nix::errno::Errno::ENOENT) => Some(None),
            Err(_) => None,
        }
    }
    let minute = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() / 60;
    let mut stamp = format!("{minute}");
    note(&mut stamp, &repo.handle())?;
    let refs = optional(&repo.handle(), "refs")?;
    for dir in [refs.as_ref(), optional(&repo.handle(), "reftable")?.as_ref()] {
        match dir {
            Some(dir) => note(&mut stamp, dir)?,
            None => stamp.push_str(":-"),
        }
    }
    if let Some(refs) = refs.as_ref()
        && let Some(heads) = optional(refs, "heads")?
    {
        walk(&mut stamp, &heads)?;
    }
    Some(stamp)
}

/// One row of the index: everything it shows, and no open repository handle, so a large
/// installation holds one handle at a time however many repositories it lists.
pub(crate) struct Row {
    pub(crate) public: bool,
    pub(crate) owner: String,
    pub(crate) name: String,
    pub(crate) description: Option<String>,
    pub(crate) head: Option<Head>,
}

/// Whether a repository matches a filter: every word of it appears, ignoring case, in the
/// repository's `owner/name` or its description.
fn matches(words: &[String], owner: &str, name: &str, description: Option<&str>) -> bool {
    let haystack = format!("{owner}/{name} {}", description.unwrap_or_default()).to_lowercase();
    words.iter().all(|word| haystack.contains(word.as_str()))
}

pub(crate) fn view_index(signed_in: bool, q: &Q) -> View {
    let deadline = Instant::now() + gitv_core::GIT_TIMEOUT;
    let filter = param(q, "q").unwrap_or_default();
    let words: Vec<String> = filter.split_whitespace().map(str::to_lowercase).collect();
    let mut total = 0;
    let mut rows = Vec::new();
    let root = open_root();
    for owner in root.as_ref().map(sorted_names).unwrap_or_default() {
        // Read through the owner's open directory: a symlinked owner isn't followed or listed.
        let Some(owner_dir) = open_owner(&owner) else { continue };
        for entry in sorted_names(&owner_dir) {
            let Some(name) = entry.strip_suffix(".git") else { continue };
            if Instant::now() >= deadline {
                return View::Busy;
            }
            let Some(mut dir) = repo_in(&owner_dir, &owner, name) else { continue };
            let public = dir.is_public();
            if !signed_in && !public {
                continue;
            }
            total += 1;
            // Filtered before any git runs, so a narrow filter is cheap however many there are.
            let description = dir.description();
            if !matches(&words, &owner, name, description.as_deref()) {
                continue;
            }
            dir.limit_until(deadline);
            let repo = Repo::from_dir(&owner, name, dir);
            // HEAD usually names a real branch; only look further when it doesn't. An empty
            // repository caches as an empty answer.
            let lookup = || {
                let latest = repo.reader.latest_raw("HEAD", b"").or_else(|| {
                    repo.reader.resolve(&repo.reader.default_ref()).and_then(|id| repo.reader.latest_raw(&id, b""))
                });
                (Instant::now() < deadline).then(|| latest.unwrap_or_default())
            };
            let raw = match refs_fingerprint(&repo.reader.dir) {
                Some(stamp) => cached(format!("index:{}:{stamp}", repo.reader.dir.path.display()), lookup),
                None => lookup().map(Arc::from),
            };
            let head = raw.as_deref().and_then(Head::parse);
            // `repo`, and with it the directory handle, is dropped here.
            rows.push(Row { public, owner: owner.clone(), name: name.to_string(), description, head });
        }
    }
    rows.sort_by_key(|row| Reverse(row.head.as_ref().and_then(|h| h.stamp.parse::<u64>().ok()).unwrap_or(0)));
    let count = if words.is_empty() {
        plural(rows.len(), "repository", "repositories")
    } else {
        format!("{} of {total}", rows.len())
    };
    let rows = rows
        .into_iter()
        .map(|row| {
            let (subject, when) = row.head.map_or_else(
                || ("No commits yet".into(), String::new()),
                |h| (subject_or_placeholder(&h.subject).into(), ago(&h.stamp, &h.date)),
            );
            templates::RepositoryRow {
                owner: row.owner,
                name: row.name,
                public: row.public,
                description: row.description,
                subject,
                when,
            }
        })
        .collect();
    View::Html(
        templates::Repositories {
            title: "Repositories",
            signed_in,
            count,
            filter: filter.trim().to_string(),
            total,
            rows,
            branch: icon("branch"),
            host: config::host(),
        }
        .to_string(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn filters_match_every_word_in_the_name_or_description() {
        let words = |q: &str| q.split_whitespace().map(str::to_lowercase).collect::<Vec<_>>();
        assert!(matches(&words(""), "ada", "tools", None));
        assert!(matches(&words("TOOL"), "ada", "tools", None));
        assert!(matches(&words("ada/to"), "ada", "tools", None));
        assert!(matches(&words("small box"), "ada", "tools", Some("A small toolbox")));
        assert!(!matches(&words("small crate"), "ada", "tools", Some("A small toolbox")));
        assert!(!matches(&words("bob"), "ada", "tools", None));
    }
    #[test]
    fn an_incomplete_fingerprint_is_never_trusted() {
        if nix::unistd::geteuid().is_root() {
            return; // Root reads anything, so the unreadable folder below can't be made.
        }
        use std::os::unix::fs::PermissionsExt;
        let dir = std::env::temp_dir().join(format!("gitv-web-fingerprint-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        for folder in ["refs/heads/open", "refs/heads/locked/inner"] {
            std::fs::create_dir_all(dir.join(folder)).unwrap();
        }
        let repo = RepoDir::at(&dir).unwrap();
        assert!(refs_fingerprint(&repo).is_some());
        // A branch folder that can't be read: its refs could change unseen.
        std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o000)).unwrap();
        assert_eq!(refs_fingerprint(&repo), None, "a fingerprint missing a folder was trusted");
        // Names readable but not searchable: the folder's children can't be inspected.
        std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o444)).unwrap();
        assert_eq!(refs_fingerprint(&repo), None, "a fingerprint with an uninspectable folder was trusted");
        std::fs::set_permissions(dir.join("refs/heads/locked"), std::fs::Permissions::from_mode(0o755)).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }
}