1use crate::lockfile::locked_package;
2use crate::package;
3use std::{collections::HashMap, io};
4
5use bon::Builder;
6use itertools::Itertools;
7use miette::Diagnostic;
8use thiserror::Error;
9use tracing::Instrument;
10
11use crate::{
12 build,
13 config::Config,
14 lockfile::{FlushLockfileError, LockedPackage, LockedPackageLockType, Lockfile, ReadWrite},
15 lua,
16 luarocks::installation,
17 package::db::PackageDB,
18 tree::{self, InstallTree},
19 workspace::TreeError,
20};
21
22use crate::pipeline::{
23 build::{Build as PipelineBuild, Error as PipelineBuildError},
24 emit_lockfile::LockfileHandle,
25 materialise::{Error as MaterialiseError, Materialise},
26 resolve::{self, ResolvePackageDependencies},
27};
28
29use crate::operations::install;
30
31#[derive(Builder)]
36#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
37pub struct InstallPackages<'a, T>
38where
39 T: InstallTree + Send + Sync,
40{
41 #[builder(start_fn)]
42 config: &'a Config,
43 #[builder(start_fn)]
44 tree: &'a T,
45 #[builder(field)]
46 build_packages: Vec<install::Spec>,
47 #[builder(field)]
48 test_packages: Option<Vec<install::Spec>>,
49 #[builder(field)]
50 packages: Vec<install::Spec>,
51 package_db: PackageDB,
52}
53
54impl<'a, T, State> InstallPackagesBuilder<'a, T, State>
55where
56 T: InstallTree + Send + Sync,
57 State: install_packages_builder::State,
58{
59 pub fn packages(mut self, packages: Vec<install::Spec>) -> Self {
60 self.packages = packages;
61 self
62 }
63
64 pub fn package(mut self, package: install::Spec) -> Self {
65 self.packages.push(package);
66 self
67 }
68
69 pub fn build_packages(mut self, packages: Vec<install::Spec>) -> Self {
70 self.build_packages = packages;
71 self
72 }
73
74 pub fn test_packages(mut self, packages: Vec<install::Spec>) -> Self {
75 self.test_packages = Some(packages);
76 self
77 }
78}
79
80impl<T, State> InstallPackagesBuilder<'_, T, State>
81where
82 State: install_packages_builder::State + install_packages_builder::IsComplete,
83 T: InstallTree + Send + Sync,
84{
85 pub async fn install(self) -> Result<(Vec<LockedPackage>, LockfileHandle), Error> {
86 let args = self._build();
87 if args.packages.is_empty()
88 && args.build_packages.is_empty()
89 && args.test_packages.is_none()
90 {
91 return Ok((Vec::new(), LockfileHandle::default()));
92 }
93 let span = match args.packages.as_slice() {
94 [install_spec] => {
95 tracing::info_span!("Installing", package = install_spec.package.to_string())
96 }
97 packages => tracing::info_span!("Installing", count = packages.len()),
98 };
99 install_packages(args).instrument(span).await
100 }
101}
102
103async fn install_packages<T>(
104 install: InstallPackages<'_, T>,
105) -> Result<(Vec<LockedPackage>, LockfileHandle), Error>
106where
107 T: InstallTree + Send + Sync,
108{
109 let package_db = install.package_db;
110
111 let duplicate_entrypoints = install
112 .packages
113 .iter()
114 .filter(|pkg| pkg.entry_type == tree::EntryType::Entrypoint)
115 .map(|pkg| pkg.package.name())
116 .duplicates()
117 .cloned()
118 .collect_vec();
119
120 if !duplicate_entrypoints.is_empty() {
121 return Err(Error::DuplicateEntrypoints(package::List::new(
122 duplicate_entrypoints,
123 )));
124 }
125
126 let packages = install.packages;
127 let config = install.config;
128 let tree = install.tree;
129
130 let lockfile = tree.lockfile()?;
131 let build_tree = tree.build_tree(config)?;
132 let build_lockfile = build_tree.lockfile()?;
133
134 let mut installed: HashMap<LockedPackageLockType, Vec<LockedPackage>> = HashMap::new();
135 installed.insert(
136 LockedPackageLockType::Regular,
137 lockfile.rocks().values().cloned().collect_vec(),
138 );
139 installed.insert(
140 LockedPackageLockType::Build,
141 build_lockfile.rocks().values().cloned().collect_vec(),
142 );
143 if install.test_packages.is_some() {
144 installed.insert(
145 LockedPackageLockType::Test,
146 tree.test_tree(config)?
147 .lockfile()?
148 .rocks()
149 .values()
150 .cloned()
151 .collect_vec(),
152 );
153 }
154
155 let mut resolve = ResolvePackageDependencies::new(package_db, config)
156 .installed(installed)
157 .packages(packages)
158 .build_packages(install.build_packages);
159 if let Some(test_packages) = install.test_packages {
160 resolve = resolve.test_packages(test_packages);
161 }
162 let resolved = resolve.resolve().await?;
163 let artifacts = Materialise::new(config)
164 .resolved(resolved)
165 .materialise()
166 .await?;
167 let handle = LockfileHandle::from_artifacts(&artifacts);
168
169 let build_packages = artifacts
170 .build
171 .unwrap_or_default()
172 .into_values()
173 .collect_vec();
174 let regular_packages = artifacts
175 .regular
176 .unwrap_or_default()
177 .into_values()
178 .collect_vec();
179
180 let mut conflicting_entrypoints: HashMap<locked_package::ID, LockedPackage> = HashMap::new();
183 let mut unforced_conflicts = Vec::new();
184 for package in regular_packages
185 .iter()
186 .filter(|package| package.entry_type == tree::EntryType::Entrypoint)
187 {
188 match lockfile.entrypoint(package.package.name()) {
189 None => continue,
190 Some(existing) => match package.build_behaviour {
191 build::Behaviour::Force => {
193 conflicting_entrypoints.insert(existing.id(), existing.clone());
194 }
195 build::Behaviour::Ignore if existing.version() == package.package.version() => {}
197 build::Behaviour::Ignore | build::Behaviour::Conflict => {
199 unforced_conflicts.push(format!("{}@{}", existing.name(), existing.version()));
200 }
201 },
202 }
203 }
204
205 if !unforced_conflicts.is_empty() {
206 return Err(Error::ConflictingEntrypoints(unforced_conflicts.join("\n")));
207 }
208
209 let conflicting_entrypoints = conflicting_entrypoints.into_values().collect_vec();
212 for package in &conflicting_entrypoints {
213 tree.cleanup(package, tree::EntryType::Entrypoint)?;
214 }
215
216 let regular_entry_types: HashMap<locked_package::ID, tree::EntryType> = regular_packages
217 .iter()
218 .map(|pkg| (pkg.package.spec.id(), pkg.entry_type))
219 .collect();
220
221 let built_build_deps = PipelineBuild::new(config, &build_tree)
223 .packages(build_packages)
224 .build()
225 .await?;
226 let built = PipelineBuild::new(config, tree)
227 .packages(regular_packages)
228 .build()
229 .await?;
230 if let Some(test_packages) = artifacts.test {
231 let test_tree = tree.test_tree(config)?;
232 PipelineBuild::new(config, &test_tree)
233 .packages(test_packages.into_values().collect_vec())
234 .build()
235 .await?;
236 }
237
238 let mut installed_packages: HashMap<locked_package::ID, LockedPackage> = lockfile
239 .rocks()
240 .iter()
241 .map(|(id, package)| (id.clone(), package.clone()))
242 .collect();
243 installed_packages.extend(built.iter().map(|pkg| (pkg.spec().id(), pkg.clone())));
244 let mut installed_build_deps: HashMap<locked_package::ID, LockedPackage> = build_lockfile
245 .rocks()
246 .iter()
247 .map(|(id, package)| (id.clone(), package.clone()))
248 .collect();
249 installed_build_deps.extend(
250 built_build_deps
251 .iter()
252 .map(|pkg| (pkg.spec().id(), pkg.clone())),
253 );
254
255 tree.lockfile()?.map_then_flush(|lockfile| {
258 for package in &conflicting_entrypoints {
259 if regular_entry_types.contains_key(&package.id()) {
262 continue;
263 }
264 lockfile.remove_by_id(&package.id());
265 }
266 for package in &built {
267 let entry_type = regular_entry_types[&package.spec().id()];
268 lockfile.add_dependencies(package, entry_type, &installed_packages)?;
269 lockfile.add_build_dependencies(package, &installed_build_deps)?;
270 }
271 Ok::<_, io::Error>(())
272 })?;
273
274 Ok((built, handle))
275}
276
277#[derive(Error, Debug, Diagnostic)]
278pub enum Error {
279 #[error(transparent)]
280 #[diagnostic(transparent)]
281 LuaVersion(#[from] lua::version::Error),
282 #[error(transparent)]
283 #[diagnostic(transparent)]
284 LuaInstallation(#[from] lua::installation::Error),
285 #[error(transparent)]
286 #[diagnostic(transparent)]
287 FlushLockfile(#[from] FlushLockfileError),
288 #[error(transparent)]
289 #[diagnostic(transparent)]
290 Tree(#[from] tree::Error),
291 #[error(transparent)]
292 #[diagnostic(transparent)]
293 WorkspaceTree(#[from] TreeError),
294 #[error("error preparing the LuaRocks compatibility layer")]
295 #[diagnostic(forward(0))]
296 LuaRocks(#[from] Box<installation::Error>),
297 #[error("error initialising remote package DB")]
298 #[diagnostic(forward(0))]
299 PackageDB(#[from] package::db::Error),
300 #[error("cannot install duplicate entrypoints:\n{0}")]
301 DuplicateEntrypoints(package::List),
302 #[error("cannot install conflicting entrypoints:\n{0}")]
303 #[diagnostic(help(
304 "only a single entrypoint per package is allowed.\nif you would like to replace the existing entrypoints, retry with `--force` to overwrite the existing entrypoint"
305 ))]
306 ConflictingEntrypoints(String),
307 #[error(transparent)]
308 #[diagnostic(transparent)]
309 Resolve(#[from] resolve::Error),
310 #[error(transparent)]
311 #[diagnostic(transparent)]
312 Download(#[from] MaterialiseError),
313 #[error(transparent)]
314 #[diagnostic(transparent)]
315 Build(#[from] PipelineBuildError),
316}
317
318impl From<installation::Error> for Error {
319 fn from(source: installation::Error) -> Self {
320 Self::LuaRocks(Box::new(source))
321 }
322}
323
324trait LockfileExt {
325 fn add_dependencies(
326 self,
327 pkg: &LockedPackage,
328 entry_type: tree::EntryType,
329 installed_packages: &HashMap<locked_package::ID, LockedPackage>,
330 ) -> io::Result<()>;
331
332 fn add_build_dependencies(
333 self,
334 pkg: &LockedPackage,
335 build_dependencies: &HashMap<locked_package::ID, LockedPackage>,
336 ) -> io::Result<()>;
337}
338
339impl LockfileExt for &mut Lockfile<ReadWrite> {
340 fn add_dependencies(
341 self,
342 pkg: &LockedPackage,
343 entry_type: tree::EntryType,
344 installed_packages: &HashMap<locked_package::ID, LockedPackage>,
345 ) -> io::Result<()> {
346 if entry_type == tree::EntryType::Entrypoint {
347 self.add_entrypoint(pkg);
348 }
349
350 for dependency_id in pkg.spec().dependencies() {
351 self.add_dependency(
352 pkg,
353 installed_packages
354 .get(dependency_id)
355 .ok_or(io::Error::other(
356 r#"
357error writing dependencies to the lockfile.
358A required dependency was not installed correctly.
359This is likely a bug in Lux.
360"#,
361 ))?,
362 );
363 }
364 Ok(())
365 }
366
367 fn add_build_dependencies(
368 self,
369 pkg: &LockedPackage,
370 build_dependencies: &HashMap<locked_package::ID, LockedPackage>,
371 ) -> io::Result<()> {
372 for dependency_id in pkg.spec().build_dependencies() {
373 self.add_build_dependency(
374 pkg,
375 build_dependencies
376 .get(dependency_id)
377 .ok_or(io::Error::other(
378 r#"
379error writing build dependencies to the lockfile.
380A required build dependency was not installed correctly.
381This is likely a bug in Lux.
382"#,
383 ))?,
384 );
385 }
386 Ok(())
387 }
388}