flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/services/repos/src/refs.rs

107 lines4,004 bytesCodeBlame
1//! Listing a repository's branches.
2//!
3//! The Artifacts binding reads commits, trees and blobs but does not list
4//! refs, so this asks the way a git client does: the ref advertisement of
5//! the smart HTTP protocol.
6
7use g1t_contracts::repos::{Branch, GitAccess};
8use worker::{Error, Fetch, Headers, Method, Request, RequestInit, Result};
9
10use crate::land::read_pkt_lines;
11
12const HEADS: &str = "refs/heads/";
13
14/// Every ref in a ref advertisement, with its commit, in the order
15/// advertised: `(refs/heads/main, <hash>)`.
16fn parse_refs(bytes: &[u8]) -> Vec<(String, String)> {
17 let (lines, _) = read_pkt_lines(bytes);
18 lines
19 .into_iter()
20 .filter_map(|line| {
21 // `<hash> <ref>`, and on the first ref a NUL then capabilities.
22 let line = line.split(|byte| *byte == 0).next()?;
23 let line = std::str::from_utf8(line).ok()?.trim_end();
24 let (hash, name) = line.split_once(' ')?;
25 (hash.len() >= 40 && name.starts_with("refs/")).then(|| (name.to_owned(), hash.to_owned()))
26 })
27 .collect()
28}
29
30/// The branches in a ref advertisement, in the order advertised.
31fn parse_advertisement(bytes: &[u8]) -> Vec<Branch> {
32 parse_refs(bytes)
33 .into_iter()
34 .filter_map(|(name, hash)| Some(Branch { name: name.strip_prefix(HEADS)?.to_owned(), hash }))
35 .collect()
36}
37
38pub async fn branches(access: &GitAccess) -> Result<Vec<Branch>> {
39 Ok(parse_advertisement(&advertisement(access).await?))
40}
41
42/// Every ref the repository has: branches, tags, and the heads of pull
43/// requests kept there (forks.rs).
44pub async fn all(access: &GitAccess) -> Result<Vec<(String, String)>> {
45 Ok(parse_refs(&advertisement(access).await?))
46}
47
48async fn advertisement(access: &GitAccess) -> Result<Vec<u8>> {
49 let headers = Headers::new();
50 headers.set("authorization", &format!("Bearer {}", access.token))?;
51 let mut init = RequestInit::new();
52 init.with_method(Method::Get).with_headers(headers);
53 let request = Request::new_with_init(
54 &format!("{}/info/refs?service=git-upload-pack", access.remote),
55 &init,
56 )?;
57 let mut response = Fetch::Request(request).send().await?;
58 let bytes = response.bytes().await?;
59 crate::meters::record_remote("internal.git.info_refs", &access.remote, 0, bytes.len() as u64);
60 if response.status_code() != 200 {
61 return Err(Error::RustError(format!(
62 "listing refs returned {}",
63 response.status_code()
64 )));
65 }
66 Ok(bytes)
67}
68
69#[cfg(test)]
70mod tests {
71 use super::{parse_advertisement, parse_refs};
72
73 fn pkt(payload: &str) -> Vec<u8> {
74 format!("{:04x}{payload}", payload.len() + 4).into_bytes()
75 }
76
77 #[test]
78 fn branches_are_read_from_an_advertisement() {
79 let main = "c71546fcd893ef8b0f57388b65e620d759705dda";
80 let shout = "4807077b296e6edbf410d55e72749d3e1170c291";
81 let advertisement = [
82 pkt("# service=git-upload-pack\n"),
83 b"0000".to_vec(),
84 pkt(&format!(
85 "{main} HEAD\0side-band-64k symref=HEAD:refs/heads/main\n"
86 )),
87 pkt(&format!("{main} refs/heads/main\n")),
88 pkt(&format!("{shout} refs/heads/shout\n")),
89 pkt(&format!("{shout} refs/tags/v1.0.0\n")),
90 b"0000".to_vec(),
91 ]
92 .concat();
93 let branches = parse_advertisement(&advertisement);
94 let names: Vec<&str> = branches.iter().map(|branch| branch.name.as_str()).collect();
95 assert_eq!(names, ["main", "shout"]);
96 assert_eq!(branches[1].hash, shout);
97 let all = parse_refs(&advertisement);
98 assert_eq!(all.len(), 3);
99 assert_eq!(all[2], ("refs/tags/v1.0.0".to_owned(), shout.to_owned()));
100 }
101
102 #[test]
103 fn an_empty_repository_has_no_branches() {
104 let advertisement = [pkt("# service=git-upload-pack\n"), b"00000000".to_vec()].concat();
105 assert!(parse_advertisement(&advertisement).is_empty());
106 }
107}