puffin_build/utils/
git.rs

1use std::ffi::OsStr;
2use std::path::{Path, PathBuf};
3use std::process::{Command, ExitStatus};
4use std::{fmt, io};
5
6use serde::{Deserialize, Serialize};
7
8pub fn archive(tree: impl Into<Tree>) -> GitArchive {
9    GitArchive::new(tree)
10}
11
12pub fn clone(tree: impl Into<Tree>) -> GitClone {
13    GitClone::new(tree)
14}
15
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17pub struct Tree {
18    repo: Repo,
19    #[serde(flatten)]
20    #[serde(skip_serializing_if = "Head::is_default")]
21    head: Head,
22}
23
24impl Tree {
25    pub fn new(repo: impl Into<Repo>, head: impl Into<Head>) -> Self {
26        Self {
27            repo: repo.into(),
28            head: head.into(),
29        }
30    }
31}
32
33impl From<Repo> for Tree {
34    fn from(repo: Repo) -> Self {
35        Self {
36            repo,
37            head: Head::Default,
38        }
39    }
40}
41
42impl From<&str> for Tree {
43    fn from(repo: &str) -> Self {
44        Self::from(Into::<Repo>::into(repo))
45    }
46}
47
48impl fmt::Display for Tree {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        write!(f, "{}_{}", self.repo, self.head)
51    }
52}
53
54#[derive(Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum Head {
57    #[default]
58    Default,
59    Branch(String),
60    Commit(String),
61}
62
63impl Head {
64    pub fn branch(name: impl AsRef<str>) -> Self {
65        Self::Branch(name.as_ref().to_owned())
66    }
67
68    pub fn commit(hash: impl AsRef<str>) -> Self {
69        Self::Commit(hash.as_ref().to_owned())
70    }
71
72    pub fn is_default(&self) -> bool {
73        matches!(self, Self::Default)
74    }
75}
76
77impl fmt::Display for Head {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        match self {
80            Head::Default => f.write_str("default"),
81            Head::Branch(b) => f.write_str(b),
82            Head::Commit(c) => f.write_str(c),
83        }
84    }
85}
86
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub struct Repo(String);
89
90impl Repo {
91    pub fn new(s: impl AsRef<str>) -> Self {
92        Repo(s.as_ref().to_owned())
93    }
94
95    pub fn at(&self, head: impl Into<Head>) -> Tree {
96        Tree::new(self.clone(), head)
97    }
98
99    pub fn at_commit(&self, id: impl Into<String>) -> Tree {
100        Tree::new(self.clone(), Head::Commit(id.into()))
101    }
102
103    pub fn at_branch(&mut self, name: impl Into<String>) -> Tree {
104        Tree::new(self.clone(), Head::Branch(name.into()))
105    }
106
107    pub fn at_default(&mut self) -> Tree {
108        Tree::new(self.clone(), Head::Default)
109    }
110}
111
112impl From<&str> for Repo {
113    fn from(value: &str) -> Self {
114        Self(value.into())
115    }
116}
117
118impl fmt::Display for Repo {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(f, "{}", self.0)
121    }
122}
123
124#[derive(Debug, Clone)]
125pub struct GitArchive {
126    pub tree: Tree,
127    format: String,
128}
129
130impl GitArchive {
131    fn new(tree: impl Into<Tree>) -> Self {
132        Self {
133            tree: tree.into(),
134            format: String::from("tar.gz"),
135        }
136    }
137
138    pub fn to_dir(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> {
139        // NOTE using git-archive directly would be more efficient but is not supported by GitHub
140        //
141        // Running `git archive --remote=...` would allow us to efficiently download an archive
142        // matching the requested head. Instead, we perform a shallow clone and then archive the
143        // result.
144        //
145        // see also: https://docs.github.com/en/repositories/working-with-files/using-files/downloading-source-code-archives
146        // see also: https://github.com/isaacs/github/issues/554
147
148        let archive_file = path
149            .as_ref()
150            .join(format!("git.{}.{}", self.tree.head, self.format));
151        let download_dir = tempfile::tempdir()?;
152
153        clone(self.tree.clone()).shallow().to_dir(&download_dir)?;
154
155        let mut cmd = Command::new("git");
156        cmd.arg("-C").arg(download_dir.path()).arg("archive");
157        cmd.arg(format!("--format={}", self.format));
158        cmd.arg(format!("--output={}", archive_file.display()));
159        cmd.arg("HEAD");
160
161        cmd.status()?
162            .success()
163            .then_some(archive_file)
164            .ok_or(io::Error::other(format!(
165                "failed git archive: tree={:?}",
166                self.tree
167            )))
168    }
169}
170
171#[derive(Debug, Clone)]
172pub struct GitClone {
173    pub tree: Tree,
174    shallow: bool,
175}
176
177impl GitClone {
178    pub fn new(tree: impl Into<Tree>) -> Self {
179        Self {
180            tree: tree.into(),
181            shallow: false,
182        }
183    }
184
185    pub fn shallow(&mut self) -> &mut Self {
186        self.shallow = true;
187        self
188    }
189
190    pub fn full(&mut self) -> &mut Self {
191        self.shallow = false;
192        self
193    }
194
195    pub fn to_dir(&self, path: impl AsRef<Path>) -> io::Result<()> {
196        let status = match self.tree.head {
197            Head::Default => self.do_clone_branch(Option::<&str>::None, path.as_ref()),
198            Head::Branch(ref name) => self.do_clone_branch(Some(name), path.as_ref()),
199            Head::Commit(ref id) => self.do_clone_commit(id, path.as_ref()),
200        };
201
202        status?
203            .success()
204            .then_some(())
205            .ok_or(io::Error::other(format!(
206                "failed git clone: tree={:?}",
207                self.tree
208            )))
209    }
210
211    fn do_clone_branch(
212        &self,
213        maybe_name: Option<impl AsRef<OsStr>>,
214        to: impl AsRef<OsStr>,
215    ) -> io::Result<ExitStatus> {
216        let mut cmd = Command::new("git");
217        cmd.arg("clone");
218
219        if let Some(name) = maybe_name {
220            cmd.arg("--branch");
221            cmd.arg(name.as_ref());
222        }
223
224        if self.shallow {
225            cmd.arg("--depth=1");
226        }
227
228        cmd.arg(&self.tree.repo.0).arg(to.as_ref()).status()
229    }
230
231    fn do_clone_commit(
232        &self,
233        commit_id: impl AsRef<OsStr>,
234        to: impl AsRef<OsStr>,
235    ) -> io::Result<ExitStatus> {
236        let mut cmd = Command::new("git");
237        cmd.arg("clone");
238
239        if self.shallow {
240            cmd.arg("--filter=tree:0");
241        }
242
243        cmd.arg(&self.tree.repo.0).arg(to.as_ref()).status()?;
244
245        Command::new("git")
246            .current_dir(to.as_ref())
247            .arg("checkout")
248            .arg(commit_id)
249            .status()
250    }
251}