mise 2026.9.9

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
//! Early initialization settings from .miserc.toml
//!
//! This module handles loading settings that need to be known before the main
//! config files are parsed. The primary use case is setting MISE_ENV, which
//! determines which environment-specific config files (e.g., mise.development.toml)
//! to load.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use eyre::Result;
use path_absolutize::Absolutize;
use tera::Context;

use crate::config::config_file::diagnostic::toml_parse_error;
use crate::config::settings::MisercSettings;
use crate::dirs;
use crate::env;
use crate::file;
use crate::tera::{
    TeraEngine, contains_template_syntax, get_miserc_tera, render_str, take_tera_accessed_files,
};

static MISERC: OnceLock<MisercSettings> = OnceLock::new();
static INVOCATION_CWD: OnceLock<Option<PathBuf>> = OnceLock::new();

/// Load operator-owned environment selection without discovering project files.
pub(crate) fn init_global_only() {
    let mut settings = MisercSettings::default();
    // A broken file must not block credentials or discard another valid layer.
    for path in [
        env::MISE_SYSTEM_CONFIG_DIR.join("miserc.toml"),
        dirs::CONFIG.join("miserc.toml"),
    ] {
        if let Ok(layer) = load_miserc_files(vec![path]) {
            merge_settings(&mut settings, layer);
        }
    }
    let _ = MISERC.set(settings);
    let _ = take_tera_accessed_files();
}

/// Initialize miserc settings by loading .miserc.toml files.
/// This must be called early in the initialization process, before
/// MISE_ENV or other early settings are accessed.
pub(crate) fn init() -> Result<()> {
    let _ = invocation_cwd();
    let settings = load_miserc_settings()?;
    let _ = MISERC.set(settings);
    // Discard any files tracked via hash_file/file_size/last_modified during miserc
    // template rendering. Those filters write to TERA_ACCESSED_FILES (used by hook-env
    // for file-watch detection), but miserc is loaded before config and should not
    // contribute to that list.
    let _ = take_tera_accessed_files();
    Ok(())
}

/// The working directory mise was invoked from, before settings such as `cd`
/// change the process working directory.
pub(crate) fn invocation_cwd() -> Option<&'static Path> {
    INVOCATION_CWD
        .get_or_init(|| std::env::current_dir().ok())
        .as_deref()
}

/// Get the loaded miserc settings, or default if not initialized.
pub(crate) fn get() -> &'static MisercSettings {
    if super::Settings::is_package_query() {
        static QUERY_MISERC: std::sync::LazyLock<MisercSettings> =
            std::sync::LazyLock::new(MisercSettings::default);
        return &QUERY_MISERC;
    }
    MISERC.get_or_init(|| {
        let settings = load_miserc_settings().unwrap_or_default();
        let _ = take_tera_accessed_files();
        settings
    })
}

/// Get the MISE_ENV value from miserc, if set.
pub(crate) fn get_env() -> Option<&'static Vec<String>> {
    get().env.as_ref()
}

/// Get the auto_env value from miserc, if set.
pub(crate) fn get_auto_env() -> Option<bool> {
    get().auto_env
}

/// Get the env_conf_d value from miserc, if set.
pub(crate) fn get_env_conf_d() -> Option<bool> {
    get().env_conf_d
}

/// Get the ceiling_paths value from miserc, if set.
pub(crate) fn get_ceiling_paths() -> Option<&'static BTreeSet<PathBuf>> {
    get().ceiling_paths.as_ref()
}

/// Get the ignored_config_paths value from miserc, if set.
pub(crate) fn get_ignored_config_paths() -> Option<&'static BTreeSet<PathBuf>> {
    get().ignored_config_paths.as_ref()
}

/// Get the override_config_filenames value from miserc, if set.
pub(crate) fn get_override_config_filenames() -> Option<&'static Vec<String>> {
    get().override_config_filenames.as_ref()
}

/// Get the override_tool_versions_filenames value from miserc, if set.
pub(crate) fn get_override_tool_versions_filenames() -> Option<&'static Vec<String>> {
    get().override_tool_versions_filenames.as_ref()
}

