Skip to main content

lux_lib/tree/
mod.rs

1use crate::package;
2use crate::{
3    config::Config,
4    fs,
5    lockfile::{self, LockedPackage, LockedPackageId, LockedPackageSpec, Lockfile, ReadOnly},
6    lua, path,
7    variables::{GetVariableError, HasVariables},
8};
9use std::{collections::HashMap, io, path::PathBuf, sync::Arc};
10
11use itertools::Itertools;
12use miette::Diagnostic;
13use nonempty::NonEmpty;
14use thiserror::Error;
15mod dist;
16mod layout;
17mod list;
18
19pub use dist::*;
20pub use layout::*;
21
22const LOCKFILE_NAME: &str = "lux.lock";
23
24/// A tree is a collection of files where installed rocks are located.
25///
26/// `lux` diverges from the traditional hierarchy employed by luarocks.
27/// Instead, we opt for a much simpler approach:
28///
29/// - /rocks/<lua-version> - contains rocks
30/// - /rocks/<lua-version>/<rock>/etc - documentation and supplementary files for the rock
31/// - /rocks/<lua-version>/<rock>/lib - shared libraries (.so files)
32/// - /rocks/<lua-version>/<rock>/src - library code for the rock
33/// - /bin - binary files produced by various rocks
34pub trait InstallTree {
35    /// The Lua version for which to install packages.
36    fn version(&self) -> &lua::Version;
37    /// The root directory of the tree
38    fn root(&self) -> PathBuf;
39    /// Where wrapped package binaries are installed
40    fn bin(&self) -> PathBuf;
41    /// Where unwrapped package binaries are installed
42    fn unwrapped_bin(&self) -> PathBuf;
43    /// The standard install layout for a package.
44    fn layout_for(&self, package: &LockedPackageSpec) -> RockLayout;
45    /// Create a [`Lockfile`] for this tree.
46    fn lockfile(&self) -> Result<Lockfile<ReadOnly>, Error>;
47    /// Get this tree's lockfile path.
48    fn lockfile_path(&self) -> PathBuf;
49    /// The tree in which to install build dependencies.
50    fn build_tree(&self, config: &Config) -> Result<Tree, Error>;
51    /// The tree in which to install test dependencies.
52    fn test_tree(&self, config: &Config) -> Result<Tree, Error>;
53    /// List the packages that are installed in this tree.
54    fn list(&self) -> Result<HashMap<package::Name, Vec<LockedPackage>>, Error>;
55    /// Find installed rocks that match the given [`package::Req`].
56    fn match_rocks(&self, req: &package::Req) -> Result<RockMatches, Error>;
57    /// Create the standard directories (src, lib, etc.) for a package.
58    fn prepare(&self, package: &LockedPackageSpec) -> Result<(), Error>;
59    /// Apply the custom layout once a package has been fully installed.
60    ///
61    /// For entrypoints, this creates the symlinks for the custom layout, if one is configured.
62    /// Must be called after the package's files have been written to the standard layout.
63    fn finalize(&self, _package: &LockedPackage, _entry_type: EntryType) -> Result<(), Error> {
64        Ok(())
65    }
66    /// Remove the install layout directories.
67    ///
68    /// For entrypoints, this also applies the custom layout, if one is configured.
69    fn cleanup(&self, package: &LockedPackage, entry_type: EntryType) -> Result<(), Error>;
70}
71
72/// The standard install layout for a rock.
73#[derive(Debug, PartialEq, Eq, Clone)]
74pub struct RockLayout {
75    /// The local installation directory.
76    /// Can be substituted in a rockspec's `build.build_variables` and `build.install_variables`
77    /// using `$(PREFIX)`.
78    pub root: PathBuf,
79    /// The `etc` directory, containing resources.
80    pub etc: PathBuf,
81    /// The `lib` directory, containing native libraries.
82    /// Can be substituted in a rockspec's `build.build_variables` and `build.install_variables`
83    /// using `$(LIBDIR)`.
84    pub lib: PathBuf,
85    /// The `src` directory, containing Lua sources.
86    /// Can be substituted in a rockspec's `build.build_variables` and `build.install_variables`
87    /// using `$(LUADIR)`.
88    pub src: PathBuf,
89    /// The `bin` directory, containing executables.
90    /// Can be substituted in a rockspec's `build.build_variables` and `build.install_variables`
91    /// using `$(BINDIR)`.
92    /// This points to a global binary path at the root of the current tree by default.
93    pub bin: PathBuf,
94    /// The `etc/conf` directory, containing configuration files.
95    /// Can be substituted in a rockspec's `build.build_variables` and `build.install_variables`
96    /// using `$(CONFDIR)`.
97    pub conf: PathBuf,
98    /// The `etc/doc` directory, containing documentation files.
99    /// Can be substituted in a rockspec's `build.build_variables` and `build.install_variables`
100    /// using `$(DOCDIR)`.
101    pub doc: PathBuf,
102}
103
104impl RockLayout {
105    /// Create the standard install layout rooted at `root`, with binaries in `bin`.
106    pub fn new(root: PathBuf, bin: PathBuf) -> Self {
107        let etc = root.join("etc");
108        let lib = root.join("lib");
109        let src = root.join("src");
110        let conf = etc.join("conf");
111        let doc = etc.join("doc");
112        Self {
113            root,
114            etc,
115            lib,
116            src,
117            bin,
118            conf,
119            doc,
120        }
121    }
122
123    /// The path to the package's stored rockspec.
124    pub fn rockspec_path(&self) -> PathBuf {
125        self.root.join("package.rockspec")
126    }
127}
128
129/// A Lux install tree that supports multiple versions of the same dependency,
130/// with packages addressed by their [`LockedPackageId`]
131#[derive(Clone, Debug)]
132pub struct Tree {
133    /// The Lua version of the tree.
134    version: lua::Version,
135    /// The parent of this tree's root directory.
136    root_parent: PathBuf,
137    /// The root of this tree's test dependency tree.
138    test_tree_dir: PathBuf,
139    /// The root of this tree's build dependency tree.
140    build_tree_dir: PathBuf,
141    /// The custom layout to apply to entrypoint packages, if any.
142    entrypoint_layout: Option<Arc<dyn CustomRockLayout>>,
143}
144
145#[derive(Debug, Error, Diagnostic)]
146pub enum Error {
147    #[error(transparent)]
148    #[diagnostic(transparent)]
149    Fs(#[from] fs::Error),
150    #[error(transparent)]
151    #[diagnostic(transparent)]
152    Lockfile(#[from] lockfile::Error),
153    #[error(transparent)]
154    Io(#[from] io::Error),
155}
156
157impl HasVariables for RockLayout {
158    fn get_variable(&self, var: &str) -> Result<Option<String>, GetVariableError> {
159        Ok(match var {
160            "PREFIX" => Some(path::quoted(&self.root)),
161            "LIBDIR" => Some(path::quoted(&self.lib)),
162            "LUADIR" => Some(path::quoted(&self.src)),
163            "BINDIR" => Some(path::quoted(&self.bin)),
164            "CONFDIR" => Some(path::quoted(&self.conf)),
165            "DOCDIR" => Some(path::quoted(&self.doc)),
166            _ => None,
167        })
168    }
169}
170
171impl Tree {
172    /// NOTE: This is exposed for use by the config module.
173    /// Use `Config::tree()`
174    pub(crate) fn new(
175        root: PathBuf,
176        version: lua::Version,
177        config: &Config,
178    ) -> Result<Self, Error> {
179        let version_dir = root.join(version.to_string());
180        let test_tree_dir = version_dir.join("test_dependencies");
181        let build_tree_dir = version_dir.join("build_dependencies");
182        Self::new_with_paths(root, test_tree_dir, build_tree_dir, version, config)
183    }
184
185    fn new_with_paths(
186        root: PathBuf,
187        test_tree_dir: PathBuf,
188        build_tree_dir: PathBuf,
189        version: lua::Version,
190        config: &Config,
191    ) -> Result<Self, Error> {
192        let path_with_version = root.join(version.to_string());
193
194        // Ensure that the root and the version directory exist.
195        fs::sync::create_dir_all(&path_with_version)?;
196
197        // In case the tree is in a git repository, we tell git to ignore it.
198        let gitignore_file = root.join(".gitignore");
199        fs::sync::write(&gitignore_file, "*")?;
200
201        // Ensure that the bin directory exists.
202        let bin_dir = path_with_version.join("bin");
203        fs::sync::create_dir_all(&bin_dir)?;
204
205        Ok(Self {
206            root_parent: root,
207            version,
208            test_tree_dir,
209            build_tree_dir,
210            entrypoint_layout: config.entrypoint_layout().cloned(),
211        })
212    }
213
214    pub fn match_rocks_and<F>(&self, req: &package::Req, filter: F) -> Result<RockMatches, Error>
215    where
216        F: Fn(&LockedPackage) -> bool,
217    {
218        match self.list()?.get(req.name()) {
219            Some(packages) => {
220                let found_packages = packages
221                    .iter()
222                    .rev()
223                    .filter(|package| {
224                        req.version_req().matches(package.version()) && filter(package)
225                    })
226                    .map(|package| package.id())
227                    .collect_vec();
228
229                Ok(match NonEmpty::try_from(found_packages) {
230                    Ok(found_packages) => {
231                        if found_packages.len() == 1 {
232                            RockMatches::Single(found_packages.last().clone())
233                        } else {
234                            RockMatches::Many(found_packages)
235                        }
236                    }
237                    Err(_) => RockMatches::NotFound(req.clone()),
238                })
239            }
240            None => Ok(RockMatches::NotFound(req.clone())),
241        }
242    }
243}
244
245impl InstallTree for Tree {
246    fn version(&self) -> &lua::Version {
247        &self.version
248    }
249
250    fn root(&self) -> PathBuf {
251        self.root_parent.join(self.version.to_string())
252    }
253
254    fn prepare(&self, package: &LockedPackageSpec) -> Result<(), Error> {
255        let layout = self.layout_for(package);
256        fs::sync::create_dir_all(&layout.root)?;
257        fs::sync::create_dir_all(&layout.lib)?;
258        fs::sync::create_dir_all(&layout.src)?;
259        fs::sync::create_dir_all(&layout.etc)?;
260
261        Ok(())
262    }
263
264    fn finalize(&self, package: &LockedPackage, entry_type: EntryType) -> Result<(), Error> {
265        if let Some(custom_layout) = &self.entrypoint_layout {
266            if entry_type.is_entrypoint() || custom_layout.layout_dependencies() {
267                custom_layout.apply_layout(self, &package.spec)?;
268            }
269        }
270
271        Ok(())
272    }
273
274    fn cleanup(&self, package: &LockedPackage, entry_type: EntryType) -> Result<(), Error> {
275        if let Some(layout) = &self.entrypoint_layout {
276            if entry_type.is_entrypoint() || layout.layout_dependencies() {
277                layout.remove_layout(self, &package.spec)?;
278            }
279        }
280
281        let layout = self.layout_for(&package.spec);
282        fs::sync::remove_dir_all(&layout.etc)?;
283        fs::sync::remove_dir_all(&layout.root)?;
284
285        let lockfile = self.lockfile()?;
286        for relative_binary_path in lockfile
287            .binaries(&package.id())
288            .into_iter()
289            .flat_map(|binaries| binaries.iter())
290        {
291            if let Some(binary_file_name) = relative_binary_path.file_name() {
292                let binary_path = self.bin().join(binary_file_name);
293                if binary_path.is_file() {
294                    fs::sync::remove_file(binary_path)?;
295                }
296
297                let unwrapped_binary_path = self.unwrapped_bin().join(binary_file_name);
298                if unwrapped_binary_path.is_file() {
299                    fs::sync::remove_file(unwrapped_binary_path)?;
300                }
301            }
302        }
303
304        Ok(())
305    }
306
307    fn lockfile(&self) -> Result<Lockfile<ReadOnly>, Error> {
308        Ok(Lockfile::new(self.lockfile_path())?)
309    }
310
311    fn lockfile_path(&self) -> PathBuf {
312        self.root().join(LOCKFILE_NAME)
313    }
314
315    fn layout_for(&self, package: &LockedPackageSpec) -> RockLayout {
316        RockLayout::new(
317            self.root().join(format!(
318                "{}-{}@{}",
319                package.id(),
320                package.name(),
321                package.version()
322            )),
323            self.bin(),
324        )
325    }
326
327    fn bin(&self) -> PathBuf {
328        self.root().join("bin")
329    }
330
331    fn unwrapped_bin(&self) -> PathBuf {
332        self.bin().join("unwrapped")
333    }
334
335    fn test_tree(&self, config: &Config) -> Result<Self, Error> {
336        let test_tree_dir = self.test_tree_dir.clone();
337        let build_tree_dir = self.build_tree_dir.clone();
338        Self::new_with_paths(
339            test_tree_dir.clone(),
340            test_tree_dir,
341            build_tree_dir,
342            self.version.clone(),
343            config,
344        )
345    }
346
347    fn build_tree(&self, config: &Config) -> Result<Self, Error> {
348        let test_tree_dir = self.test_tree_dir.clone();
349        let build_tree_dir = self.build_tree_dir.clone();
350        Self::new_with_paths(
351            build_tree_dir.clone(),
352            test_tree_dir,
353            build_tree_dir,
354            self.version.clone(),
355            config,
356        )
357    }
358
359    fn list(&self) -> Result<HashMap<package::Name, Vec<LockedPackage>>, Error> {
360        Ok(self.lockfile()?.list())
361    }
362
363    fn match_rocks(&self, req: &package::Req) -> Result<RockMatches, Error> {
364        let found_packages = self.lockfile()?.find_rocks(req);
365        Ok(match NonEmpty::try_from(found_packages) {
366            Ok(found_packages) => {
367                if found_packages.len() == 1 {
368                    RockMatches::Single(found_packages.last().clone())
369                } else {
370                    RockMatches::Many(found_packages)
371                }
372            }
373            Err(_) => RockMatches::NotFound(req.clone()),
374        })
375    }
376}
377
378#[derive(Copy, Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord)]
379pub enum EntryType {
380    Entrypoint,
381    DependencyOnly,
382}
383
384impl EntryType {
385    pub fn is_entrypoint(&self) -> bool {
386        matches!(self, Self::Entrypoint)
387    }
388}
389
390#[derive(Clone, Debug)]
391pub enum RockMatches {
392    NotFound(package::Req),
393    Single(LockedPackageId),
394    Many(NonEmpty<LockedPackageId>),
395}
396
397// Loosely mimic the Option<T> functions.
398impl RockMatches {
399    pub fn is_found(&self) -> bool {
400        matches!(self, Self::Single(_) | Self::Many(_))
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use assert_fs::prelude::PathCopy;
407    use itertools::Itertools;
408    use std::path::PathBuf;
409
410    use crate::package;
411    use crate::remote;
412
413    use insta::assert_yaml_snapshot;
414
415    use crate::{
416        config,
417        lockfile::{self, LockedPackage, LockedPackageHashes},
418        lua,
419        tree::{InstallTree, RockLayout},
420        variables,
421    };
422
423    #[test]
424    fn rock_layout() {
425        let tree_path =
426            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree");
427
428        let temp = assert_fs::TempDir::new().unwrap();
429        temp.copy_from(&tree_path, &["**"]).unwrap();
430        let tree_path = temp.to_path_buf();
431
432        let config = config::Builder::new()
433            .unwrap()
434            .user_tree(Some(tree_path.clone()))
435            .build()
436            .unwrap();
437        let tree = config.user_tree(lua::Version::Lua51).unwrap();
438
439        let mock_hashes = LockedPackageHashes {
440            rockspec: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
441                .parse()
442                .unwrap(),
443            source: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
444                .parse()
445                .unwrap(),
446        };
447
448        let package = LockedPackage::from(
449            &package::Spec::parse("neorg".into(), "8.0.0-1".into()).unwrap(),
450            lockfile::Constraint::Unconstrained,
451            remote::package::Source::Test,
452            None,
453            mock_hashes.clone(),
454        );
455
456        let id = package.id();
457        tree.prepare(&package.spec).unwrap();
458
459        assert_eq!(
460            tree.layout_for(&package.spec),
461            RockLayout {
462                bin: tree_path.join("5.1/bin"),
463                root: tree_path.join(format!("5.1/{id}-neorg@8.0.0-1")),
464                etc: tree_path.join(format!("5.1/{id}-neorg@8.0.0-1/etc")),
465                lib: tree_path.join(format!("5.1/{id}-neorg@8.0.0-1/lib")),
466                src: tree_path.join(format!("5.1/{id}-neorg@8.0.0-1/src")),
467                conf: tree_path.join(format!("5.1/{id}-neorg@8.0.0-1/etc/conf")),
468                doc: tree_path.join(format!("5.1/{id}-neorg@8.0.0-1/etc/doc")),
469            }
470        );
471    }
472
473    #[test]
474    fn tree_list() {
475        let tree_path =
476            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree");
477
478        let temp = assert_fs::TempDir::new().unwrap();
479        temp.copy_from(&tree_path, &["**"]).unwrap();
480        let tree_path = temp.to_path_buf();
481
482        let config = config::Builder::new()
483            .unwrap()
484            .user_tree(Some(tree_path.clone()))
485            .build()
486            .unwrap();
487        let tree = config.user_tree(lua::Version::Lua51).unwrap();
488        let result = tree.list().unwrap();
489        // note: sorted_redaction doesn't work because we have a nested Vec
490        let sorted_result: Vec<(package::Name, Vec<package::Version>)> = result
491            .into_iter()
492            .sorted()
493            .map(|(name, package)| {
494                (
495                    name,
496                    package
497                        .into_iter()
498                        .map(|package| package.version().clone())
499                        .sorted()
500                        .collect_vec(),
501                )
502            })
503            .collect_vec();
504
505        assert_yaml_snapshot!(sorted_result)
506    }
507
508    #[test]
509    fn rock_layout_substitute() {
510        let tree_path =
511            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree");
512
513        let temp = assert_fs::TempDir::new().unwrap();
514        temp.copy_from(&tree_path, &["**"]).unwrap();
515        let tree_path = temp.to_path_buf();
516
517        let config = config::Builder::new()
518            .unwrap()
519            .user_tree(Some(tree_path.clone()))
520            .build()
521            .unwrap();
522        let tree = config.user_tree(lua::Version::Lua51).unwrap();
523
524        let mock_hashes = LockedPackageHashes {
525            rockspec: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
526                .parse()
527                .unwrap(),
528            source: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
529                .parse()
530                .unwrap(),
531        };
532
533        let package = LockedPackage::from(
534            &package::Spec::parse("neorg".into(), "8.0.0-1-1".into()).unwrap(),
535            lockfile::Constraint::Unconstrained,
536            remote::package::Source::Test,
537            None,
538            mock_hashes.clone(),
539        );
540        let layout = tree.layout_for(&package.spec);
541        let build_variables = vec![
542            "$(PREFIX)",
543            "$(LIBDIR)",
544            "$(LUADIR)",
545            "$(BINDIR)",
546            "$(CONFDIR)",
547            "$(DOCDIR)",
548        ];
549        let result: Vec<String> = build_variables
550            .into_iter()
551            .map(|var| variables::substitute(&[&layout], var))
552            .try_collect()
553            .unwrap();
554        assert_eq!(
555            result,
556            vec![
557                layout.root.to_string_lossy().to_string(),
558                layout.lib.to_string_lossy().to_string(),
559                layout.src.to_string_lossy().to_string(),
560                layout.bin.to_string_lossy().to_string(),
561                layout.conf.to_string_lossy().to_string(),
562                layout.doc.to_string_lossy().to_string(),
563            ]
564        );
565    }
566}