//! A revision's files as a `.tar.gz`, made by `git archive`. use super::Repo; use crate::View; use crate::urls::Q; pub(crate) fn view_archive(repo: &Repo, q: &Q) -> Option { let reference = q.get("ref")?; let commit = repo.reader.resolve(reference)?; let base = format!("{}-{}", repo.name, archive_label(reference, &commit)); let prefix = format!("--prefix={base}/"); let mut command = gitv_core::git_command(&repo.reader.dir); // The commit id, not the name: what's archived is exactly what was resolved, and the // archive's file times are that commit's time, so the same revision always gives the // same bytes. command.args(["archive", "--format=tar.gz", &prefix, &commit, "--"]); Some(View::Archive(Box::new(command), format!("{base}.tar.gz"))) } /// The revision's part of the archive's name: a branch or tag name with `refs/…` dropped, or a /// short id for a commit id. Only letters, digits and `.`, `_`, `+`, `-` are kept, so the name /// is safe as a file name and inside a quoted header. pub(crate) fn archive_label(reference: &[u8], commit: &str) -> String { let name = reference.strip_prefix(b"refs/tags/").or_else(|| reference.strip_prefix(b"refs/heads/")).unwrap_or(reference); if name.eq_ignore_ascii_case(commit.as_bytes()) { return commit[..12].to_string(); } let label: String = name.iter().map(|&b| if b.is_ascii_alphanumeric() || b"._+-".contains(&b) { b as char } else { '-' }).collect(); let label = label.trim_matches(['-', '.']); if label.is_empty() { commit[..12].to_string() } else { label.to_string() } } #[cfg(test)] mod tests { use super::*; #[test] fn archive_names_are_plain_file_names() { let id = "0123456789abcdef0123456789abcdef01234567"; assert_eq!(archive_label(b"refs/tags/v1.2.0", id), "v1.2.0"); assert_eq!(archive_label(b"release/2.0", id), "release-2.0"); assert_eq!(archive_label(b"caf\xc3\xa9 \"quoted\"", id), "caf----quoted"); assert_eq!(archive_label(b"..", id), "0123456789ab"); assert_eq!(archive_label(id.to_uppercase().as_bytes(), id), "0123456789ab"); } }