1use std::path::{Path, PathBuf};
2
3use anyhow::{anyhow, Context};
4use tempfile::{tempdir, TempDir};
5use tokio::process::Command;
6use url::Url;
7
8use crate::{directory::subdirectories, git::UnderstandGitResult};
9
10const TEMPLATE_SOURCE_DIR: &str = "templates";
11const TEMPLATE_VERSION_TAG_PREFIX: &str = "spin/templates/v";
12
13#[derive(Debug)]
15pub enum TemplateSource {
16 Git(GitTemplateSource),
23 File(PathBuf),
28 RemoteTar(Url),
34}
35
36#[derive(Debug)]
38pub struct GitTemplateSource {
39 url: Url,
41 branch: Option<String>,
43 spin_version: String,
46}
47
48impl TemplateSource {
49 pub fn try_from_git(
52 git_url: impl AsRef<str>,
53 branch: &Option<String>,
54 spin_version: &str,
55 ) -> anyhow::Result<Self> {
56 let url_str = git_url.as_ref();
57 let url =
58 Url::parse(url_str).with_context(|| format!("Failed to parse {url_str} as URL"))?;
59 Ok(Self::Git(GitTemplateSource {
60 url,
61 branch: branch.clone(),
62 spin_version: spin_version.to_owned(),
63 }))
64 }
65
66 pub(crate) fn to_install_record(&self) -> Option<crate::reader::RawInstalledFrom> {
67 match self {
68 Self::Git(g) => Some(crate::reader::RawInstalledFrom::Git {
69 git: g.url.to_string(),
70 }),
71 Self::File(p) => {
72 if p.is_absolute() {
74 Some(crate::reader::RawInstalledFrom::File {
75 dir: format!("{}", p.display()),
76 })
77 } else {
78 None
79 }
80 }
81 Self::RemoteTar(url) => Some(crate::reader::RawInstalledFrom::RemoteTar {
82 url: url.to_string(),
83 }),
84 }
85 }
86
87 pub async fn resolved_tag(&self) -> Option<String> {
91 match self {
92 Self::Git(g) => version_matched_tag(g.url.as_str(), &g.spin_version).await,
93 _ => None,
94 }
95 }
96}
97
98pub(crate) struct LocalTemplateSource {
99 root: PathBuf,
100 _temp_dir: Option<TempDir>,
101}
102
103impl TemplateSource {
104 pub(crate) async fn get_local(&self) -> anyhow::Result<LocalTemplateSource> {
105 match self {
106 Self::Git(git_source) => clone_local(git_source).await,
107 Self::File(path) => check_local(path).await,
108 Self::RemoteTar(url) => download_untar_local(url).await,
109 }
110 }
111
112 pub(crate) fn requires_copy(&self) -> bool {
113 match self {
114 Self::Git { .. } => true,
115 Self::File(_) => false,
116 Self::RemoteTar(_) => true,
117 }
118 }
119}
120
121impl LocalTemplateSource {
122 pub async fn template_directories(&self) -> anyhow::Result<Vec<PathBuf>> {
123 let templates_root = self.root.join(TEMPLATE_SOURCE_DIR);
124 if templates_root.exists() {
125 subdirectories(&templates_root).with_context(|| {
126 format!("Failed to read contents of '{TEMPLATE_SOURCE_DIR}' directory")
127 })
128 } else {
129 Err(anyhow!(
130 "Template source {} does not contain a '{}' directory",
131 self.root.display(),
132 TEMPLATE_SOURCE_DIR
133 ))
134 }
135 }
136}
137
138async fn clone_local(git_source: &GitTemplateSource) -> anyhow::Result<LocalTemplateSource> {
139 let temp_dir = tempdir()?;
140 let path = temp_dir.path().to_owned();
141
142 let url_str = git_source.url.as_str();
143
144 let actual_branch = match &git_source.branch {
145 Some(b) => Some(b.clone()),
146 None => version_matched_tag(url_str, &git_source.spin_version).await,
147 };
148
149 let mut git = Command::new("git");
150 git.arg("clone");
151 git.arg("--depth").arg("1");
152
153 if let Some(b) = actual_branch {
154 git.arg("--branch").arg(b);
155 }
156
157 git.arg(url_str).arg(&path);
158
159 let clone_result = git.output().await.understand_git_result();
160 match clone_result {
161 Ok(_) => Ok(LocalTemplateSource {
162 root: path,
163 _temp_dir: Some(temp_dir),
164 }),
165 Err(e) => Err(anyhow!("Error cloning Git repo {}: {}", url_str, e)),
166 }
167}
168
169async fn version_matched_tag(url: &str, spin_version: &str) -> Option<String> {
170 let preferred_tag = version_preferred_tag(spin_version);
171
172 let mut git = Command::new("git");
173 git.arg("ls-remote");
174 git.arg("--exit-code");
175 git.arg(url);
176 git.arg(&preferred_tag);
177
178 match git.output().await.understand_git_result() {
179 Ok(_) => Some(preferred_tag),
180 Err(_) => None,
181 }
182}
183
184fn version_preferred_tag(text: &str) -> String {
185 let mm_version = match semver::Version::parse(text) {
186 Ok(version) => format!("{}.{}", version.major, version.minor),
187 Err(_) => text.to_owned(),
188 };
189 format!("{TEMPLATE_VERSION_TAG_PREFIX}{mm_version}")
190}
191
192async fn check_local(path: &Path) -> anyhow::Result<LocalTemplateSource> {
193 if path.exists() {
194 Ok(LocalTemplateSource {
195 root: path.to_owned(),
196 _temp_dir: None,
197 })
198 } else {
199 Err(anyhow!("Path not found: {}", path.display()))
200 }
201}
202
203async fn download_untar_local(url: &Url) -> anyhow::Result<LocalTemplateSource> {
205 use bytes::buf::Buf;
206
207 let temp_dir = tempdir()?;
208 let path = temp_dir.path().to_owned();
209
210 let resp = reqwest::get(url.clone())
211 .await
212 .with_context(|| format!("Failed to download from {url}"))?;
213 let tar_content = resp
214 .bytes()
215 .await
216 .with_context(|| format!("Failed to download from {url}"))?;
217
218 let reader = flate2::read::GzDecoder::new(tar_content.reader());
219 let mut archive = tar::Archive::new(reader);
220 archive
221 .unpack(&path)
222 .context("Failed to unpack tar archive")?;
223
224 let templates_root = bypass_gh_added_root(path);
225
226 Ok(LocalTemplateSource {
227 root: templates_root,
228 _temp_dir: Some(temp_dir),
229 })
230}
231
232fn bypass_gh_added_root(unpack_dir: PathBuf) -> PathBuf {
235 if has_templates_dir(&unpack_dir) {
237 return unpack_dir;
238 }
239
240 let Ok(dirs) = unpack_dir.read_dir() else {
241 return unpack_dir;
244 };
245
246 let dirs = dirs.filter_map(|de| de.ok()).take(2).collect::<Vec<_>>();
250 if dirs.len() != 1 {
251 return unpack_dir;
252 }
253
254 let candidate_repo_root = dirs[0].path();
256 let Ok(mut candidate_repo_dirs) = candidate_repo_root.read_dir() else {
257 return unpack_dir;
259 };
260 let has_templates_dir = candidate_repo_dirs.any(is_templates_dir);
261
262 if has_templates_dir {
263 candidate_repo_root
264 } else {
265 unpack_dir
266 }
267}
268
269fn has_templates_dir(path: &Path) -> bool {
270 let Ok(mut dirs) = path.read_dir() else {
271 return false;
272 };
273
274 dirs.any(is_templates_dir)
275}
276
277fn is_templates_dir(dir_entry: Result<std::fs::DirEntry, std::io::Error>) -> bool {
278 dir_entry.is_ok_and(|d| d.file_name() == TEMPLATE_SOURCE_DIR)
279}
280
281#[cfg(test)]
282mod test {
283 use super::*;
284
285 #[test]
286 fn preferred_tag_excludes_patch_version() {
287 assert_eq!("spin/templates/v1.2", version_preferred_tag("1.2.3"));
288 }
289
290 #[test]
291 fn preferred_tag_excludes_prerelease_and_build() {
292 assert_eq!(
293 "spin/templates/v1.2",
294 version_preferred_tag("1.2.3-preview.1")
295 );
296 assert_eq!(
297 "spin/templates/v1.2",
298 version_preferred_tag("1.2.3+build.0f74628")
299 );
300 assert_eq!(
301 "spin/templates/v1.2",
302 version_preferred_tag("1.2.3-alpha+0f74628")
303 );
304 }
305
306 #[test]
307 fn preferred_tag_defaults_sensibly_on_bad_semver() {
308 assert_eq!("spin/templates/v1.2", version_preferred_tag("1.2"));
309 assert_eq!("spin/templates/v1.2.3.4", version_preferred_tag("1.2.3.4"));
310 assert_eq!("spin/templates/vgarbage", version_preferred_tag("garbage"));
311 }
312}