stout-install 0.2.0

Package installation for stout
Documentation
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! Build from source support
//!
//! This module provides functionality to build formulas from source
//! when pre-built bottles are not available for the current platform.

use crate::error::{BuildError, Error, Result};
use std::path::{Path, PathBuf};
use std::process::Command;
use tracing::{debug, info, warn};

/// Build configuration
#[derive(Debug, Clone)]
pub struct BuildConfig {
    /// Source archive URL
    pub source_url: String,
    /// Expected SHA256 hash
    pub sha256: String,
    /// Formula name
    pub name: String,
    /// Version
    pub version: String,
    /// Homebrew prefix (e.g., /opt/homebrew)
    pub prefix: PathBuf,
    /// Cellar path (e.g., /opt/homebrew/Cellar)
    pub cellar: PathBuf,
    /// Build dependencies to ensure are installed
    pub build_deps: Vec<String>,
    /// Number of parallel build jobs (default: auto-detect)
    pub jobs: Option<usize>,
    /// C compiler to use
    pub cc: Option<String>,
    /// C++ compiler to use
    pub cxx: Option<String>,
}

impl BuildConfig {
    /// Get the number of parallel jobs to use
    pub fn get_jobs(&self) -> usize {
        self.jobs.unwrap_or_else(num_cpus::get)
    }
}

/// Build result
#[derive(Debug)]
pub struct BuildResult {
    /// Path to the installed package
    pub install_path: PathBuf,
}

/// Source builder for formulas
pub struct SourceBuilder {
    config: BuildConfig,
    work_dir: PathBuf,
}

impl SourceBuilder {
    /// Create a new source builder
    pub fn new(config: BuildConfig, work_dir: impl AsRef<Path>) -> Self {
        Self {
            config,
            work_dir: work_dir.as_ref().to_path_buf(),
        }
    }

    /// Build the formula from source
    pub async fn build(&self) -> Result<BuildResult> {
        info!("Building {} {} from source", self.config.name, self.config.version);

        // Create work directory
        std::fs::create_dir_all(&self.work_dir)?;

        // Download source
        let archive_path = self.download_source().await?;

        // Extract source
        let source_dir = self.extract_source(&archive_path)?;

        // Build
        let install_path = self.run_build(&source_dir)?;

        Ok(BuildResult { install_path })
    }

    /// Download the source archive
    async fn download_source(&self) -> Result<PathBuf> {
        use sha2::{Digest, Sha256};

        let archive_name = self.config.source_url
            .rsplit('/')
            .next()
            .unwrap_or("source.tar.gz");
        let archive_path = self.work_dir.join(archive_name);

        info!("Downloading source from {}", self.config.source_url);

        // Use reqwest to download
        let client = reqwest::Client::new();
        let response = client.get(&self.config.source_url)
            .send()
            .await
            .map_err(|e| Error::Build(BuildError::DownloadFailed {
                package: self.config.name.clone(),
                reason: format!("Failed to download: {}", e)
            }))?;

        if !response.status().is_success() {
            return Err(Error::Build(BuildError::DownloadFailed {
                package: self.config.name.clone(),
                reason: format!("HTTP {}", response.status())
            }));
        }

        let bytes = response.bytes()
            .await
            .map_err(|e| Error::Build(BuildError::DownloadFailed {
                package: self.config.name.clone(),
                reason: format!("Failed to read: {}", e)
            }))?;

        // Verify checksum
        let mut hasher = Sha256::new();
        hasher.update(&bytes);
        let hash = format!("{:x}", hasher.finalize());

        if hash != self.config.sha256 {
            return Err(Error::Build(BuildError::DownloadFailed {
                package: self.config.name.clone(),
                reason: format!("Checksum mismatch: expected {}, got {}", self.config.sha256, hash)
            }));
        }

        std::fs::write(&archive_path, &bytes)?;
        debug!("Downloaded and verified source archive");

        Ok(archive_path)
    }

    /// Extract the source archive
    fn extract_source(&self, archive_path: &Path) -> Result<PathBuf> {
        use flate2::read::GzDecoder;
        use tar::Archive;

        info!("Extracting source archive");

        let file = std::fs::File::open(archive_path)?;
        let decoder = GzDecoder::new(file);
        let mut archive = Archive::new(decoder);

        // Extract to work directory
        archive.unpack(&self.work_dir)?;

        // Find the extracted directory (usually name-version)
        let expected_dir = format!("{}-{}", self.config.name, self.config.version);
        let source_dir = self.work_dir.join(&expected_dir);

        if source_dir.exists() {
            return Ok(source_dir);
        }

        // Try to find any directory that was created
        for entry in std::fs::read_dir(&self.work_dir)? {
            let entry = entry?;
            if entry.file_type()?.is_dir() {
                let name = entry.file_name();
                if name.to_string_lossy() != "." && name.to_string_lossy() != ".." {
                    return Ok(entry.path());
                }
            }
        }

        Err(Error::Build(BuildError::SourceDirectoryNotFound {
            package: self.config.name.clone()
        }))
    }

