mise 2026.9.3

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
//! 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::bail;
use std::collections::HashMap;
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};

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.aliases.contains(r))
            {
                warn!(
                    "'{alias}' is an alias of '{}' — 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);
            }
        }
        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()
            })
            .collect::<Vec<_>>();
        let downloads = bottles
            .iter()
            .enumerate()
            .filter_map(|(index, bottle)| {
                let (_, bottle) = bottle.as_ref()?;
                let name = &to_pour[index].formula.name;
                let pkg_version = &pkg_versions[index];
                let pr = &reports[index];
                Some(async move {
                    fetch::fetch_bottle(name, pkg_version, bottle, Some(&**pr))
                        .await
                        .map(|path| (index, path))
                        .map_err(|err| (index, err))
                })
            })
            .collect::<Vec<_>>();
        let mut tarballs: HashMap<usize, _> = match fetch::concurrently(
            downloads,
            crate::jobs::normalize(Settings::get().jobs),
        )
        .await
        {
            Ok(downloads) => downloads.into_iter().collect(),
            Err((failed, err)) => {
                for (index, pr) in reports.iter().enumerate() {
                    if index == failed {
                        pr.finish_with_icon("failed".to_string(), ProgressIcon::Error);
                    } else {
                        pr.abandon();
                    }
                }
                mpr.footer_finish();
                return Err(err);
            }
        };
        // Pour and build in dependency order. Only network transfers above
        // are concurrent; extraction and prefix linking mutate shared state.
        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((tag, bottle)) => {
                    let tarball = tarballs
                        .remove(&index)
                        .expect("every selected bottle was prefetched");
                    pour::pour(rf, tag, bottle, &tarball, &closure, &**pr)
                        .await
                        .map(|()| pkg_version.clone())
                }
                None => source::build(rf, &closure, &**pr)
                    .await
                    .map(|()| pkg_version.clone()),
            };
            let version = match installed {
                Ok(version) => version,
                Err(err) => {
                    pr.finish_with_icon("failed".to_string(), ProgressIcon::Error);
                    for pending in reports.iter().skip(index + 1) {
                        pending.abandon();
                    }
                    // render the final progress state so the error that
                    // propagates from here isn't masked by live jobs
                    mpr.footer_finish();
                    return Err(err);
                }
            };
            pr.finish_with_message(version);
            mpr.footer_inc(1);
        }
        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()
            }
        );
    }
}