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