mise 2026.9.14

Dev tools, env vars, and tasks in one CLI
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Homebrew formulae without Homebrew.
//!
//! mise installs homebrew/core bottles directly into the canonical prefix
//! (/opt/homebrew on arm64 macOS, /home/linuxbrew/.linuxbrew on Linux) —
//! fetching metadata from formulae.brew.sh, downloading bottles from
//! ghcr.io, and doing the same relocation/codesigning work `brew` does at
//! pour time. mise never shells out to brew to pour a bottle; the receipts
//! it writes are brew-compatible, so a real Homebrew sees mise-poured kegs
//! as its own.
//!
//! Formulae without a usable bottle are built from source, still without
//! Homebrew: mise provisions a mise-managed ruby and evaluates the formula
//! with its own Formula-DSL shim (see source.rs and shim.rb).
//!
//! Scope: formulae only. Casks are implemented by the sibling `brew-cask`
//! manager. Services are not implemented. homebrew/core formulae use mise's
//! direct pour path; fully-qualified third-party tap formulae use published
//! metadata or mise's metadata-only Ruby shim. mise never shells out to `brew`.

use async_trait::async_trait;
use eyre::{WrapErr, bail};
use std::collections::{HashMap, HashSet};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use super::{InstallOpts, PackageRequest, PackageState, PackageStatus, SystemPackageManager};
use crate::config::Settings;
use crate::result::Result;
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::progress_report::{ProgressIcon, SingleReport};

mod api;
mod cask;
mod elf;
mod fetch;
mod macho;
mod maintenance;
mod pour;
mod prefix;
mod relocate;
mod resolve;
mod source;
mod tag;
mod tap;

pub(crate) struct BrewManager {}
pub(crate) use cask::{
    BrewCaskManager, apply_cask_prune_plan, cask_formula_dependencies, cask_prune_plan,
};
pub(crate) use maintenance::{apply_prune_plan, default_tap_url, linked_formulae, prune_plan};

/// Resolve a canonical formula name or owner/tap/name to its installed opt path using local records.
/// Qualified names identify the rack by their final component; aliases and tap provenance are not resolved.
pub(crate) fn package_root(name: &str) -> Result<PathBuf> {
    let parts = name.split('/').collect::<Vec<_>>();
    if !matches!(parts.len(), 1 | 3)
        || parts.iter().any(|part| {
            part.is_empty()
                || part
                    .chars()
                    .any(|c| c.is_whitespace() || c.is_control() || matches!(c, ':' | '\\'))
                || !is_normal_formula_component(part)
        })
    {
        bail!(
            "invalid brew formula {name:?}; use brew:<formula> or brew:<owner>/<tap>/<formula> with normal, nonempty path components"
        );
    }
    if parts.len() == 3 && parts[0] == "homebrew" && parts[1] == "cask" {
        bail!("brew:{name}: the Homebrew cask namespace is unsupported for formula lookup");
    }
    let formula = request_formula_name(name);
    assert!(
        is_normal_formula_component(formula),
        "validated formula must normalize to exactly one normal path component"
    );
    pour::strict_package_root(formula)
        .wrap_err_with(|| format!("failed to locate installed brew:{name}"))
}

/// Require one normal path component so a formula name stays within its expected rack.
fn is_normal_formula_component(name: &str) -> bool {
    let mut components = Path::new(name).components();
    matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
}

impl BrewManager {
    pub(crate) fn new() -> Self {
        Self {}
    }

