mise 2026.9.4

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
use std::path::{Path, PathBuf};
use std::sync::Arc;

use async_trait::async_trait;
use eyre::{Result, eyre};
use indoc::formatdoc;
use mise_interactive_config::{
    BackendInfo, BackendProvider, ConfigResult, InteractiveConfig, ToolInfo, ToolProvider,
    VersionProvider,
};

use strum::IntoEnumIterator;

use crate::backend::backend_type::BackendType;
use crate::cli::args::BackendArg;
use crate::cli::version::VERSION_PLAIN;
use crate::config::config_file;
use crate::config::{Config, Settings, global_config_path};
use crate::file::display_path;
use crate::plugins::PluginType;
use crate::registry::REGISTRY;
use crate::toolset::install_state;
use crate::ui::progress_report::{ProgressIcon, SingleReport};
use crate::{env, file};

/// Tool provider that lists tools from the mise REGISTRY
struct MiseToolProvider;

impl ToolProvider for MiseToolProvider {
    fn list_tools(&self) -> Vec<ToolInfo> {
        REGISTRY
            .iter()
            .map(|(name, rt)| ToolInfo {
                name: name.to_string(),
                description: rt.description.map(|s| s.to_string()),
                aliases: rt.aliases.iter().map(|s| s.to_string()).collect(),
            })
            .collect()
    }
}

/// Version provider that fetches latest versions from backends
struct MiseVersionProvider;

#[async_trait]
impl VersionProvider for MiseVersionProvider {
    async fn latest_version(&self, tool: &str) -> Option<String> {
        // Create BackendArg from tool name
        let ba = Arc::new(BackendArg::from(tool));

        // Get the backend
        let backend = ba.backend().ok()?;

        // Get config
        let config = Config::get().await.ok()?;

        // Get the latest version
        backend.latest_version(&config, None, None).await.ok()?
    }
}

/// Backend provider that lists available backends
struct MiseBackendProvider;

impl BackendProvider for MiseBackendProvider {
    fn list_backends(&self) -> Vec<BackendInfo> {
        let mut backends = Vec::new();

        // Add built-in backend types (skip Core, Unknown, and Vfox/VfoxBackend which are for plugins)
        for backend_type in BackendType::iter() {
            let (name, description) = match backend_type {
                BackendType::Aqua => ("aqua", Some("Install tools from aquaproj registry")),
                BackendType::Asdf => ("asdf", Some("Install tools via asdf plugins")),
                BackendType::Cargo => ("cargo", Some("Install Rust packages from crates.io")),
                BackendType::Conda => ("conda", Some("Install packages from conda-forge")),
                BackendType::Dotnet => ("dotnet", Some("Install .NET tools")),
                BackendType::Forgejo => ("forgejo", Some("Install from Forgejo releases")),
                BackendType::Gem => ("gem", Some("Install Ruby gems")),
                BackendType::Github => ("github", Some("Install from GitHub releases")),
                BackendType::Gitlab => ("gitlab", Some("Install from GitLab releases")),
                BackendType::Go => ("go", Some("Install Go modules")),
                BackendType::Npm => ("npm", Some("Install npm packages globally")),
                BackendType::Packslip => {
                    ("packslip", Some("Install from a vendor's signed packslip"))
                }
                BackendType::Pipx => ("pipx", Some("Install Python CLI tools")),
                BackendType::Pkgx => ("pkgx", Some("Install pkgx pantry packages")),
                BackendType::Spm => ("spm", Some("Install Swift packages")),
                BackendType::Http => ("http", Some("Download files from HTTP URLs")),
                BackendType::S3 => ("s3", Some("Download from S3 buckets")),
                BackendType::Ubi => ("ubi", Some("Universal Binary Installer")),
                // Skip internal/meta types
                BackendType::Core
                | BackendType::Vfox
                | BackendType::VfoxBackend(_)
                | BackendType::Unknown => continue,
            };

            // Skip experimental backends unless experimental mode is enabled
            if backend_type.is_experimental() && !Settings::get().experimental {
                continue;
            }

            backends.push(BackendInfo {
                name: name.to_string(),
                description: description.map(|s| s.to_string()),
            });
        }

        // Add plugin-provided backends (vfox-backend plugins)
        for (plugin_name, plugin_type) in install_state::list_plugins().iter() {
            if *plugin_type == PluginType::VfoxBackend {
                backends.push(BackendInfo {
                    name: plugin_name.clone(),
                    description: Some(format!("Plugin-provided backend: {}", plugin_name)),
                });
            }
        }

        backends
    }
}

