Skip to main content

lux_lib/rockspec/toml/
gen.rs

1use crate::package;
2use std::{
3    path::{Path, PathBuf},
4    str::FromStr,
5};
6
7use crate::{
8    rockspec,
9    variables::{self, Environment, GetVariableError, HasVariables},
10};
11use ::serde::Deserialize;
12use git2::Repository;
13use miette::Diagnostic;
14use serde::Serialize;
15use thiserror::Error;
16
17#[derive(Debug, PartialEq, Deserialize, Serialize, Clone, Default)]
18#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
19/// Template for generating a remote rockspec source
20///
21/// Variables that can be substituted in each of the fields:
22/// - `$(PACKAGE)`: Package name
23/// - `$(VERSION)`: Package version
24/// - `$(REF)`: Git tag or revision (prioritising tags if present)
25///
26/// Fields can also be substituted with environment variables.
27pub(crate) struct RockSourceTemplate {
28    /// URL template for `SemVer` releases
29    url: Option<String>,
30
31    /// URL template for `DevVer` releases
32    dev: Option<String>,
33
34    /// File name of the source archive.
35    /// Can be omitted if it can be inferred from the generated URL.
36    file: Option<PathBuf>,
37
38    /// Name of the directory created when the source archive is unpacked.
39    /// Can be omitted if it can be inferred from the `file` field.
40    dir: Option<PathBuf>,
41
42    /// The tag or revision to be checked out if the source URL is a git source.
43    /// If unset, Lux will try to auto-detect it.
44    tag: Option<String>,
45
46    /// The branch to be checked out if the source URL is a git source.
47    branch: Option<String>,
48}
49
50#[derive(Debug, Error, Diagnostic)]
51pub enum GenerateSourceError {
52    #[error(
53        "unsupported version {0}.\nCan only generate source for SemVer versions, 'dev' or 'scm'."
54    )]
55    StringVer(String),
56    #[error("need a `source.url` (release URL) in lux.toml for SemVer versions.")]
57    MissingReleaseUrl(String),
58    #[error("need a `source.dev` (dev/scm URL) in lux.toml for dev versions.")]
59    MissingDevUrl(String),
60    #[error("error substituting project source variables")]
61    #[diagnostic(forward(0))]
62    VariableSubstitution(#[from] variables::Error),
63    #[error("error parsing source URL from template")]
64    #[diagnostic(forward(0))]
65    SourceUrl(#[from] rockspec::source::UrlError),
66    #[error("error generating git source URL")]
67    Git(#[from] git2::Error),
68    #[error("refusing to generate nondeterministic rockspec with git source.\nSupply a `source.tag` parameter.")]
69    NonDeterministicGitSource,
70}
71
72/// Helper for substituting git variables from a git project
73#[derive(Debug)]
74struct GitProject<'a>(&'a Path);
75
76impl HasVariables for GitProject<'_> {
77    #[tracing::instrument(level = "trace")]
78    fn get_variable(&self, input: &str) -> Result<Option<String>, GetVariableError> {
79        Ok(match input {
80            "REF" => {
81                let repo = find_git_repo(self.0).map_err(GetVariableError::new)?;
82                Some(current_tag_or_revision(&repo).map_err(GetVariableError::new)?)
83            }
84            _ => None,
85        })
86    }
87}
88
89fn find_git_repo(path: impl AsRef<Path>) -> Result<Repository, git2::Error> {
90    let mut path: PathBuf = path.as_ref().to_path_buf();
91    loop {
92        match Repository::open(&path) {
93            Ok(repo) => return Ok(repo),
94            Err(err) => {
95                if !path.pop() {
96                    return Err(err);
97                }
98            }
99        }
100    }
101}
102
103impl RockSourceTemplate {
104    pub(crate) fn try_generate(
105        &self,
106        project_root: &Path,
107        package: &package::Name,
108        version: &package::Version,
109    ) -> Result<rockspec::source::internal::Spec, GenerateSourceError> {
110        let package_spec = package::Spec::new(package.clone(), version.clone());
111        let url_template_str = match version {
112            package::Version::SemVer(ver) => self
113                .url
114                .as_ref()
115                .ok_or(GenerateSourceError::MissingReleaseUrl(ver.to_string())),
116            package::Version::DevVer(ver) => self
117                .dev
118                .as_ref()
119                .ok_or(GenerateSourceError::MissingDevUrl(ver.to_string())),
120            package::Version::StringVer(ver) => {
121                Err(GenerateSourceError::StringVer(ver.to_string()))
122            }
123        }?;
124        let url_str = variables::substitute(
125            &[&package_spec, &Environment {}, &GitProject(project_root)],
126            url_template_str,
127        )?;
128        let dir = match self.dir.as_ref() {
129            Some(dir) => Some(
130                variables::substitute(
131                    &[&package_spec, &Environment {}, &GitProject(project_root)],
132                    &dir.to_string_lossy(),
133                )?
134                .into(),
135            ),
136            None => None,
137        };
138        let file = match self.file.as_ref() {
139            Some(file) => Some(
140                variables::substitute(
141                    &[&package_spec, &Environment {}, &GitProject(project_root)],
142                    &file.to_string_lossy(),
143                )?
144                .into(),
145            ),
146            None => None,
147        };
148        let tag = match self.tag.as_ref() {
149            Some(tag) => Some(variables::substitute(
150                &[&package_spec, &Environment {}, &GitProject(project_root)],
151                tag,
152            )?),
153            None => None,
154        };
155        let branch = match self.branch.as_ref() {
156            Some(branch) => Some(variables::substitute(
157                &[&package_spec, &Environment {}, &GitProject(project_root)],
158                branch,
159            )?),
160            None => None,
161        };
162        match rockspec::source::internal::SourceUrl::from_str(&url_str)? {
163            rockspec::source::internal::SourceUrl::File(_)
164            | rockspec::source::internal::SourceUrl::Url(_) => {
165                Ok(rockspec::source::internal::Spec {
166                    url: Some(url_str.to_string()),
167                    file,
168                    dir,
169                    branch,
170                    tag,
171                })
172            }
173            rockspec::source::internal::SourceUrl::Git(_)
174                if self.tag.is_none() && self.branch.is_none() =>
175            {
176                if let Ok(repo) = find_git_repo(project_root) {
177                    let tag_or_rev = current_tag_or_revision(&repo)?;
178                    Ok(rockspec::source::internal::Spec {
179                        url: Some(url_str.to_string()),
180                        tag: Some(tag_or_rev),
181                        file,
182                        dir,
183                        branch: None,
184                    })
185                } else {
186                    Err(GenerateSourceError::NonDeterministicGitSource)
187                }
188            }
189            rockspec::source::internal::SourceUrl::Git(_) => Ok(rockspec::source::internal::Spec {
190                url: Some(url_str.to_string()),
191                file,
192                dir,
193                tag,
194                branch,
195            }),
196        }
197    }
198}
199
200#[derive(Debug, PartialEq, Deserialize, Serialize, Clone, Default)]
201pub(crate) struct PackageVersionTemplate(Option<package::Version>);
202
203#[derive(Debug, Error, Diagnostic)]
204pub enum GenerateVersionError {
205    #[error("error generating version from git repository metadata")]
206    Git(#[from] git2::Error),
207    #[error("error parsing version from git ref")]
208    #[diagnostic(forward(0))]
209    PackageVersionParse(#[from] package::version::Error),
210}
211
212impl PackageVersionTemplate {
213    pub(crate) fn try_generate(
214        &self,
215        project_root: &Path,
216        specrev: Option<package::version::SpecRev>,
217    ) -> Result<package::Version, GenerateVersionError> {
218        if let Some(version) = &self.0 {
219            return Ok(specrev.map_or_else(
220                || version.clone(),
221                |specrev| version.clone().with_specrev(specrev),
222            ));
223        }
224        let specrev = specrev.unwrap_or_default();
225        let repo = find_git_repo(project_root)?;
226        if let Some(version) = version_from_semver_tag(&repo, &specrev)? {
227            Ok(version)
228        } else {
229            Ok(package::Version::default_dev_version_with_specrev(specrev))
230        }
231    }
232}
233
234/// Searches the current HEAD for SemVer tags and returns the first one found.
235fn version_from_semver_tag(
236    repo: &Repository,
237    specrev: &package::version::SpecRev,
238) -> Result<Option<package::Version>, git2::Error> {
239    let head = repo.head()?;
240    let current_rev = head
241        .target()
242        .ok_or_else(|| git2::Error::from_str("No HEAD target"))?;
243    let mut result = None;
244    repo.tag_foreach(|oid, name| {
245        let name = std::str::from_utf8(name).ok().map(|x| x.to_string());
246        let target = find_commit_id(repo, oid);
247        if let (Some(tag_name), Some(target_rev)) = (name, target) {
248            let tag_name = tag_name.trim_start_matches("refs/tags/");
249            if target_rev == current_rev {
250                let tag_name = tag_name.trim_start_matches("v");
251                let version_str = format!("{}-{specrev}", tag_name);
252                if let Ok(version @ package::Version::SemVer(_)) =
253                    package::Version::parse(&version_str)
254                {
255                    result = Some(version);
256                    return false; // stop iteration
257                }
258            }
259        }
260        true // continue iteration
261    })?;
262    Ok(result)
263}
264
265/// Searches the current HEAD for a tag, and if found, returns it.
266/// Prioritises SemVer tags.
267/// Returns the HEAD's commit SHA if no tag is found.
268fn current_tag_or_revision(repo: &Repository) -> Result<String, git2::Error> {
269    let head = repo.head()?;
270    let current_rev = head
271        .target()
272        .ok_or_else(|| git2::Error::from_str("No HEAD target"))?;
273    let mut semver_tag = None;
274    let mut fallback_tag = None;
275    repo.tag_foreach(|oid, name| {
276        let name = std::str::from_utf8(name).ok().map(|x| x.to_string());
277        let target = find_commit_id(repo, oid);
278        if let (Some(tag_name), Some(target_rev)) = (name, target) {
279            let tag_name = tag_name.trim_start_matches("refs/tags/");
280            if target_rev == current_rev {
281                if package::Version::parse(tag_name.trim_start_matches("v"))
282                    .is_ok_and(|version| version.is_semver())
283                {
284                    semver_tag = Some(tag_name.to_string());
285                    return false; // stop iteration
286                }
287                fallback_tag = Some(tag_name.to_string());
288            }
289        }
290        true // continue iteration
291    })?;
292    Ok(semver_tag
293        .or(fallback_tag)
294        .unwrap_or(current_rev.to_string()))
295}
296
297fn find_commit_id(repo: &Repository, tag_or_commit_oid: git2::Oid) -> Option<git2::Oid> {
298    // HACK: The Oids passed to git2's tag_foreach callback apparently aren't always tag Oids
299    repo.find_tag(tag_or_commit_oid)
300        .map(|tag| tag.target_id())
301        .or_else(|_| {
302            repo.find_commit(tag_or_commit_oid)
303                .map(|_| tag_or_commit_oid)
304        })
305        .ok()
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    #[test]
313    fn explicit_version_uses_requested_specrev() {
314        for (version, specrev, expected) in [("0.0.3", 3u16, "0.0.3-3"), ("1", 2, "1-2")] {
315            let template = PackageVersionTemplate(Some(package::Version::parse(version).unwrap()));
316            let generated = template
317                .try_generate(Path::new("."), Some(specrev.into()))
318                .unwrap();
319            assert_eq!(generated.to_string(), expected);
320        }
321    }
322}