    fn split_tapped<'a>(
        &self,
        pkgs: &'a [PackageRequest],
    ) -> (Vec<&'a PackageRequest>, Vec<&'a PackageRequest>) {
        pkgs.iter().partition(|p| is_tapped_formula(&p.name))
    }

    /// Repair requested roots before resolving formula metadata or pouring kegs.
    fn repair_records(
        &self,
        pkgs: &[PackageRequest],
        opts: &InstallOpts,
    ) -> Result<Vec<PackageRequest>> {
        let mut repaired = vec![];
        for request in pkgs {
            let name = request_formula_name(&request.name);
            let state = linked_package_state(&request.version, pour::linked_state(name));
            if matches!(state, PackageState::NeedsRepair { .. })
                && pour::repair_link_record(name, opts.dry_run)?
            {
                repaired.push(request.clone());
            }
        }
        Ok(repaired)
    }

    /// Prefetch bottles concurrently, then install the closure in dependency order.
    async fn install_via_pour(&self, pkgs: &[PackageRequest], opts: &InstallOpts) -> Result<()> {
        // bottles only exist for a formula's current version — versioning is
        // expressed in the formula name itself (postgresql@17); the CLI
        // filters pinned requests out before calling
        if let Some(p) = pkgs.iter().find(|p| p.version.is_some()) {
            bail!(
                "brew bottles are only published for a formula's current version ('{p}'): \
                 pin via the formula name instead (e.g. \"brew:postgresql@17\")"
            );
        }
        let roots: Vec<String> = pkgs.iter().map(|p| p.name.clone()).collect();
        let closure = resolve::resolve_closure_with_taps(pkgs, !opts.dry_run).await?;
        for rf in &closure {
            if rf.on_request
                && !roots.contains(&rf.formula.name)
                && let Some(alias) = roots
                    .iter()
                    .find(|r| rf.formula.names().any(|n| n == r.as_str()))
            {
                warn!(
                    "'{alias}' resolves to '{}' — use the canonical name in [bootstrap.packages] \
                     so `mise bootstrap packages status` can track it",
                    rf.formula.name
                );
            }
        }
        let mut to_pour: Vec<_> = vec![];
        for rf in &closure {
            // a malformed version is an error, not "already poured"
            let pkg_version = rf.formula.pkg_version()?;
            if !pour::keg_installed(&rf.formula.name, &pkg_version) {
                to_pour.push(rf.clone());
            }
        }
        if to_pour.is_empty() {
            info!("brew: all formulae already poured");
            return Ok(());
        }
        // formulae without a usable bottle are built from source by
        // evaluating their Ruby with mise's formula shim; reject the ones
        // the builder can't handle before any work happens
        let source_builds: Vec<_> = to_pour
            .iter()
            .filter(|rf| !source::has_bottle(&rf.formula))
            .collect();
        for rf in &source_builds {
            source::check_buildable(&rf.formula)?;
        }
        if opts.dry_run {
            prefix::bootstrap(true)?;
            for rf in &to_pour {
                let origin = if rf.on_request {
                    "requested"
                } else {
                    "dependency"
                };
                if source::has_bottle(&rf.formula) {
                    miseprintln!(
                        "pour {}/{} ({origin})",
                        rf.formula.name,
                        rf.formula.pkg_version()?,
                    );
                } else {
                    miseprintln!(
                        "build {}/{} from source ({origin}, {})",
                        rf.formula.name,
                        rf.formula.pkg_version()?,
                        source::missing_bottle_reason(&rf.formula),
                    );
                }
            }
            return Ok(());
        }
        if prefix::sudo_invoking_user().is_some() {
            warn!(
                "running under sudo — poured files will be owned by root; run \
                 `mise bootstrap packages apply` without sudo instead (mise elevates itself \
                 for the one-time prefix setup)"
            );
        }
        prefix::bootstrap(false)?;
        prefix::setup_linux_runtime()?;
        if !source_builds.is_empty() {
            info!(
                "brew: building from source (no bottle for this machine): {}",
                source_builds
                    .iter()
                    .map(|rf| rf.formula.name.clone())
                    .collect::<Vec<_>>()
                    .join(", "),
            );
        }
        let mpr = MultiProgressReport::get();
        // overall [cur/total] header above the per-formula clx jobs, same as
        // tool installs (no-op when only one formula is being installed)
        mpr.init_footer(false, "install", to_pour.len());
        let pkg_versions = to_pour
            .iter()
            .map(|rf| rf.formula.pkg_version())
            .collect::<Result<Vec<_>>>()?;
        // Keep one report for both phases so every concurrent transfer has
        // independent progress, then the same row advances through pouring.
        let reports = to_pour
            .iter()
            .map(|rf| Arc::<dyn SingleReport>::from(mpr.add(&format!("brew:{}", rf.formula.name))))
            .collect::<Vec<_>>();
        let bottles = to_pour
            .iter()
            .map(|rf| {
                source::has_bottle(&rf.formula)
                    .then(|| rf.formula.bottle_files().and_then(tag::select))
                    .flatten()
                    .map(|(tag, bottle)| (tag.to_string(), bottle.clone()))
            })
            .collect::<Vec<_>>();
        // Keep each bottle's download and preparation in one bounded job so
        // extraction can begin as soon as that bottle arrives while other
        // jobs are still downloading. The existing jobs limit bounds the
        // whole pipeline rather than multiplying concurrency per phase.
        let closure = Arc::new(closure);
        let bottle_jobs = bottles
            .iter()
            .enumerate()
            .filter_map(|(index, bottle)| {
                let (tag, bottle) = bottle.as_ref()?.clone();
                let rf = to_pour[index].clone();
                let pkg_version = pkg_versions[index].clone();
                let closure = closure.clone();
                let pr = reports[index].clone();
                Some(async move {
                    let result = async {
                        let tarball = fetch::fetch_bottle(
                            &rf.formula.name,
                            &pkg_version,
                            &bottle,
                            Some(&*pr),
                        )
                        .await?;
                        tokio::task::spawn_blocking(move || {
                            pour::prepare_bottle(&rf, &tag, &bottle, &tarball, &closure, &*pr)
                        })
                        .await
                        .wrap_err("brew bottle preparation task failed")?
                    }
                    .await;
                    (index, result)
                })
            })
            .collect::<Vec<_>>();
        let mut bottle_jobs =
            fetch::concurrently(bottle_jobs, crate::jobs::normalize(Settings::get().jobs));
        let mut prepared = HashMap::new();
        let mut completed = HashSet::new();
        let mut failure = None;

        // Commit bottles and build source formulae in dependency order as
        // soon as their preparation permits. Only these short commit steps
        // mutate shared prefix links; out-of-order results wait in `prepared`.
        for (index, rf) in to_pour.iter().enumerate() {
            let pkg_version = &pkg_versions[index];
            let pr = &reports[index];
            let bottle = &bottles[index];
            let installed = match bottle {
                Some(_) => {
                    while !prepared.contains_key(&index) && failure.is_none() {
                        let Some((completed, result)) = bottle_jobs.next().await else {
                            unreachable!("every selected bottle has a preparation job");
                        };
                        match result {
                            Ok(bottle) => {
                                prepared.insert(completed, bottle);
                            }
                            Err(err) => {
                                reports[completed]
                                    .finish_with_icon("failed".to_string(), ProgressIcon::Error);
                                failure = Some((completed, err));
                            }
                        }
                    }
                    if failure.is_some() {
                        break;
                    }
                    let bottle = prepared
                        .remove(&index)
                        .expect("every selected bottle was prepared");
                    pour::install_prepared(bottle, &**pr).map(|()| pkg_version.clone())
                }
                None => {
                    if failure.is_some() {
                        break;
                    }
                    // Source builds must remain dependency ordered, but they
                    // can safely run alongside bottle download/preparation,
                    // which does not mutate active prefix links.
                    let build = source::build(rf, &closure, &**pr);
                    tokio::pin!(build);
                    let mut jobs_open = true;
                    loop {
                        tokio::select! {
                            // Record a ready bottle failure before a simultaneously
                            // completed source build can advance the install loop.
                            biased;
                            job = bottle_jobs.next(), if jobs_open => match job {
                                Some((completed, Ok(bottle))) => {
                                    prepared.insert(completed, bottle);
                                }
                                Some((completed, Err(err))) => {
                                    reports[completed].finish_with_icon(
                                        "failed".to_string(),
                                        ProgressIcon::Error,
                                    );
                                    if failure.is_none() {
                                        failure = Some((completed, err));
                                        bottle_jobs.cancel_pending();
                                    }
                                }
                                None => jobs_open = false,
                            },
                            result = &mut build => break result.map(|()| pkg_version.clone()),
                        }
                    }
                }
            };
            let version = match installed {
                Ok(version) => version,
                Err(err) => {
                    pr.finish_with_icon("failed".to_string(), ProgressIcon::Error);
                    if failure.is_none() {
                        failure = Some((index, err));
                    }
                    break;
                }
            };
            pr.finish_with_message(version);
            completed.insert(index);
            mpr.footer_inc(1);
            // A bottle may have failed while this source build was already
            // running. Let that in-flight build finish, but do not start any
            // more prefix mutations after the earlier failure.
            if failure.is_some() {
                break;
            }
        }

        // A failed download, preparation, source build, or prefix commit must
        // not start any queued work or detach already-active blocking jobs.
        // Drain only the active set so every staging guard has cleaned up
        // before returning the first error.
        if failure.is_some() {
            bottle_jobs.cancel_pending();
        }
        while let Some((index, result)) = bottle_jobs.next().await {
            if let Err(err) = result {
                reports[index].finish_with_icon("failed".to_string(), ProgressIcon::Error);
                if failure.is_none() {
                    failure = Some((index, err));
                }
            }
        }
        if let Some((failed, err)) = failure {
            for (index, pending) in reports.iter().enumerate() {
                if index != failed && !completed.contains(&index) {
                    pending.abandon();
                }
            }
            // Render the final progress state so the propagated error is not
            // masked by live jobs.
            mpr.footer_finish();
            if let Err(runtime_err) = prefix::setup_linux_runtime() {
                return Err(err.wrap_err(format!(
                    "failed to finish Linux runtime setup after a partial brew install: {runtime_err:#}"
                )));
            }
            return Err(err);
        }
        mpr.footer_finish();
        // a glibc poured in this run repoints <prefix>/lib/ld.so at it
        prefix::setup_linux_runtime()?;
        Ok(())
    }
}