/// Edit mise.toml interactively
#[derive(Debug, usage_rs::Args)]
#[usage(
    verbatim_doc_comment,
    example(
        r###"mise edit             # edit mise.toml interactively
mise edit .mise.toml  # edit a specific file
mise edit -g          # edit the global config file
mise edit -y          # skip interactive editor
mise edit -n          # preview without writing"###
    )
)]
pub(crate) struct Edit {
    /// Edit the global config file (~/.config/mise/config.toml)
    // Rejected alongside a path rather than resolved in its favour: "edit the global config
    // file, namely ./custom.toml" has no meaning, and resolving it silently is how
    // `mise edit config --global` came to write a file called `config` into the current
    // directory and report success. `mise bootstrap dotfiles add` states the same collision the
    // same way, with `conflicts_with_all` between its own `--global` and `--path`.
    #[usage(long, short = 'g', conflicts = "path")]
    global: bool,
    /// Show what would be generated without writing to file
    #[usage(long, short = 'n')]
    dry_run: bool,
    /// Path to the config file to create
    #[usage(verbatim_doc_comment, value_hint = ValueHint::FilePath)]
    path: Option<PathBuf>,
    /// Path to a .tool-versions file to import tools from
    #[usage(long, short, verbatim_doc_comment, value_hint = ValueHint::FilePath)]
    tool_versions: Option<PathBuf>,
}

/// A detected tool with its source and suggested version
#[derive(Debug, Clone)]
struct DetectedTool {
    name: String,
    version: Option<String>,
    #[allow(dead_code)]
    source: String,
}

impl Edit {
    pub(super) fn is_dry_run(&self) -> bool {
        self.dry_run
    }

    pub(crate) fn new(
        global: bool,
        dry_run: bool,
        path: Option<PathBuf>,
        tool_versions: Option<PathBuf>,
    ) -> Self {
        Self {
            global,
            dry_run,
            path,
            tool_versions,
        }
    }

    pub(crate) async fn run(self) -> Result<()> {
        let path = if let Some(path) = self.path.clone() {
            path
        } else if self.global {
            global_config_path()
        } else {
            PathBuf::from(&*env::MISE_DEFAULT_CONFIG_FILENAME)
        };

        if let Some(tool_versions) = &self.tool_versions {
            // Import from .tool-versions file
            let doc = self.tool_versions(tool_versions, &path).await?;

            if self.dry_run {
                info!("would write to {}", display_path(&path));
                miseprintln!("{doc}");
            } else {
                info!("writing to {}", display_path(&path));
                write_config(&path, doc)?;
            }
        } else if self.should_run_interactive() {
            // Run interactive TOML editor
            self.interactive(&path).await?;
        } else {
            // Non-interactive: output default template
            let doc = self.default();

            if self.dry_run {
                info!("would write to {}", display_path(&path));
                miseprintln!("{doc}");
            } else {
                info!("writing to {}", display_path(&path));
                write_config(&path, doc)?;
            }
        }

        Ok(())
    }

    fn should_run_interactive(&self) -> bool {
        !Settings::get().yes && console::user_attended_stderr()
    }

    async fn interactive(&self, path: &Path) -> Result<()> {
        use crate::ui::progress_report::ProgressReport;

        let title = format!("mise {} by @jdx", *VERSION_PLAIN);

        // Show loading spinner while setting up
        let pr = ProgressReport::new("edit".into());
        pr.set_message("Loading...".into());

        // Create the interactive config editor
        let mut editor = if path.exists() {
            pr.set_message("Loading config...".into());
            InteractiveConfig::open(path.to_path_buf()).map_err(|e| eyre!(e))?
        } else {
            InteractiveConfig::new(path.to_path_buf())
        };

        editor = editor
            .title(&title)
            .dry_run(self.dry_run)
            .with_tool_provider(Box::new(MiseToolProvider))
            .with_version_provider(Box::new(MiseVersionProvider))
            .with_backend_provider(Box::new(MiseBackendProvider));

        // Auto-detect tools and add them
        pr.set_message("Detecting tools...".into());
        let detected = detect_tools();
        for tool in detected {
            let version = tool.version.unwrap_or_else(|| "latest".to_string());
            editor.add_tool(&tool.name, &version);
        }

        // Auto-detect deps providers if experimental is enabled
        if Settings::get().experimental {
            pr.set_message("Detecting deps providers...".into());
            let cwd = env::current_dir().unwrap_or_default();
            let deps_providers = crate::deps::detect_applicable_providers(&cwd);
            for provider in deps_providers {
                editor.add_deps(&provider);
            }
        }

        // Clear the loading spinner before starting the TUI
        pr.finish_with_icon("Ready".into(), ProgressIcon::Success);

        // Run the editor (now async)
        match editor.run().await {
            Ok(ConfigResult::Saved(content)) => {
                if self.dry_run {
                    info!("would write to {}", display_path(path));
                    miseprintln!("{content}");
                } else {
                    info!("saved to {}", display_path(path));
                }
            }
            Ok(ConfigResult::Cancelled) => {
                info!("cancelled");
            }
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {
                return Err(crate::request_exit(130));
            }
            Err(e) => return Err(eyre!(e)),
        }

        Ok(())
    }

