GITv
master
tags.rs101 lines, 4.2 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
//! The tags in a repository.

use std::collections::HashMap;

use data_encoding::HEXLOWER;
use sha2::{Digest, Sha256};

use super::Repo;
use crate::cache::cached;
use crate::html::ago;
use crate::urls::lossy;
use crate::{View, templates};

pub(crate) fn view_tags(repo: &Repo) -> Option<View> {
    let out = repo.reader.git_bytes(&[
        "for-each-ref",
        "--sort=-creatordate",
        "--format=%(refname:lstrip=2)%1f%(objectname)%1f%(*objectname)%1f%(creatordate:unix)%1f%(creatordate:format:%-d %b %Y)%1f%(objecttype)%1f%(contents:subject)",
        "refs/tags",
    ])?;
    let mut rows: Vec<templates::TagRow> = Vec::new();
    let mut names: Vec<&[u8]> = Vec::new();
    let mut targets: Vec<String> = Vec::new();
    for line in out.split(|b| *b == b'\n') {
        // The tag's message goes last, so one containing the separator stays whole.
        let Ok([name, direct, peeled, stamp, date, kind, note]) =
            <[&[u8]; 7]>::try_from(line.splitn(7, |b| *b == 0x1f).collect::<Vec<_>>())
        else {
            continue;
        };
        let target = if peeled.is_empty() { direct } else { peeled };
        names.push(name);
        targets.push(lossy(target).into_owned());
        rows.push(templates::TagRow {
            name: lossy(name),
            note: (kind == b"tag" && !note.is_empty()).then(|| lossy(note)),
            sha_link: repo.sha_link(&lossy(target)),
            when: ago(&lossy(stamp), &lossy(date)),
            browse: repo.url_at("tree", &repo.reader.tag_ref(name), b"", ""),
            archive: repo.url_at("archive", &repo.reader.tag_ref(name), b"", ""),
            compare: None,
        });
    }
    // Each tag is compared with the release before it: the nearest tag in its own history.
    for (row, (i, previous)) in rows.iter_mut().zip(previous_tags(repo, &out, &targets).into_iter().enumerate()) {
        if let Some(previous) = previous.and_then(|p| names.get(p)) {
            let (from, to) = (repo.reader.tag_ref(previous), repo.reader.tag_ref(names[i]));
            row.compare = Some((repo.compare_url(&from, &to), format!("Changes since {}", lossy(previous))));
        }
    }
    Some(View::Html(
        templates::Tags {
            title: format!("Tags in {}/{}", repo.owner, repo.name),
            signed_in: repo.signed_in,
            masthead: repo.masthead("tags", &repo.reader.default_ref(), None),
            rows,
        }
        .to_string(),
    ))
}

/// For each tag, the index in `names` of the tag before it: the nearest tagged commit back
/// along its first parents, so a merge's tag follows its main line rather than the branch it
/// merged. Creation dates can't order releases: tags made in the same second, or added late,
/// would pair with the wrong neighbour.
///
/// One walk of the tagged history answers for every tag. `--simplify-by-decoration` keeps only
/// tagged commits and rewrites each one's parents to the nearest tagged ones. The answer is
/// cached for the whole listing; `listing` (every tag's name, target and date) names it, so any
/// change to the tags makes a new entry. If git fails, nothing is cached and no links show.
fn previous_tags(repo: &Repo, listing: &[u8], targets: &[String]) -> Vec<Option<usize>> {
    let key = repo.key("previous-tags", &HEXLOWER.encode(&Sha256::digest(listing)), "");
    let walk = cached(key, || {
        repo.reader.git(&[
            "log",
            "--first-parent",
            "--simplify-by-decoration",
            "--decorate-refs=refs/tags/",
            "--parents",
            "--format=%H %P",
            "--tags",
            "--",
        ])
    });
    // Each tagged commit and its first rewritten parent, if it has one.
    let parent: HashMap<&str, &str> = walk
        .as_deref()
        .unwrap_or_default()
        .lines()
        .filter_map(|line| {
            let mut ids = line.split(' ');
            Some((ids.next()?, ids.next()?))
        })
        .collect();
    // The first listed tag at a commit (the newest, as the page lists them) stands for it.
    let mut tag_at: HashMap<&str, usize> = HashMap::new();
    for (i, target) in targets.iter().enumerate() {
        tag_at.entry(target.as_str()).or_insert(i);
    }
    targets.iter().map(|target| parent.get(target.as_str()).and_then(|p| tag_at.get(p).copied())).collect()
}