1use lux_lib::package;
2use lux_lib::rockspec;
3use std::path::{Path, PathBuf};
4
5use crate::{args::PackageOrRockspec, build, workspace::exists_matching_workspace_member};
6use clap::Args;
7use itertools::Itertools;
8use lux_lib::{
9 config::Config,
10 drivers::InstallPackages,
11 lua,
12 operations::{self, install},
13 package::db::PackageDB,
14 pipeline::build_local::Build,
15 rockspec::Rockspec as _,
16 tree::{self, InstallTree},
17 workspace::Workspace,
18};
19use miette::{miette, IntoDiagnostic, Result};
20use path_slash::PathBufExt;
21use tempfile::tempdir;
22
23#[derive(Args)]
24pub struct Pack {
25 #[clap(value_parser)]
41 pub(crate) package_or_rockspec: Option<PackageOrRockspec>,
42}
43
44async fn pack_workspace(
45 member: Option<&package::Name>,
46 dest_dir: &Path,
47 config: &Config,
48) -> Result<Vec<PathBuf>> {
49 let workspace = Workspace::current_or_err()?;
50
51 let packages = match member {
54 Some(package_name) => {
56 let project = workspace.select_member(package_name)?;
57 project
58 .toml()
59 .into_remote(None)?
60 .to_lua_remote_rockspec_string()?;
61
62 let mut build = build::Build::default();
63 build.package = Some(package_name.clone());
64 build::build(build, config.clone())
65 .await?
66 .into_iter()
67 .filter(|package| package.name() == package_name)
68 .collect_vec()
69 }
70 None => {
72 for project in workspace.members() {
73 project
74 .toml()
75 .into_remote(None)?
76 .to_lua_remote_rockspec_string()?;
77 }
78 build::build(build::Build::default(), config.clone())
79 .await?
80 .into_iter()
81 .filter(|package| {
82 workspace
83 .members()
84 .iter()
85 .any(|member| member.toml().package() == package.name())
86 })
87 .collect_vec()
88 }
89 };
90
91 if packages.is_empty() {
92 return Err(miette!("build did not produce a package"));
93 }
94
95 let mut rock_paths = Vec::new();
96 for package in packages {
97 let tree = workspace.tree(config)?;
98 let rock_path = operations::Pack::new(dest_dir.to_path_buf(), tree, package)
99 .pack()
100 .await?;
101 rock_paths.push(rock_path);
102 }
103
104 Ok(rock_paths)
105}
106
107pub async fn pack(args: Pack, config: Config) -> Result<()> {
108 let lua_version = lua::Version::from(&config)?.clone();
109 let dest_dir = std::env::current_dir().into_diagnostic()?;
110 let rock_paths: Vec<PathBuf> = match args.package_or_rockspec {
111 Some(PackageOrRockspec::Package(package_req))
112 if exists_matching_workspace_member(&package_req)? =>
113 {
114 pack_workspace(Some(package_req.name()), &dest_dir, &config).await
115 }
116 Some(PackageOrRockspec::Package(package_req)) => {
117 let user_tree = config.user_tree(lua_version.clone())?;
118 match user_tree.match_rocks(&package_req)? {
119 tree::RockMatches::NotFound(_) => {
120 let temp_dir = tempdir().into_diagnostic()?;
121 let temp_config = config.with_tree(temp_dir.path().to_path_buf());
122 let tree = temp_config.user_tree(lua_version.clone())?;
123 let packages = InstallPackages::new(&temp_config, &tree)
124 .package(
125 install::Spec::new(package_req, tree::EntryType::Entrypoint)
126 .build_behaviour(lux_lib::build::Behaviour::Force)
127 .build(),
128 )
129 .package_db(PackageDB::from_config(&temp_config).await?)
130 .install()
131 .await?
132 .0;
133 let package = packages
134 .first()
135 .ok_or_else(|| miette!("no packages installed"))?;
136 let rock_path = operations::Pack::new(dest_dir, tree, package.clone())
137 .pack()
138 .await?;
139 Ok(vec![rock_path])
140 }
141 tree::RockMatches::Single(local_package_id) => {
142 let lockfile = user_tree.lockfile()?;
143 let package = lockfile.get(&local_package_id).ok_or_else(|| {
144 miette!("package is installed, but was not found in the lockfile")
145 })?;
146 let rock_path = operations::Pack::new(dest_dir, user_tree, package.clone())
147 .pack()
148 .await?;
149 Ok(vec![rock_path])
150 }
151 tree::RockMatches::Many(vec) => {
152 let local_package_id = vec.first();
153 let lockfile = user_tree.lockfile()?;
154 let package = lockfile.get(local_package_id).ok_or_else(|| {
155 miette!(
156 "multiple package installations found, but not found in the lockfile"
157 )
158 })?;
159 let rock_path = operations::Pack::new(dest_dir, user_tree, package.clone())
160 .pack()
161 .await?;
162 Ok(vec![rock_path])
163 }
164 }
165 }
166 Some(PackageOrRockspec::RockSpec(rockspec_path)) => {
167 let content = tokio::fs::read_to_string(&rockspec_path)
168 .await
169 .into_diagnostic()?;
170 let rockspec = match rockspec_path
171 .extension()
172 .map(|ext| ext.to_string_lossy().to_string())
173 .unwrap_or("".into())
174 .as_str()
175 {
176 "rockspec" => Ok(rockspec::lua::Remote::new(&content)?),
177 _ => Err(miette!(
178 "expected a path to a .rockspec or a package requirement."
179 )),
180 }?;
181 let temp_dir = tempdir().into_diagnostic()?;
182 let config = config.with_tree(temp_dir.path().to_path_buf());
183 let lua = lua::Installation::new(&lua_version, &config).await?;
184 let tree = config.user_tree(lua_version)?;
185 let package = Build::new()
186 .rockspec(&rockspec)
187 .lua(&lua)
188 .tree(&tree)
189 .entry_type(tree::EntryType::Entrypoint)
190 .config(&config)
191 .behaviour(lux_lib::build::Behaviour::Force)
192 .build()
193 .await?;
194 let rock_path = operations::Pack::new(dest_dir, tree, package)
195 .pack()
196 .await?;
197 Ok(vec![rock_path])
198 }
199 None => pack_workspace(None, &dest_dir, &config).await,
200 }?;
201
202 if rock_paths.len() > 1 {
203 let rock_paths = rock_paths
204 .iter()
205 .map(|path| path.to_slash_lossy().to_string())
206 .join("\n");
207 print!("packed rocks created at\n{}", rock_paths)
208 } else {
209 rock_paths
210 .first()
211 .iter()
212 .for_each(|path| print!("packed rock created at {}", path.display()));
213 }
214 Ok(())
215}