#[async_trait(?Send)]
impl SystemPackageManager for BrewManager {
    fn name(&self) -> &str {
        "brew"
    }

    fn is_available(&self) -> bool {
        cfg!(all(target_os = "macos", target_arch = "aarch64"))
            || cfg!(all(
                target_os = "linux",
                any(target_arch = "x86_64", target_arch = "aarch64")
            ))
    }

    fn unavailable_reason(&self) -> String {
        "only available on arm64 macos and x86_64/arm64 linux".to_string()
    }

    fn supports_version_pins(&self) -> bool {
        false
    }

    async fn installed(&self, pkgs: &[PackageRequest]) -> Result<Vec<PackageStatus>> {
        // the prefix is the source of truth whether kegs were poured by mise
        // or by a real brew; a formula counts as installed only when its opt
        // symlink resolves to a keg — a Cellar directory without one is a
        // remnant of a failed install and must not mask a retry
        let mut statuses = Vec::with_capacity(pkgs.len());
        for req in pkgs {
            let linked_name = request_formula_name(&req.name);
            let linked = pour::linked_state(linked_name);
            let state = linked_package_state(&req.version, linked);
            statuses.push(PackageStatus {
                request: req.clone(),
                state,
            });
        }
        Ok(statuses)
    }

    async fn install(&self, pkgs: &[PackageRequest], opts: &InstallOpts) -> Result<()> {
        let repaired = self.repair_records(pkgs, opts)?;
        let remaining = pkgs
            .iter()
            .filter(|request| !repaired.contains(request))
            .cloned()
            .collect::<Vec<_>>();
        let (tapped, core) = self.split_tapped(&remaining);
        if !core.is_empty() {
            let core = core
                .into_iter()
                .map(normalize_core_request)
                .collect::<Vec<_>>();
            self.install_via_pour(&core, opts).await?;
        }
        if !tapped.is_empty() {
            let tapped = tapped.into_iter().cloned().collect::<Vec<_>>();
            self.install_via_pour(&tapped, opts).await?;
        }
        Ok(())
    }