/// Render any Tera template syntax in miserc content before TOML parsing.
/// Uses a minimal context that is safe to build before the main config is loaded:
/// - `env` – OS environment variables (from PRISTINE_ENV)
/// - `config_root` – directory containing the miserc file
/// - `cwd` – current working directory
/// - `xdg_*` – XDG base directory variables
///
/// Notably absent (would cause circular initialization):
/// - `mise_env` (depends on miserc itself)
/// - `exec()` (depends on Settings, which are not yet loaded)
/// - `read_file()` (not registered — needs per-file directory context not set up at this stage)
fn render_miserc_template(
    tera: &mut Option<TeraEngine>,
    content: &str,
    config_root: &Path,
) -> String {
    if !contains_template_syntax(content) {
        return content.to_string();
    }
    // Lazily initialize the Tera instance — only pay the clone cost if at least one file
    // contains template syntax.
    let tera = tera.get_or_insert_with(get_miserc_tera);
    let mut context = Context::new();
    context.insert("env", &*env::PRISTINE_ENV);
    context.insert("config_root", config_root);
    match std::env::current_dir() {
        Ok(dir) => context.insert("cwd", &dir),
        Err(e) => {
            debug!("miserc template: could not determine cwd, `cwd` will be unavailable: {e}")
        }
    };
    context.insert("xdg_cache_home", &*env::XDG_CACHE_HOME);
    context.insert("xdg_config_home", &*env::XDG_CONFIG_HOME);
    context.insert("xdg_data_home", &*env::XDG_DATA_HOME);
    context.insert("xdg_state_home", &*env::XDG_STATE_HOME);
    match render_str(tera, content, &context) {
        Ok(rendered) => rendered,
        Err(e) => {
            warn!("Failed to render template in miserc: {e}");
            content.to_string()
        }
    }
}

/// Load and merge all miserc settings files.
/// Precedence (highest to lowest):
/// 1. Local .miserc.toml and .config/miserc.toml (closest to cwd wins)
/// 2. Global ~/.config/mise/miserc.toml
/// 3. System /etc/mise/miserc.toml
fn load_miserc_settings() -> Result<MisercSettings> {
    load_miserc_files(find_miserc_files())
}

fn load_miserc_files(files: Vec<PathBuf>) -> Result<MisercSettings> {
    let mut merged = MisercSettings::default();
    // Load in reverse precedence order so later loads override earlier ones
    // Tera is initialized lazily inside render_miserc_template — only paid if a file
    // actually contains template syntax. Shared across all files to avoid redundant clones.
    let mut tera: Option<TeraEngine> = None;

    for path in files.into_iter().rev() {
        if let Ok(content) = file::read_to_string(&path) {
            let config_root = path.parent().unwrap_or(Path::new("."));
            let content = render_miserc_template(&mut tera, &content, config_root);
            let mut settings = toml::from_str::<MisercSettings>(&content)
                .map_err(|e| toml_parse_error(&e, &content, &path))?;
            resolve_ignored_config_paths(&mut settings, config_root);
            merge_settings(&mut merged, settings);
        }
    }

    Ok(merged)
}

fn resolve_ignored_config_paths(settings: &mut MisercSettings, config_root: &Path) {
    let Some(paths) = settings.ignored_config_paths.take() else {
        return;
    };
    settings.ignored_config_paths = Some(
        paths
            .into_iter()
            .map(|path| resolve_ignored_config_path(path, config_root))
            .collect(),
    );
}

pub(crate) fn resolve_ignored_config_path(path: PathBuf, relative_to: &Path) -> PathBuf {
    file::replace_path(path)
        .absolutize_from(relative_to)
        .into_owned()
}

/// Merge source settings into target, where source values override target.
fn merge_settings(target: &mut MisercSettings, source: MisercSettings) {
    if source.env.is_some() {
        target.env = source.env;
    }
    if source.auto_env.is_some() {
        target.auto_env = source.auto_env;
    }
    if source.env_conf_d.is_some() {
        target.env_conf_d = source.env_conf_d;
    }
    if source.ceiling_paths.is_some() {
        target.ceiling_paths = source.ceiling_paths;
    }
    if source.ignored_config_paths.is_some() {
        target.ignored_config_paths = source.ignored_config_paths;
    }
    if source.override_config_filenames.is_some() {
        target.override_config_filenames = source.override_config_filenames;
    }
    if source.override_tool_versions_filenames.is_some() {
        target.override_tool_versions_filenames = source.override_tool_versions_filenames;
    }
}

/// Find all miserc.toml files in order of precedence (highest first).
fn find_miserc_files() -> Vec<PathBuf> {
    let mut files = Vec::new();
    let ceiling_paths = env_ceiling_paths();

    // Local hierarchy: .miserc.toml and .config/miserc.toml in cwd and ancestors
    // Use raw std::env to avoid depending on our lazy statics
    if let Ok(cwd) = std::env::current_dir() {
        // Walk up the directory tree, but stop at home or root
        let home: &Path = &dirs::HOME;
        for dir in cwd.ancestors() {
            if ceiling_paths.contains(dir) {
                break;
            }
            let path = dir.join(".miserc.toml");
            if path.is_file() {
                files.push(path);
            }
            // Stop at home directory to avoid searching too far
            if dir == home || dir.parent().is_none() {
                break;
            }
            let path = dir.join(".config").join("miserc.toml");
            if path.is_file() {
                files.push(path);
            }
        }
    }

    // Global: ~/.config/mise/miserc.toml
    let global_path = dirs::CONFIG.join("miserc.toml");
    if global_path.is_file() {
        files.push(global_path);
    }

    // System: /etc/mise/miserc.toml (or MISE_SYSTEM_CONFIG_DIR)
    let system_dir = env::MISE_SYSTEM_CONFIG_DIR.clone();
    let system_path = system_dir.join("miserc.toml");
    if system_path.is_file() {
        files.push(system_path);
    }

    files
}