    /// Run the build process
    fn run_build(&self, source_dir: &Path) -> Result<PathBuf> {
        let install_path = self.config.cellar
            .join(&self.config.name)
            .join(&self.config.version);

        info!("Building in {:?}", source_dir);
        info!("Install path: {:?}", install_path);

        // Create install directory
        std::fs::create_dir_all(&install_path)?;

        // Detect build system and run appropriate commands
        if source_dir.join("CMakeLists.txt").exists() {
            self.build_cmake(source_dir, &install_path)?;
        } else if source_dir.join("configure").exists() {
            self.build_autotools(source_dir, &install_path)?;
        } else if source_dir.join("Makefile").exists() {
            self.build_make(source_dir, &install_path)?;
        } else if source_dir.join("meson.build").exists() {
            self.build_meson(source_dir, &install_path)?;
        } else if source_dir.join("Cargo.toml").exists() {
            self.build_cargo(source_dir, &install_path)?;
        } else {
            return Err(Error::Build(BuildError::unknown_build_system(&self.config.name)));
        }

        Ok(install_path)
    }

    /// Build using autotools (configure/make/make install)
    fn build_autotools(&self, source_dir: &Path, install_path: &Path) -> Result<()> {
        info!("Using autotools build system");

        let mut configure_cmd = Command::new("./configure");
        configure_cmd
            .arg(format!("--prefix={}", install_path.display()))
            .current_dir(source_dir)
            .env("HOMEBREW_PREFIX", &self.config.prefix);

        // Set compilers if specified (with validation)
        if let Some(cc) = &self.config.cc {
            validate_compiler_path(cc)?;
            configure_cmd.env("CC", cc);
        }
        if let Some(cxx) = &self.config.cxx {
            validate_compiler_path(cxx)?;
            configure_cmd.env("CXX", cxx);
        }

        let configure_status = configure_cmd.status()?;

        if !configure_status.success() {
            return Err(Error::Build(BuildError::configure_failed(&self.config.name)));
        }

        // Make
        let mut make_cmd = Command::new("make");
        make_cmd
            .arg("-j")
            .arg(self.config.get_jobs().to_string())
            .current_dir(source_dir);

        // Set compilers for make too (with validation)
        if let Some(cc) = &self.config.cc {
            validate_compiler_path(cc)?;
            make_cmd.env("CC", cc);
        }
        if let Some(cxx) = &self.config.cxx {
            validate_compiler_path(cxx)?;
            make_cmd.env("CXX", cxx);
        }

        let make_status = make_cmd.status()?;

        if !make_status.success() {
            return Err(Error::Build(BuildError::make_failed(&self.config.name)));
        }

        // Make install
        // Use -- to prevent any argument injection - everything after -- is treated as a target
        let install_status = Command::new("make")
            .arg("install")
            .arg("--")
            .current_dir(source_dir)
            .status()?;

        if !install_status.success() {
            return Err(Error::Build(BuildError::make_install_failed(&self.config.name)));
        }

        Ok(())
    }

    /// Build using CMake
    fn build_cmake(&self, source_dir: &Path, install_path: &Path) -> Result<()> {
        info!("Using CMake build system");

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

        // Configure
        let mut cmake_cmd = Command::new("cmake");
        cmake_cmd
            .arg("..")
            .arg(format!("-DCMAKE_INSTALL_PREFIX={}", install_path.display()))
            .arg("-DCMAKE_BUILD_TYPE=Release")
            .current_dir(&build_dir);

        // Set compilers if specified (with validation)
        if let Some(cc) = &self.config.cc {
            validate_compiler_path(cc)?;
            cmake_cmd.arg(format!("-DCMAKE_C_COMPILER={}", cc));
        }
        if let Some(cxx) = &self.config.cxx {
            validate_compiler_path(cxx)?;
            cmake_cmd.arg(format!("-DCMAKE_CXX_COMPILER={}", cxx));
        }

        let cmake_status = cmake_cmd.status()?;

        if !cmake_status.success() {
            return Err(Error::Build(BuildError::CmakeConfigureFailed {
                package: self.config.name.clone()
            }));
        }

        // Build
        let build_status = Command::new("cmake")
            .arg("--build")
            .arg(".")
            .arg("-j")
            .arg(self.config.get_jobs().to_string())
            .current_dir(&build_dir)
            .status()?;

        if !build_status.success() {
            return Err(Error::Build(BuildError::CmakeBuildFailed {
                package: self.config.name.clone()
            }));
        }

        // Install
        let install_status = Command::new("cmake")
            .arg("--install")
            .arg(".")
            .current_dir(&build_dir)
            .status()?;

        if !install_status.success() {
            return Err(Error::Build(BuildError::CmakeInstallFailed {
                package: self.config.name.clone()
            }));
        }

        Ok(())
    }

