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
use eyre::Result;
use std::{collections::BTreeMap, sync::Arc};
use crate::cli::args::ToolArg;
use crate::config::Config;
use crate::env_diff::EnvMap;
use crate::shell::{ShellType, get_shell};
use crate::toolset::{InstallOptions, Toolset, ToolsetBuilder};
use crate::wildcard::wildcard_match;
use indexmap::IndexSet;
/// Print the environment for the current configuration
///
/// Evaluate the shell output to load tools and variables once, without installing
/// prompt hooks. Changing directories afterward does not recompute this environment.
/// Use `mise exec -- command` to apply it to one child process instead.
///
/// JSON, dotenv, and shell output contain actual variable values, including secrets.
/// `--redacted` selects variables marked for redaction; it does not mask their values.
/// Environment construction may install missing tools according to mise's settings.
#[derive(Debug, usage_rs::Args)]
#[usage(
visible_alias = "e",
verbatim_doc_comment,
example(
r###"eval "$(mise env -s bash)"
eval "$(mise env -s zsh)"
mise env -s fish | source
execx($(mise env -s xonsh))"###
)
)]
pub(crate) struct Env {
/// Tool(s) to include in addition to those in config, e.g. node@20
#[usage(value_name = "TOOL@VERSION")]
tool: Vec<ToolArg>,
/// Output in dotenv format
#[usage(long, short = 'D', overrides = "shell")]
dotenv: bool,
/// Output in JSON format
#[usage(long, short = 'J', overrides = "shell")]
json: bool,
/// Shell type to generate environment variables for
#[usage(long, short, overrides = "json", value_enum)]
shell: Option<ShellType>,
/// Output in JSON format with additional information (source, tool)
#[usage(long, overrides = "shell")]
json_extended: bool,
/// Only include variables marked for redaction; their values are printed unmasked
#[usage(long)]
redacted: bool,
/// Only show values of environment variables
#[usage(long)]
values: bool,
}
impl Env {
pub(crate) async fn run(self) -> Result<()> {
let mut config = Config::get().await?;
let mut ts = ToolsetBuilder::new()
.with_args(&self.tool)
.build(&config)
.await?;
let (_, missing) = ts
.install_missing_versions(&mut config, &InstallOptions::default())
.await?;
// The printed environment places the shim farms on PATH for lazy
// declarations, so evaluating it must leave working bootstrap shims
// behind: an eval'd shell has no command-not-found handler to fall
// back on (discussion #12678).
if ts.has_lazy_declarations()
&& let Err(err) = crate::shims::ensure_lazy_shims(&missing)
{
warn!("failed to create shims for lazy tools: {err:#}");
}
ts.notify_missing_versions(missing);
// Pre-compute final_env when needed by --redacted or --dotenv to
// avoid calling it twice. final_env includes the tools-only pass
// whose redactions are not in config.env_results().
let final_env = if self.redacted || self.dotenv {
Some(ts.final_env(&config).await?)
} else {
None
};
let redacted_keys = if self.redacted {
let env_results = config.env_results().await?;
let mut keys = IndexSet::new();
keys.extend(env_results.redactions.clone());
if let Some((_, ref tools_env_results)) = final_env {
keys.extend(tools_env_results.redactions.clone());
}
keys.extend(config.redaction_keys());
Some(keys)
} else {
None
};
if self.json {
self.output_json(&config, ts, &redacted_keys).await
} else if self.json_extended {
self.output_extended_json(&config, ts, &redacted_keys).await
} else if self.dotenv {
self.output_dotenv(final_env.unwrap().0, &redacted_keys)
} else if self.values {
self.output_values(&config, ts, &redacted_keys).await
} else {
self.output_shell(&config, ts, &redacted_keys).await
}
}
async fn output_json(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let mut env = ts.env_with_path(config).await?;
if let Some(keys) = redacted_keys {
env.retain(|k, _| self.should_include_key(k, keys));
}
miseprintln!("{}", serde_json::to_string_pretty(&env)?);
Ok(())
}
async fn output_extended_json(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let mut res = BTreeMap::new();
ts.env_with_path(config).await?.iter().for_each(|(k, v)| {
res.insert(k.to_string(), BTreeMap::from([("value", v.to_string())]));
});
config.env_with_sources().await?.iter().for_each(|(k, v)| {
res.insert(
k.to_string(),
BTreeMap::from([
("value", v.0.to_string()),
("source", v.1.to_string_lossy().into_owned()),
]),
);
});
let tool_map: BTreeMap<String, String> = ts
.list_all_versions(config)
.await?
.into_iter()
.map(|(b, tv)| {
(
b.id().into(),
tv.request
.source()
.path()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| "".to_string()),
)
})
.collect();
ts.env_from_tools(config)
.await
.iter()
.for_each(|(name, value, tool_id)| {
res.insert(
name.to_string(),
BTreeMap::from([
("value", value.to_string()),
("tool", tool_id.to_string()),
(
"source",
tool_map
.get(tool_id)
.cloned()
.unwrap_or_else(|| "unknown_source".to_string()),
),
]),
);
});
if let Some(keys) = redacted_keys {
res.retain(|k, _| self.should_include_key(k, keys));
}
miseprintln!("{}", serde_json::to_string_pretty(&res)?);
Ok(())
}
async fn output_shell(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let default_shell = get_shell(Some(fallback_shell())).unwrap();
let shell = get_shell(self.shell).unwrap_or(default_shell);
let (mut env, mut env_remove) = ts.env_with_path_and_removals(config).await?;
if let Some(keys) = redacted_keys {
env.retain(|k, _| self.should_include_key(k, keys));
env_remove.retain(|k| self.should_include_key(k, keys));
}
for k in env_remove {
miseprint!("{}", shell.unset_env(&k))?;
}
for (k, v) in env {
let k = k.to_string();
let v = v.to_string();
miseprint!("{}", shell.set_env(&k, &v))?;
}
Ok(())
}
fn output_dotenv(
&self,
mut env: EnvMap,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
if let Some(keys) = redacted_keys {
env.retain(|k, _| self.should_include_key(k, keys));
}
for (k, v) in env {
let k = k.to_string();
let v = v.to_string();
miseprint!("{}={}\n", k, v)?;
}
Ok(())
}
async fn output_values(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let mut env = ts.env_with_path(config).await?;
if let Some(keys) = redacted_keys {
env.retain(|k, _| self.should_include_key(k, keys));
}
for (_, v) in env {
miseprintln!("{}", v);
}
Ok(())
}
fn should_include_key(&self, key: &str, redacted_keys: &IndexSet<String>) -> bool {
redacted_keys
.iter()
.any(|pattern| wildcard_match(key, pattern))
}
}
/// The shell to emit for when there is nothing to detect from.
///
/// Detection is `MISE_SHELL`, then `SHELL`. On unix that always resolves — an unset `SHELL` falls
/// back to `sh` — so this is reached only on Windows, where PowerShell and cmd set neither and the
/// value mise would otherwise read, `COMSPEC`, names cmd.exe. mise has no cmd implementation, so
/// bash was being printed into a PowerShell session:
///
/// ```console
/// PS> mise env
/// export MY_PATH='C:\Users\me'
/// ```
///
/// pwsh is the only shell mise can emit for that a Windows user is likely to be in. It is not
/// right for a cmd user, but neither was bash, and there is no third answer available.
fn fallback_shell() -> ShellType {
match cfg!(windows) {
true => ShellType::Pwsh,
false => ShellType::Bash,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Asserted on the output rather than on the enum, which would only restate the `cfg!` above.
/// What matters is that the syntax is one the platform's shell can run.
#[test]
fn the_fallback_emits_syntax_this_platform_can_run() {
let line = fallback_shell().as_shell().set_env("K", "V");
if cfg!(windows) {
// `export K=V` is what a PowerShell session used to be handed.
assert!(!line.starts_with("export "), "{line}");
assert!(line.contains("${Env:K}"), "{line}");
} else {
assert!(line.starts_with("export "), "{line}");
}
}
}