fn env_ceiling_paths() -> BTreeSet<PathBuf> {
    // Only the raw env var is available here; env::MISE_CEILING_PATHS also
    // falls back to .miserc, which would recurse during .miserc discovery.
    env::var_os("MISE_CEILING_PATHS")
        .map(|v| {
            std::env::split_paths(&v)
                .filter(|p| !p.as_os_str().is_empty())
                .map(file::replace_path)
                .collect()
        })
        .unwrap_or_default()
}

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

    #[test]
    fn test_merge_settings() {
        let mut target = MisercSettings {
            env: Some(vec!["base".to_string()]),
            env_conf_d: Some(false),
            ..Default::default()
        };

        let source = MisercSettings {
            env: Some(vec!["override".to_string()]),
            env_conf_d: Some(true),
            ..Default::default()
        };

        merge_settings(&mut target, source);

        assert_eq!(target.env, Some(vec!["override".to_string()]));
        assert_eq!(target.env_conf_d, Some(true));
    }

    #[test]
    fn test_parse_miserc() {
        let content = r#"
env = ["development", "local"]
env_conf_d = true
ceiling_paths = ["/home/user"]
"#;
        let settings: MisercSettings = toml::from_str(content).unwrap();
        assert_eq!(
            settings.env,
            Some(vec!["development".to_string(), "local".to_string()])
        );
        assert_eq!(settings.env_conf_d, Some(true));
        assert!(settings.ceiling_paths.is_some());
    }

    #[test]
    fn test_resolve_ignored_config_paths_from_declaring_file() {
        let mut settings = MisercSettings {
            ignored_config_paths: Some(BTreeSet::from([PathBuf::from("../vendor/./**/mise.toml")])),
            ..Default::default()
        };

        resolve_ignored_config_paths(&mut settings, Path::new("/workspaces/vcs/.config"));

        assert_eq!(
            settings.ignored_config_paths,
            Some(BTreeSet::from([PathBuf::from(
                "/workspaces/vcs/vendor/**/mise.toml"
            )]))
        );
    }

    #[test]
    fn test_render_miserc_template_no_op() {
        // Content without template syntax should pass through unchanged
        let mut tera = None;
        let content = r#"env = ["development"]"#;
        let result = render_miserc_template(&mut tera, content, Path::new("/home/user"));
        assert_eq!(result, content);
    }

    #[test]
    fn test_render_miserc_template_env_var() {
        // env.HOME should expand using PRISTINE_ENV — the same source the template uses
        let mut tera = None;
        let home = env::PRISTINE_ENV
            .get("HOME")
            .cloned()
            .unwrap_or_else(|| "/root".to_string());
        let content = r#"ceiling_paths = ["{{ env.HOME }}"]"#;
        let result = render_miserc_template(&mut tera, content, Path::new("/some/dir"));
        assert!(
            result.contains(&home),
            "Expected HOME ({home}) in rendered output, got: {result}"
        );
    }

    #[test]
    fn test_render_miserc_template_config_root() {
        let mut tera = None;
        let config_root = Path::new("/my/project");
        let content = r#"ceiling_paths = ["{{ config_root }}"]"#;
        let result = render_miserc_template(&mut tera, content, config_root);
        assert!(
            result.contains("/my/project"),
            "Expected config_root in rendered output, got: {result}"
        );
    }

    #[test]
    fn test_render_miserc_template_os_function() {
        let mut tera = None;
        let content = r#"env = ["{{ os() }}"]"#;
        let result = render_miserc_template(&mut tera, content, Path::new("/some/dir"));
        // os() should return a non-empty string (linux, macos, windows, etc.)
        assert!(
            !result.contains("{{ os() }}"),
            "Template was not rendered: {result}"
        );
    }

    #[test]
    fn test_render_miserc_template_invalid_falls_back() {
        // An invalid template should fall back to the original content (with a warning)
        let mut tera = None;
        let content = r#"ceiling_paths = ["{{ undefined_function_xyz() }}"]"#;
        let result = render_miserc_template(&mut tera, content, Path::new("/some/dir"));
        // Should return original content unchanged on error
        assert_eq!(result, content);
    }
}