Skip to main content

lux_lib/tree/
mod.rs

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