    async fn upgrade(&self, pkgs: &[PackageRequest], opts: &InstallOpts) -> Result<()> {
        let repaired = self.repair_records(pkgs, opts)?;
        let remaining = pkgs
            .iter()
            .filter(|request| request.version.is_none() || !repaired.contains(request))
            .cloned()
            .collect::<Vec<_>>();
        let (tapped, core) = self.split_tapped(&remaining);
        if !core.is_empty() {
            let core = core
                .into_iter()
                .map(normalize_core_request)
                .collect::<Vec<_>>();
            self.install_via_pour(&core, opts).await?;
        }
        if !tapped.is_empty() {
            let tapped = tapped.into_iter().cloned().collect::<Vec<_>>();
            self.install_via_pour(&tapped, opts).await?;
        }
        Ok(())
    }
}

fn is_tapped_formula(name: &str) -> bool {
    crate::system::brew_tap_name(name).is_some()
}

fn tapped_formula_name(name: &str) -> &str {
    name.rsplit('/').next().unwrap_or(name)
}

fn core_formula_name(name: &str) -> &str {
    match split_formula_name(name) {
        Some(("homebrew", "core", formula)) => formula,
        _ => name,
    }
}

/// Return the formula name used by active records for core and tapped requests.
fn request_formula_name(name: &str) -> &str {
    if is_tapped_formula(name) {
        tapped_formula_name(name)
    } else {
        core_formula_name(name)
    }
}

