waxpkg 0.15.9

Fast Homebrew-compatible package manager
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::error::{Result, WaxError};
use crate::formula_parser::{BuildSystem, ParsedFormula};
use indicatif::ProgressBar;
use std::path::{Path, PathBuf};
use std::process::Command;
use tracing::{debug, info, instrument};

pub struct Builder {
    num_cores: usize,
    use_ccache: bool,
}

impl Builder {
    pub fn new() -> Self {
        let num_cores = Self::detect_cpu_cores();
        let use_ccache = Self::detect_ccache();

        info!(
            "Builder initialized: {} cores, ccache: {}",
            num_cores, use_ccache
        );

        Self {
            num_cores,
            use_ccache,
        }
    }

    fn detect_cpu_cores() -> usize {
        num_cpus::get().saturating_sub(1).max(1)
    }

    fn detect_ccache() -> bool {
        Command::new("which")
            .arg("ccache")
            .output()
            .map(|output| output.status.success())
            .unwrap_or(false)
    }

    #[instrument(skip(self, progress))]
    pub async fn build_from_source(
        &self,
        formula: &ParsedFormula,
        source_tarball: &Path,
        build_dir: &Path,
        install_prefix: &Path,
        progress: Option<&ProgressBar>,
    ) -> Result<()> {
        info!("Building {} from source", formula.name);

        if let Some(pb) = progress {
            pb.set_message("Extracting source...");
        }

        self.extract_source(source_tarball, build_dir).await?;

        let source_dir = self.find_source_directory(build_dir)?;

        if let Some(pb) = progress {
            pb.set_message("Configuring build...");
        }

        match formula.build_system {
            BuildSystem::Autotools => {
                self.build_autotools(&source_dir, install_prefix, &formula.configure_args)
                    .await?
            }
            BuildSystem::CMake => {
                self.build_cmake(&source_dir, install_prefix, &formula.configure_args)
                    .await?
            }
            BuildSystem::Meson => {
                self.build_meson(&source_dir, install_prefix, &formula.configure_args)
                    .await?
            }
            BuildSystem::Make => self.build_make(&source_dir, install_prefix).await?,
            BuildSystem::Cargo => self.build_cargo(&source_dir, install_prefix).await?,
            BuildSystem::Unknown => {
                return Err(WaxError::BuildError(
                    "Unknown build system - cannot build from source".to_string(),
                ))
            }
        }

        if let Some(pb) = progress {
            pb.set_message("Build complete");
        }

        Ok(())
    }

    /// Build directly from an already-present source directory (e.g. a git clone).
    #[instrument(skip(self, progress))]
    pub async fn build_from_directory(
        &self,
        formula: &ParsedFormula,
        source_dir: &Path,
        install_prefix: &Path,
        progress: Option<&ProgressBar>,
    ) -> Result<()> {
        info!("Building {} from directory {:?}", formula.name, source_dir);

        match formula.build_system {
            BuildSystem::Autotools => {
                self.build_autotools(source_dir, install_prefix, &formula.configure_args)
                    .await?
            }
            BuildSystem::CMake => {
                self.build_cmake(source_dir, install_prefix, &formula.configure_args)
                    .await?
            }
            BuildSystem::Meson => {
                self.build_meson(source_dir, install_prefix, &formula.configure_args)
                    .await?
            }
            BuildSystem::Make => self.build_make(source_dir, install_prefix).await?,
            BuildSystem::Cargo => self.build_cargo(source_dir, install_prefix).await?,
            BuildSystem::Unknown => {
                return Err(WaxError::BuildError(
                    "Unknown build system - cannot build from source".to_string(),
                ))
            }
        }

        if let Some(pb) = progress {
            pb.set_message("Build complete");
        }

        Ok(())
    }

    async fn extract_source(&self, tarball: &Path, dest: &Path) -> Result<()> {
        debug!("Extracting {:?} to {:?}", tarball, dest);

        tokio::fs::create_dir_all(dest).await?;

        let output = Command::new("tar")
            .arg("xzf")
            .arg(tarball)
            .arg("-C")
            .arg(dest)
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(WaxError::BuildError(format!(
                "Failed to extract source: {}",
                stderr
            )));
        }