    async fn tool_versions(&self, tool_versions: &Path, path: &Path) -> Result<String> {
        let to = config_file::parse_or_init(path).await?;
        let from = config_file::parse(tool_versions).await?;
        let tools = from.to_tool_request_set()?.tools;
        for (ba, tools) in tools {
            to.replace_versions(&ba, tools)?;
        }
        to.dump()
    }

    fn default(&self) -> String {
        formatdoc! {r#"
            # mise config files are hierarchical. mise will find all of the config files
            # in all parent directories and merge them together.
            # You might have a structure like:
            #
            # * ~/work/project/mise.toml   # a config file for a specific work project
            # * ~/work/mise.toml           # a config file for projects related to work
            # * ~/.config/mise/config.toml # the global config file
            # * /etc/mise/config.toml      # the system config file
            #
            # This setup allows you to define default versions and configuration across
            # all projects but override them for specific projects.

            # [env]
            # NODE_ENV = "development"
            # _.file = ".env"                # load vars from a dotenv file
            # _.path = "./node_modules/.bin" # add a directory to PATH

            # [tools]
            # node = "22"
            # python = "3.12"
            # go = "latest"
        "#}
    }
}

/// Write a generated config, creating its directory if it is not there yet.
///
/// `--global` resolves to `~/.config/mise/config.toml`, and nothing creates that directory
/// ahead of time. Every other writer of that same file goes through `MiseToml::save`, which
/// has always created the parent first — these two commands reached `file::write` directly, so
/// on a fresh install, where `mise generate config --global` is the first thing to touch the
/// path, they failed with a bare "no such file or directory" and wrote nothing.
///
/// A bare relative name (`mise edit foo.toml`) gives an empty parent, which `create_dir_all`
/// treats as a no-op.
fn write_config(path: &Path, doc: String) -> Result<()> {
    if let Some(parent) = path.parent() {
        file::create_dir_all(parent)?;
    }
    file::write(path, doc)
}

// ============================================================================
// Tool detection
// ============================================================================

fn detect_tools() -> Vec<DetectedTool> {
    let cwd = env::current_dir().unwrap_or_default();
    let mut detected = Vec::new();
    let mut seen_tools = std::collections::HashSet::new();

    // Scan registry for tools with detect files
    for (name, tool) in REGISTRY.iter() {
        if tool.detect.is_empty() {
            continue;
        }

        for detect_file in tool.detect.iter() {
            let path = cwd.join(detect_file);
            if path.exists() && !seen_tools.contains(name) {
                let version = extract_version(name, &path);
                detected.push(DetectedTool {
                    name: name.to_string(),
                    version,
                    source: detect_file.to_string(),
                });
                seen_tools.insert(name);
                break; // Only detect once per tool
            }
        }
    }

    detected
}

fn extract_version(tool: &str, path: &Path) -> Option<String> {
    let filename = path.file_name()?.to_str()?;
    let content = file::read_to_string(path).ok()?;

    match (tool, filename) {
        // Node.js version from package.json engines
        ("node", "package.json") => {
            let json: serde_json::Value = serde_json::from_str(&content).ok()?;
            json.get("engines")
                .and_then(|e| e.get("node"))
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
        }
        // Python version from pyproject.toml
        ("python", "pyproject.toml") => {
            let doc: toml::Value = toml::from_str(&content).ok()?;
            doc.get("project")
                .and_then(|p| p.get("requires-python"))
                .and_then(|v| v.as_str())
                .map(|s| {
                    s.trim_start_matches(|c: char| !c.is_ascii_digit())
                        .to_string()
                })
                .filter(|s| !s.is_empty())
        }
        // Go version from go.mod
        ("go", "go.mod") => content
            .lines()
            .find(|line| line.starts_with("go "))
            .map(|line| line.trim_start_matches("go ").trim().to_string()),
        // Version files (simple text content)
        (_, f) if f.starts_with('.') && f.ends_with("-version") => {
            let v = content.trim().to_string();
            if v.is_empty() { None } else { Some(v) }
        }
        (_, ".nvmrc") => {
            let v = content.trim().to_string();
            if v.is_empty() { None } else { Some(v) }
        }
        _ => None,
    }
}