1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
|
use crate::cfg::config::Config;
use std::{
fs::create_dir_all,
path::{Path, PathBuf},
process::Command,
};
use glob::glob;
use num_cpus;
use super::archive::ArchiveOperations;
use super::types::{Build, BuildSystems, Package};
pub trait BuildOperations {
fn execute_build(&self, build_meta: &Build) -> Result<(), std::io::Error>;
fn build(&mut self) -> Result<bool, std::io::Error>;
fn find_makefile(
&self,
build_meta: &Build,
search_dir: &Path,
) -> std::io::Result<Option<PathBuf>>;
fn run_command(cmd: std::process::Command, context: &str) -> Result<(), std::io::Error>;
fn run_build_system(
source_dir: &Path,
required_file: &str,
configure_cmd: &[&str],
build_cmd: &[&str],
work_dir: &Path,
envs: &[(String, String)],
context: &str,
) -> Result<(), std::io::Error>;
}
#[allow(dead_code)]
impl BuildOperations for Package {
/// Runs a command and checks if it was successful.
/// If the command fails, it returns an error with the command's
/// stdout and stderr.
///
/// # Arguments
///
/// * `cmd`: The command to run.
/// * `context`: A string to prefix the error message with if the command fails.
fn run_command(mut cmd: std::process::Command, context: &str) -> Result<(), std::io::Error> {
let output = cmd
.output()
.map_err(|e| std::io::Error::other(format!("{} failed: {}", context, e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
return Err(std::io::Error::other(format!(
"{} failed:\nStdout: {}\nStderr: {}",
context, stdout, stderr
)));
}
Ok(())
}
/// Runs a build system given the following parameters:
///
/// `source_dir`: The directory containing the source code
/// `required_file`: The file that must exist in the source directory
/// `configure_cmd`: The command to run for configure step
/// `build_cmd`: The command to run for build step
/// `work_dir`: The directory where the build process will take place
/// `envs`: A list of environment variables to set during the build process
/// `context`: A string context to provide for error messages
fn run_build_system(
source_dir: &Path,
required_file: &str,
configure_cmd: &[&str],
build_cmd: &[&str],
work_dir: &Path,
envs: &[(String, String)],
context: &str,
) -> Result<(), std::io::Error> {
let required_path = source_dir.join(required_file);
if !required_path.exists() {
return Err(std::io::Error::other(format!(
"{} file not found: {}",
context,
required_path.display()
)));
}
if !work_dir.exists() {
create_dir_all(work_dir)?;
}
// Configure step
let mut config_cmd = std::process::Command::new(configure_cmd[0]);
config_cmd.args(&configure_cmd[1..]).current_dir(source_dir);
for (key, value) in envs {
config_cmd.env(key, value);
}
log::info!("Running {} configuration: {:?}", context, config_cmd);
Self::run_command(config_cmd, &format!("{} config", context))?;
// Build step
let mut build_cmd_inner = std::process::Command::new(build_cmd[0]);
build_cmd_inner.args(&build_cmd[1..]).current_dir(work_dir);
for (key, value) in envs {
build_cmd_inner.env(key, value);
}
log::info!("Running {} build: {:?}", context, build_cmd_inner);
Self::run_command(build_cmd_inner, &format!("{} build", context))?;
Ok(())
}
/// Finds the build system file (e.g. Makefile, meson.build, CMakeLists.txt, Cargo.toml)
/// based on the build system specified in the build metadata.
///
/// # Arguments
///
/// * `build_meta`: The build metadata containing the build system type.
/// * `search_dir`: The directory to search in for the build system file.
///
/// # Returns
///
/// A `Result` containing an `Option<PathBuf>` which is `Some` if the build
/// system file is found, and `None` otherwise.
fn find_makefile(
&self,
build_meta: &Build,
search_dir: &Path,
) -> std::io::Result<Option<PathBuf>> {
let (patterns, recursive) = match build_meta.build_system {
BuildSystems::Make => (vec!["Makefile", "makefile", "GNUmakefile"], false),
BuildSystems::Meson => (vec!["meson.build", "meson_options.txt"], true),
BuildSystems::CMake => (vec!["CMakeLists.txt"], true),
BuildSystems::Cargo => (vec!["Cargo.toml"], false),
};
for pattern in &patterns {
let glob_pattern = if recursive {
search_dir
.join("**")
.join(pattern)
.to_string_lossy()
.into_owned()
} else {
search_dir.join(pattern).to_string_lossy().into_owned()
};
let mut entries = glob(&glob_pattern)
.map_err(|e| std::io::Error::other(format!("Invalid glob pattern: {}", e)))?;
if let Some(entry) = entries.next() {
let path =
entry.map_err(|e| std::io::Error::other(format!("Glob error: {}", e)))?;
return Ok(Some(path));
}
}
Ok(None)
}
/// Execute the build script for the package.
///
/// This function takes the `Build` meta information as an argument and
/// executes the build script accordingly. It also handles the different
/// build systems supported (Make, CMake, Meson, Cargo).
///
/// # Errors
///
/// Returns an error if the build command fails.
fn execute_build(&self, build_meta: &Build) -> Result<(), std::io::Error> {
let config = Config::parse().map_err(|e| std::io::Error::other(e.to_string()))?;
let build_dir =
Path::new(&config.paths.cache_dir).join(format!("{}-{}", self.name, self.version));
if !build_dir.exists() {
return Err(std::io::Error::other(format!(
"Build directory not found: {}",
build_dir.display()
)));
}
let mut cmd_envs: Vec<(String, String)> = Vec::new();
if let Some(ref env_vars) = build_meta.env {
for env_line in env_vars.lines() {
if let Some((key, value)) = env_line.split_once('=') {
cmd_envs.push((key.trim().to_string(), value.trim().to_string()));
}
}
}
if let Some(ref script) = build_meta.script {
log::info!("Executing custom build script: {}", script);
Self::validate_custom_script(script)?;
let mut cmd = if script.starts_with("./") || script.starts_with('/') {
let script_path = build_dir.join(script);
if !script_path.exists() {
return Err(std::io::Error::other(format!(
"Custom script file not found: {}",
script_path.display()
)));
}
let mut inner_cmd = Command::new("/bin/sh");
inner_cmd.arg("-c");
inner_cmd.arg(script_path.to_str().unwrap());
let _ = inner_cmd.output();
inner_cmd
} else {
let mut inner_cmd = Command::new("/bin/sh");
inner_cmd.arg("-c");
inner_cmd.arg(script);
let _ = inner_cmd.output();
inner_cmd
};
cmd.current_dir(&build_dir);
for (key, value) in &cmd_envs {
cmd.env(key, value);
}
let output = cmd
.output()
.map_err(|e| std::io::Error::other(format!("Custom build script failed: {}", e)))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
return Err(std::io::Error::other(format!(
"Custom build script failed:\nStdout: {}\nStderr: {}",
stdout, stderr
)));
}
log::info!(
"Custom build script completed successfully for package: {}",
self.name
);
return Ok(());
}
// No custom script, proceed with build system
match build_meta.build_system {
BuildSystems::Make => {
let found = self
.find_makefile(build_meta, &build_dir)
.map_err(|e| {
std::io::Error::other(format!("Failed to search for Makefile: {}", e))
})?
.ok_or_else(|| std::io::Error::other("Makefile not found"))?;
if !found.exists() {
return Err(std::io::Error::other(format!(
"Makefile not found: {}",
found.display()
)));
}
let mut cmd = Command::new("make");
cmd.current_dir(&build_dir);
cmd.arg("all");
for (key, value) in &cmd_envs {
cmd.env(key, value);
}
log::info!("Running Make build: {:?}", cmd);
Self::run_command(cmd, "Make build")?;
}
BuildSystems::CMake => {
let found = self
.find_makefile(build_meta, &build_dir)
.map_err(|e| {
std::io::Error::other(format!("Failed to search for CMakeLists: {}", e))
})?
.ok_or_else(|| std::io::Error::other("Makefile not found"))?;
if !found.exists() {
return Err(std::io::Error::other(format!(
"Makefile not found: {}",
found.display()
)));
}
Self::run_build_system(
&build_dir,
"CMakeLists.txt",
&["cmake", "-S", ".", "-B", "build"],
&["make", "-j", &num_cpus::get().to_string()],
&build_dir.join("build"),
&cmd_envs,
"CMake",
)?;
}
BuildSystems::Meson => {
Self::run_build_system(
&build_dir,
"meson.build",
&["meson", "setup", "build"],
&["ninja", "-j", &num_cpus::get().to_string()],
&build_dir.join("build"),
&cmd_envs,
"Meson",
)?;
}
BuildSystems::Cargo => {
Self::run_build_system(
&build_dir,
"Cargo.toml",
&["cargo", "build", "--release"],
&[],
&build_dir,
&cmd_envs,
"Cargo",
)?;
}
}
log::info!("Build completed successfully for package: {}", self.name);
Ok(())
}
/// Builds the package according to the BUILD file in the archive.
///
/// There are two strategies for building the package. If the BUILD file is empty, the package is assumed to be a binary package and the default install hook is skipped. If the BUILD file is not empty, the package is assumed to be a source package and the default build hook is skipped.
///
/// If the BUILD file is empty and the INSTALL file contains a custom script, the custom script is run instead of the default install hook.
/// If the BUILD file is not empty and the INSTALL file contains a custom script, the custom script is ignored.
///
///
/// # Errors
///
/// Returns an error if the BUILD file is invalid or if the build or install hook fails.
fn build(&mut self) -> Result<bool, std::io::Error> {
let meta = Self::loadmeta(self)?;
let install_meta = meta.0;
// let setts_meta = meta.1;
let build_meta = meta.2;
// BUILD NOT EMPTY. SOURCE: -> BUILD -> INSTALL -> SETTS
// BUILD EMPTY. BIN: -> INSTALL -> SETTS
enum Strategies {
Bin,
Source,
}
let strategy; //default
if build_meta.is_none() {
log::info!("BUILD file is empty. Skipping build, preparing to install");
strategy = Strategies::Bin;
} else {
strategy = Strategies::Source;
log::info!("BUILD file is not empty. Skipping install, preparing to build");
}
match strategy {
Strategies::Bin => {
if install_meta.install.custom_script.is_none() {
log::info!("Strategy: BIN; No custom script. Running default install hook.");
} else {
log::info!("Strategy: BIN; Running custom script.");
let script = install_meta.install.custom_script.as_ref().unwrap();
// Validate script before execution
Self::validate_custom_script(script)?;
if self.arch.as_str().to_lowercase()
!= install_meta.package.arch.as_str().to_lowercase()
{
return Err(std::io::Error::other(format!(
"Package arch mismatch. Expected: {}, Actual: {}",
install_meta.package.arch.as_str(),
self.arch.as_str().to_lowercase()
)));
}
if !script.starts_with("./") {
let output = std::process::Command::new(script).output().map_err(|e| {
std::io::Error::other(format!("Failed to execute custom script: {}", e))
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(std::io::Error::other(format!(
"Custom script failed:\n{}",
stderr
)));
}
} else {
let output = std::process::Command::new("/bin/sh")
.arg("-c")
.arg(script)
.output()
.map_err(|e| {
std::io::Error::other(format!(
"Failed to execute custom script: {}",
e
))
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(std::io::Error::other(format!(
"Custom script failed:\n{}",
stderr
)));
}
}
}
}
Strategies::Source => {
log::info!("Strategy: SOURCE; Running default build hook.");
if let Err(e) = self.execute_build(&build_meta.unwrap()) {
return Err(std::io::Error::other(format!("Build failed: {}", e)));
}
}
}
Ok(true)
}
}
|