Skip to main content

lux_lib/luarocks/
install_binary_rock.rs

1use crate::lockfile::locked_package;
2use std::io::{self, Cursor};
3
4use crate::remote;
5use crate::{
6    build::{
7        self,
8        external_dependency::{self, ExternalDependencyInfo},
9    },
10    config::Config,
11    hash::HasIntegrity,
12    lockfile::{self, LockedPackage},
13    rockspec,
14    rockspec::Rockspec,
15    tree::{self, InstallTree},
16};
17use crate::{fs, lockfile::RemotePackageSourceUrl, rockspec::LuaVersionCompatibility};
18use bytes::Bytes;
19use miette::Diagnostic;
20use thiserror::Error;
21
22use super::{install_rock_manifest, RockManifestSources};
23
24#[derive(Error, Debug, Diagnostic)]
25#[non_exhaustive]
26pub enum Error {
27    #[error("IO operation failed")]
28    Io(#[from] io::Error),
29    #[error(transparent)]
30    #[diagnostic(transparent)]
31    Fs(#[from] fs::Error),
32    #[error(transparent)]
33    #[diagnostic(transparent)]
34    Lockfile(#[from] lockfile::Error),
35    #[error(transparent)]
36    #[diagnostic(transparent)]
37    Tree(#[from] tree::Error),
38    #[error(transparent)]
39    #[diagnostic(transparent)]
40    ExternalSpec(#[from] external_dependency::Error),
41    #[error(transparent)]
42    #[diagnostic(transparent)]
43    LuaVersion(#[from] rockspec::Error),
44    #[error("failed to unpack packed rock")]
45    Zip(#[from] zip::result::ZipError),
46    #[error(transparent)]
47    #[diagnostic(transparent)]
48    InstallRockManifest(#[from] super::Error),
49}
50
51pub(crate) struct BinaryRockInstall<'a, T>
52where
53    T: InstallTree,
54{
55    rockspec: &'a rockspec::lua::Remote,
56    spec: locked_package::Spec,
57    rock_bytes: Bytes,
58    source: remote::package::Source,
59    entry_type: tree::EntryType,
60    behaviour: build::Behaviour,
61    config: &'a Config,
62    tree: &'a T,
63}
64
65impl<'a, T> BinaryRockInstall<'a, T>
66where
67    T: InstallTree,
68{
69    pub(crate) fn new(
70        rockspec: &'a rockspec::lua::Remote,
71        spec: locked_package::Spec,
72        rock_bytes: Bytes,
73        source: remote::package::Source,
74        entry_type: tree::EntryType,
75        config: &'a Config,
76        tree: &'a T,
77    ) -> Self {
78        Self {
79            rockspec,
80            spec,
81            rock_bytes,
82            source,
83            config,
84            tree,
85            entry_type,
86            behaviour: build::Behaviour::Ignore,
87        }
88    }
89
90    pub(crate) fn behaviour(self, behaviour: build::Behaviour) -> Self {
91        Self { behaviour, ..self }
92    }
93
94    #[tracing::instrument(name = "Installing binary rock", skip_all)]
95    pub(crate) async fn install(self) -> Result<LockedPackage, Error> {
96        let rockspec = self.rockspec;
97        for (name, dep) in rockspec.external_dependencies().current_platform() {
98            let _ = ExternalDependencyInfo::probe(name, dep, self.config.external_deps())?;
99        }
100
101        rockspec.validate_lua_version_from_config(self.config)?;
102
103        let hashes = locked_package::Hashes {
104            rockspec: rockspec.hash().await?,
105            source: self.rock_bytes.hash().await?,
106        };
107        let source_url = match &self.source {
108            remote::package::Source::LuarocksBinaryRock(url) => {
109                Some(RemotePackageSourceUrl::Url { url: url.clone() })
110            }
111            _ => None,
112        };
113        let package = LockedPackage::new(self.spec, self.source, source_url, hashes);
114        match self.tree.lockfile()?.get(&package.id()) {
115            Some(package)
116                if matches!(
117                    self.behaviour,
118                    build::Behaviour::Ignore | build::Behaviour::Conflict
119                ) =>
120            {
121                Ok(package.clone())
122            }
123            _ => {
124                let unpack_dir = fs::tempfile::tempdir()?;
125                let cursor = Cursor::new(self.rock_bytes);
126                let mut zip = zip::ZipArchive::new(cursor)?;
127                zip.extract(&unpack_dir)?;
128                self.tree.prepare(&package.spec)?;
129                let layout = self.tree.layout_for(&package.spec);
130                let sources = RockManifestSources {
131                    root: unpack_dir.path().to_path_buf(),
132                    lib: unpack_dir.path().join("lib"),
133                    lua: unpack_dir.path().join("lua"),
134                    bin: unpack_dir.path().join("bin"),
135                };
136                install_rock_manifest(sources, &layout, &self.tree.bin()).await?;
137                // rename <name>-<version>.rockspec
138                let rockspec_path =
139                    layout
140                        .etc
141                        .join(format!("{}-{}.rockspec", package.name(), package.version()));
142                if rockspec_path.is_file() {
143                    fs::tokio::copy(&rockspec_path, layout.rockspec_path()).await?;
144                    fs::tokio::remove_file(&rockspec_path).await?;
145                }
146                self.tree.finalize(&package, self.entry_type)?;
147                self.tree
148                    .lockfile()?
149                    .write_guard()
150                    .set_binaries(&package, rockspec.binaries());
151                Ok(package)
152            }
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use std::path::PathBuf;
160
161    use assert_fs::TempDir;
162    use io::{Read, Write};
163    use is_executable::IsExecutable;
164    use zip::write::SimpleFileOptions;
165
166    #[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "impure_tests"))]
167    use crate::luarocks::rock_manifest::RockManifest;
168    use crate::{
169        config,
170        lockfile::{self, OptState, PinnedState},
171        lua,
172        operations::download,
173        package,
174    };
175
176    use super::*;
177    #[cfg(feature = "impure_tests")]
178    use flaky_test::flaky_test;
179
180    impl rockspec::lua::Remote {
181        fn to_locked_package_spec(&self) -> locked_package::Spec {
182            locked_package::Spec::new(
183                self.package(),
184                self.version(),
185                lockfile::Constraint::Unconstrained,
186                Vec::new(),
187                Vec::new(),
188                &PinnedState::default(),
189                &OptState::default(),
190            )
191        }
192    }
193
194    #[tokio::test]
195    async fn install_binary_rock() {
196        let rock = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
197            .join("resources/test/sample-project-0.1.0-1.all.rock");
198        let content = std::fs::read(rock).unwrap();
199        let rock_bytes = Bytes::copy_from_slice(&content);
200        let packed_rock_file_name = "sample-project-0.1.0-1.all.rock".to_string();
201        let cursor = Cursor::new(rock_bytes.clone());
202        let mut zip = zip::ZipArchive::new(cursor).unwrap();
203        let manifest_index = zip.index_for_path("rock_manifest").unwrap();
204        let mut manifest_file = zip.by_index(manifest_index).unwrap();
205        let mut content = String::new();
206        manifest_file.read_to_string(&mut content).unwrap();
207        let rock = download::PackedRockBytes {
208            name: "sample-project".into(),
209            version: "0.1.0-1".parse().unwrap(),
210            bytes: rock_bytes,
211            file_name: packed_rock_file_name.clone(),
212            url: "https://test.org".parse().unwrap(),
213        };
214        let rockspec = download::unpack_rockspec(&rock).await.unwrap();
215        let install_root = assert_fs::TempDir::new().unwrap();
216        let config = config::Builder::new()
217            .unwrap()
218            .user_tree(Some(install_root.to_path_buf()))
219            .build()
220            .unwrap();
221        let tree = config
222            .user_tree(config.lua_version().unwrap().clone())
223            .unwrap();
224        let local_package = BinaryRockInstall::new(
225            &rockspec,
226            rockspec.to_locked_package_spec(),
227            rock.bytes,
228            remote::package::Source::Test,
229            tree::EntryType::Entrypoint,
230            &config,
231            &tree,
232        )
233        .install()
234        .await
235        .unwrap();
236        assert_eq!(
237            local_package.hashes().source,
238            "sha256-zDmnjE2b8GxX+6j5vTCWUEBxe0aFXFVhC4JOrnAgQ2g="
239                .parse()
240                .unwrap()
241        );
242        let foo_bar_module = tree
243            .layout_for(&local_package.spec)
244            .src
245            .join("foo")
246            .join("bar.lua");
247        assert!(foo_bar_module.is_file());
248    }
249
250    fn packed_rock_with_bin() -> Vec<u8> {
251        let rockspec = r#"
252rockspec_format = "3.0"
253package = "test-binary-bin"
254version = "1.0-1"
255source = { url = "https://example.com/test-binary-bin.zip" }
256"#;
257        let manifest = r#"rock_manifest = { bin = { mytool = "0" } }"#;
258        let mut buf = Vec::new();
259        {
260            let mut zip = zip::ZipWriter::new(Cursor::new(&mut buf));
261            let options = SimpleFileOptions::default();
262            for (name, content) in [
263                ("test-binary-bin-1.0-1.rockspec", rockspec.as_bytes()),
264                ("bin/mytool", b"#!/bin/sh\necho hi\n".as_slice()),
265                ("rock_manifest", manifest.as_bytes()),
266            ] {
267                zip.start_file(name, options).unwrap();
268                zip.write_all(content).unwrap();
269            }
270            zip.finish().unwrap();
271        }
272        buf
273    }
274
275    #[cfg(unix)]
276    #[tokio::test]
277    async fn install_binary_rock_makes_bin_executable() {
278        let rock = download::PackedRockBytes {
279            name: "test-binary-bin".into(),
280            version: "1.0-1".parse().unwrap(),
281            bytes: Bytes::from(packed_rock_with_bin()),
282            file_name: "test-binary-bin-1.0-1.all.rock".into(),
283            url: "https://test.org".parse().unwrap(),
284        };
285        let rockspec = download::unpack_rockspec(&rock).await.unwrap();
286        let install_root = TempDir::new().unwrap();
287        let config = config::Builder::new()
288            .unwrap()
289            .user_tree(Some(install_root.to_path_buf()))
290            .build()
291            .unwrap();
292        let tree = config
293            .user_tree(config.lua_version().unwrap().clone())
294            .unwrap();
295        BinaryRockInstall::new(
296            &rockspec,
297            rockspec.to_locked_package_spec(),
298            rock.bytes,
299            remote::package::Source::Test,
300            tree::EntryType::Entrypoint,
301            &config,
302            &tree,
303        )
304        .install()
305        .await
306        .unwrap();
307        assert!(tree.bin().join("mytool").is_executable());
308    }
309
310    #[tokio::test]
311    async fn install_binary_rock_preserves_dependencies() {
312        let rock = download::PackedRockBytes {
313            name: "test-binary-bin".into(),
314            version: "1.0-1".parse().unwrap(),
315            bytes: Bytes::from(packed_rock_with_bin()),
316            file_name: "test-binary-bin-1.0-1.all.rock".into(),
317            url: "https://test.org".parse().unwrap(),
318        };
319        let rockspec = download::unpack_rockspec(&rock).await.unwrap();
320        let dependency = locked_package::ID::new(
321            &package::Name::from("transitive-dependency"),
322            &"1.0-1".parse().unwrap(),
323            PinnedState::default(),
324            OptState::default(),
325            lockfile::Constraint::Unconstrained,
326        );
327        let spec = locked_package::Spec::new(
328            rockspec.package(),
329            rockspec.version(),
330            lockfile::Constraint::Unconstrained,
331            vec![dependency.clone()],
332            Vec::new(),
333            &PinnedState::default(),
334            &OptState::default(),
335        );
336        let install_root = TempDir::new().unwrap();
337        let config = config::Builder::new()
338            .unwrap()
339            .lua_version(Some(lua::Version::Lua51))
340            .user_tree(Some(install_root.to_path_buf()))
341            .build()
342            .unwrap();
343        let tree = config.user_tree(lua::Version::Lua51).unwrap();
344
345        let installed = BinaryRockInstall::new(
346            &rockspec,
347            spec,
348            rock.bytes,
349            remote::package::Source::Test,
350            tree::EntryType::Entrypoint,
351            &config,
352            &tree,
353        )
354        .install()
355        .await
356        .unwrap();
357
358        assert_eq!(installed.dependencies(), vec![&dependency]);
359    }
360
361    /// This relatively large integration test case tests the following:
362    ///
363    /// - Install a packed rock that was packed using luarocks 3.11 from the test resources.
364    /// - operations::Pack the rock using our own `operations::Pack` implementation.
365    /// - Verify that the `rock_manifest` entry of the original packed rock and our own packed rock
366    ///   are equal (this means luarocks should be able to install our packed rock).
367    /// - operations::Uninstall the local package.
368    /// - Install the package from our packed rock.
369    /// - Verify that the contents of the install directories when installing from both packed rocks
370    ///   are the same.
371    #[cfg(all(target_os = "linux", target_arch = "x86_64", feature = "impure_tests"))]
372    #[flaky_test(tokio, times = 5)]
373    async fn install_binary_rock_roundtrip() {
374        use crate::operations;
375
376        let rock = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
377            .join("resources/test/toml-edit-0.6.0-1.linux-x86_64.rock");
378        let content = std::fs::read(rock).unwrap();
379        let rock_bytes = Bytes::copy_from_slice(&content);
380        let packed_rock_file_name = "toml-edit-0.6.0-1.linux-x86_64.rock".to_string();
381        let cursor = Cursor::new(rock_bytes.clone());
382        let mut zip = zip::ZipArchive::new(cursor).unwrap();
383        let manifest_index = zip.index_for_path("rock_manifest").unwrap();
384        let mut manifest_file = zip.by_index(manifest_index).unwrap();
385        let mut content = String::new();
386        manifest_file.read_to_string(&mut content).unwrap();
387        let orig_manifest = RockManifest::new(&content).unwrap();
388        let rock = download::PackedRockBytes {
389            name: "toml-edit".into(),
390            version: "0.6.0-1".parse().unwrap(),
391            bytes: rock_bytes,
392            file_name: packed_rock_file_name.clone(),
393            url: "https://test.org".parse().unwrap(),
394        };
395        let rockspec = download::unpack_rockspec(&rock).await.unwrap();
396        let install_root = assert_fs::TempDir::new().unwrap();
397        let config = config::Builder::new()
398            .unwrap()
399            .user_tree(Some(install_root.to_path_buf()))
400            .build()
401            .unwrap();
402        let tree = config
403            .user_tree(config.lua_version().unwrap().clone())
404            .unwrap();
405        let local_package = BinaryRockInstall::new(
406            &rockspec,
407            rockspec.to_locked_package_spec(),
408            rock.bytes,
409            remote::package::Source::Test,
410            tree::EntryType::Entrypoint,
411            &config,
412            &tree,
413        )
414        .install()
415        .await
416        .unwrap();
417        let layout = tree.layout_for(local_package.spec());
418        assert!(layout.lib.join("toml_edit.so").is_file());
419
420        let orig_install_tree_integrity = layout.root.hash().await.unwrap();
421
422        let pack_dest_dir = assert_fs::TempDir::new().unwrap();
423        let packed_rock = operations::Pack::new(
424            pack_dest_dir.to_path_buf(),
425            tree.clone(),
426            local_package.clone(),
427        )
428        .pack()
429        .await
430        .unwrap();
431        assert_eq!(
432            packed_rock
433                .file_name()
434                .unwrap()
435                .to_string_lossy()
436                .to_string(),
437            packed_rock_file_name.clone()
438        );
439
440        // let's make sure our own pack/unpack implementation roundtrips correctly
441        operations::Uninstall::new()
442            .config(&config)
443            .package(local_package.id())
444            .remove()
445            .await
446            .unwrap();
447        let content = std::fs::read(&packed_rock).unwrap();
448        let rock_bytes = Bytes::copy_from_slice(&content);
449        let cursor = Cursor::new(rock_bytes.clone());
450        let mut zip = zip::ZipArchive::new(cursor).unwrap();
451        let manifest_index = zip.index_for_path("rock_manifest").unwrap();
452        let mut manifest_file = zip.by_index(manifest_index).unwrap();
453        let mut content = String::new();
454        manifest_file.read_to_string(&mut content).unwrap();
455        let packed_manifest = RockManifest::new(&content).unwrap();
456        assert_eq!(packed_manifest, orig_manifest);
457        let rock = download::PackedRockBytes {
458            name: "toml-edit".into(),
459            version: "0.6.0-1".parse().unwrap(),
460            bytes: rock_bytes,
461            file_name: packed_rock_file_name.clone(),
462            url: "https://test.org".parse().unwrap(),
463        };
464        let rockspec = download::unpack_rockspec(&rock).await.unwrap();
465        let local_package = BinaryRockInstall::new(
466            &rockspec,
467            rockspec.to_locked_package_spec(),
468            rock.bytes,
469            remote::package::Source::Test,
470            tree::EntryType::Entrypoint,
471            &config,
472            &tree,
473        )
474        .install()
475        .await
476        .unwrap();
477        let layout = tree.layout_for(local_package.spec());
478        assert!(layout.rockspec_path().is_file());
479        let new_install_tree_integrity = layout.root.hash().await.unwrap();
480        assert_eq!(orig_install_tree_integrity, new_install_tree_integrity);
481    }
482}