        Ok(())
    }

    fn find_source_directory(&self, build_dir: &Path) -> Result<PathBuf> {
        let entries = std::fs::read_dir(build_dir)?
            .filter_map(|e| e.ok())
            .collect::<Vec<_>>();

        if entries.len() == 1 {
            let entry = &entries[0];
            if entry.file_type()?.is_dir() {
                return Ok(entry.path());
            }
        }

        Ok(build_dir.to_path_buf())
    }

    async fn build_autotools(
        &self,
        source_dir: &Path,
        prefix: &Path,
        configure_args: &[String],
    ) -> Result<()> {
        info!("Building with autotools");

        let configure_script = source_dir.join("configure");
        if !configure_script.exists() {
            let bootstrap = source_dir.join("bootstrap");
            if bootstrap.exists() {
                self.run_command(source_dir, "./bootstrap", &[], "Bootstrapping")
                    .await?;
            } else {
                let autogen = source_dir.join("autogen.sh");
                if autogen.exists() {
                    self.run_command(source_dir, "./autogen.sh", &[], "Generating build files")
                        .await?;
                }
            }
        }

        let mut args = vec![format!("--prefix={}", prefix.display())];
        args.extend(configure_args.iter().cloned());

        self.run_command(source_dir, "./configure", &args, "Configuring")
            .await?;

        let make_args = vec![format!("-j{}", self.num_cores)];
        self.run_command(source_dir, "make", &make_args, "Compiling")
            .await?;

        self.run_command(source_dir, "make", &["install".to_string()], "Installing")
            .await?;

        Ok(())
    }

    async fn build_cmake(
        &self,
        source_dir: &Path,
        prefix: &Path,
        configure_args: &[String],
    ) -> Result<()> {
        info!("Building with CMake");

        let build_dir = source_dir.join("build");
        tokio::fs::create_dir_all(&build_dir).await?;

        let prefer_ninja = Self::has_ninja();
        let generator = if prefer_ninja {
            "Ninja"
        } else {
            "Unix Makefiles"
        };

        let homebrew_prefix = crate::bottle::homebrew_prefix();
        let mut args = vec![
            "-S".to_string(),
            source_dir.display().to_string(),
            "-B".to_string(),
            build_dir.display().to_string(),
            format!("-DCMAKE_INSTALL_PREFIX={}", prefix.display()),
            format!("-G{}", generator),
            // Embed Homebrew lib dir in RPATH so installed binaries find .so files
            // without needing LD_LIBRARY_PATH.
            format!("-DCMAKE_INSTALL_RPATH={}/lib", homebrew_prefix.display()),
            "-DCMAKE_BUILD_WITH_INSTALL_RPATH=ON".to_string(),
        ];
        args.extend(configure_args.iter().cloned());

        self.run_command(source_dir, "cmake", &args, "Configuring CMake")
            .await?;

        let build_args = vec![
            "--build".to_string(),
            build_dir.display().to_string(),
            "--parallel".to_string(),
            self.num_cores.to_string(),
        ];
        self.run_command(source_dir, "cmake", &build_args, "Building")
            .await?;

        let install_args = vec!["--install".to_string(), build_dir.display().to_string()];
        self.run_command(source_dir, "cmake", &install_args, "Installing")
            .await?;

        Ok(())
    }

    async fn build_meson(
        &self,
        source_dir: &Path,
        prefix: &Path,
        configure_args: &[String],
    ) -> Result<()> {
        info!("Building with Meson");

        let build_dir = source_dir.join("build");

        let mut args = vec![
            "setup".to_string(),
            build_dir.display().to_string(),
            format!("--prefix={}", prefix.display()),
        ];
        args.extend(configure_args.iter().cloned());

        self.run_command(source_dir, "meson", &args, "Configuring Meson")
            .await?;

        let ninja_args = vec![
            "-C".to_string(),
            build_dir.display().to_string(),
            format!("-j{}", self.num_cores),
        ];
        self.run_command(source_dir, "ninja", &ninja_args, "Building")
            .await?;

        let install_args = vec![
            "-C".to_string(),
            build_dir.display().to_string(),
            "install".to_string(),
        ];
        self.run_command(source_dir, "ninja", &install_args, "Installing")
            .await?;

        Ok(())
    }

    async fn build_cargo(&self, source_dir: &Path, prefix: &Path) -> Result<()> {
        info!("Building with Cargo");

        let install_args = vec![
            "install".to_string(),
            "--path".to_string(),
            ".".to_string(),
            "--root".to_string(),
            prefix.display().to_string(),
            "--jobs".to_string(),
            self.num_cores.to_string(),
        ];
        self.run_command(source_dir, "cargo", &install_args, "Building")
            .await?;

        Ok(())
    }

    async fn build_make(&self, source_dir: &Path, prefix: &Path) -> Result<()> {
        info!("Building with Make");

        let make_args = vec![
            format!("PREFIX={}", prefix.display()),
            format!("-j{}", self.num_cores),
        ];
        self.run_command(source_dir, "make", &make_args, "Building")
            .await?;

        let install_args = vec![
            format!("PREFIX={}", prefix.display()),
            "install".to_string(),
        ];
        self.run_command(source_dir, "make", &install_args, "Installing")
            .await?;

        Ok(())
    }

    async fn run_command(
        &self,
        work_dir: &Path,
        program: &str,
        args: &[String],
        phase: &str,
    ) -> Result<()> {
        debug!("{}: {} {:?}", phase, program, args);

        let work_dir = work_dir.to_path_buf();
        let program = program.to_string();
        let args = args.to_vec();
        let use_ccache = self.use_ccache;
        let num_cores = self.num_cores;
        let phase = phase.to_string();

        tokio::task::spawn_blocking(move || {
            let mut cmd = Command::new(&program);
            cmd.current_dir(&work_dir);

            for arg in &args {
                cmd.arg(arg);
            }

            if use_ccache && (program == "gcc" || program == "clang" || program == "cc") {
                let ccache_path = Command::new("which")
                    .arg("ccache")
                    .output()
                    .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                    .unwrap_or_else(|_| "ccache".to_string());
                cmd.env("CC", format!("{} {}", ccache_path, program));
            }

            if use_ccache && (program == "g++" || program == "clang++" || program == "c++") {
                let ccache_path = Command::new("which")
                    .arg("ccache")
                    .output()
                    .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                    .unwrap_or_else(|_| "ccache".to_string());
                cmd.env("CXX", format!("{} {}", ccache_path, program));
            }

            cmd.env("MAKEFLAGS", format!("-j{}", num_cores));

            let output = cmd.output()?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                let last_lines: Vec<&str> = stderr.lines().rev().take(50).collect();
                return Err(WaxError::BuildError(format!(
                    "{} failed:\n{}",
                    phase,
                    last_lines.into_iter().rev().collect::<Vec<_>>().join("\n")
                )));
            }

            Ok(())
        })
        .await
        .map_err(|e| WaxError::BuildError(format!("Build task panicked: {}", e)))?
    }

    fn has_ninja() -> bool {
        Command::new("which")
            .arg("ninja")
            .output()
            .map(|output| output.status.success())
            .unwrap_or(false)
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}