/// Classify the active keg while preserving version mismatch precedence over repair.
fn linked_package_state(
    requested: &Option<String>,
    linked: Option<(String, bool)>,
) -> PackageState {
    match linked {
        // a pin matches the keg version exactly or up to its revision suffix
        // ("17.5" matches keg "17.5_1")
        Some((version, _))
            if requested.as_ref().is_some_and(|requested| {
                version != *requested && !version.starts_with(&format!("{requested}_"))
            }) =>
        {
            PackageState::VersionMismatch { installed: version }
        }
        Some((version, true)) => PackageState::NeedsRepair { installed: version },
        Some((version, false)) => PackageState::Installed { version },
        None => PackageState::Missing,
    }
}

fn normalize_core_request(req: &PackageRequest) -> PackageRequest {
    let mut req = req.clone();
    req.name = core_formula_name(&req.name).to_string();
    req
}

fn split_formula_name(name: &str) -> Option<(&str, &str, &str)> {
    let mut parts = name.split('/');
    let owner = parts.next()?;
    let tap = parts.next()?;
    let formula = parts.next()?;
    if parts.next().is_some() || owner.is_empty() || tap.is_empty() || formula.is_empty() {
        None
    } else {
        Some((owner, tap, formula))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tapped_formula_detection() {
        assert!(!is_tapped_formula("jq"));
        assert!(!is_tapped_formula("postgresql@17"));
        assert!(!is_tapped_formula("homebrew/core/jq"));
        assert!(is_tapped_formula("railwaycat/emacsmacport/emacs-mac"));
        assert_eq!(core_formula_name("homebrew/core/jq"), "jq");
        assert_eq!(core_formula_name("jq"), "jq");
        assert_eq!(
            tapped_formula_name("railwaycat/emacsmacport/emacs-mac"),
            "emacs-mac"
        );
    }

    #[test]
    fn version_mismatch_takes_precedence_over_record_repair() {
        assert_eq!(
            linked_package_state(&Some("2.0".to_string()), Some(("1.0".to_string(), true))),
            PackageState::VersionMismatch {
                installed: "1.0".to_string()
            }
        );
        assert_eq!(
            linked_package_state(&Some("1.0".to_string()), Some(("1.0_1".to_string(), true))),
            PackageState::NeedsRepair {
                installed: "1.0_1".to_string()
            }
        );
    }
}