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