    /// Build using plain Makefile
    fn build_make(&self, source_dir: &Path, install_path: &Path) -> Result<()> {
        info!("Using Makefile build system");

        // Make
        let mut make_cmd = Command::new("make");
        make_cmd
            .arg("-j")
            .arg(self.config.get_jobs().to_string())
            .current_dir(source_dir)
            .env("PREFIX", install_path);

        // Set compilers if specified (with validation)
        if let Some(cc) = &self.config.cc {
            validate_compiler_path(cc)?;
            make_cmd.env("CC", cc);
        }
        if let Some(cxx) = &self.config.cxx {
            validate_compiler_path(cxx)?;
            make_cmd.env("CXX", cxx);
        }

        let make_status = make_cmd.status()?;

        if !make_status.success() {
            return Err(Error::Build(BuildError::make_failed(&self.config.name)));
        }

        // Make install
        let install_status = Command::new("make")
            .arg("install")
            .arg(format!("PREFIX={}", install_path.display()))
            .current_dir(source_dir)
            .status()?;

        if !install_status.success() {
            return Err(Error::Build(BuildError::make_install_failed(&self.config.name)));
        }

        Ok(())
    }

    /// Build using Meson
    fn build_meson(&self, source_dir: &Path, install_path: &Path) -> Result<()> {
        info!("Using Meson build system");

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

        // Setup with compiler options
        let mut setup_cmd = Command::new("meson");
        setup_cmd
            .arg("setup")
            .arg(&build_dir)
            .arg(format!("--prefix={}", install_path.display()))
            .current_dir(source_dir);

        // Set compilers if specified (meson uses CC/CXX env vars, with validation)
        if let Some(cc) = &self.config.cc {
            validate_compiler_path(cc)?;
            setup_cmd.env("CC", cc);
        }
        if let Some(cxx) = &self.config.cxx {
            validate_compiler_path(cxx)?;
            setup_cmd.env("CXX", cxx);
        }

        let setup_status = setup_cmd.status()?;

        if !setup_status.success() {
            return Err(Error::Build(BuildError::MesonConfigureFailed {
                package: self.config.name.clone()
            }));
        }

        // Compile with parallel jobs
        let compile_status = Command::new("meson")
            .arg("compile")
            .arg("-C")
            .arg(&build_dir)
            .arg("-j")
            .arg(self.config.get_jobs().to_string())
            .status()?;

        if !compile_status.success() {
            return Err(Error::Build(BuildError::MesonCompileFailed {
                package: self.config.name.clone()
            }));
        }

        // Install
        let install_status = Command::new("meson")
            .arg("install")
            .arg("-C")
            .arg(&build_dir)
            .status()?;

        if !install_status.success() {
            return Err(Error::Build(BuildError::MesonInstallFailed {
                package: self.config.name.clone()
            }));
        }

        Ok(())
    }

    /// Build using Cargo (Rust)
    fn build_cargo(&self, source_dir: &Path, install_path: &Path) -> Result<()> {
        info!("Using Cargo build system");

        // Build release with configurable jobs
        let build_status = Command::new("cargo")
            .arg("build")
            .arg("--release")
            .arg("-j")
            .arg(self.config.get_jobs().to_string())
            .current_dir(source_dir)
            .status()?;

        if !build_status.success() {
            return Err(Error::Build(BuildError::CargoBuildFailed {
                package: self.config.name.clone()
            }));
        }

        // Install binaries
        let bin_dir = install_path.join("bin");
        std::fs::create_dir_all(&bin_dir)?;

        let release_dir = source_dir.join("target/release");
        if release_dir.exists() {
            for entry in std::fs::read_dir(&release_dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_file() && is_executable(&path) {
                    let file_name = path.file_name().unwrap();
                    // Skip common non-binary files
                    let name = file_name.to_string_lossy();
                    if !name.contains('.') && !name.starts_with("lib") {
                        let dest = bin_dir.join(file_name);
                        std::fs::copy(&path, &dest)?;
                        debug!("Installed binary: {:?}", dest);
                    }
                }
            }
        }

        Ok(())
    }
}

/// Check if a file is executable
fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    if let Ok(metadata) = path.metadata() {
        let permissions = metadata.permissions();
        permissions.mode() & 0o111 != 0
    } else {
        false
    }
}

/// Validate a compiler path for security
///
/// Ensures the path doesn't contain suspicious characters and is safe to use.
fn validate_compiler_path(path: &str) -> Result<()> {
    // Check for empty path
    if path.trim().is_empty() {
        return Err(Error::Build(BuildError::CompilerValidationFailed {
            reason: "Compiler path cannot be empty".to_string(),
        }));
    }

    // Check for path traversal attempts
    if path.contains("..") || path.contains(';') || path.contains('|') || path.contains('$') {
        return Err(Error::Build(BuildError::CompilerValidationFailed {
            reason: format!("Invalid compiler path '{}': contains suspicious characters", path),
        }));
    }

    Ok(())
}

/// Check if build from source is available for a formula
pub fn can_build_from_source(source_url: &Option<String>) -> bool {
    source_url.is_some()
}