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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
#![allow(unknown_lints)]
use crate::config::Settings;
use std::borrow::Cow;
use std::fmt::Display;

use indoc::formatdoc;

use crate::shell::{self, ActivateOptions, Shell};

#[derive(Default)]
pub(super) struct Pwsh {}

impl Pwsh {}

impl Shell for Pwsh {
    fn activate(&self, opts: ActivateOptions) -> String {
        let exe = opts.exe;
        let flags = opts.flags;

        // Single-quoted rather than double: PowerShell expands `$name` and honours backticks
        // inside `"..."`, so a mise installed under a directory holding either character was
        // invoked at a mangled path — `& "C:\...\a$b\mise.exe"` resolves to `C:\...\a\mise.exe`.
        // A path wants no expansion at all, which is exactly what `'...'` gives.
        let exe = escape_sq(&exe.to_string_lossy()).into_owned();
        let mut out = String::new();

        out.push_str(&shell::build_deactivation_script(self));

        out.push_str(&self.format_activate_prelude(&opts.prelude));
        out.push_str(&formatdoc! {r#"
            $env:MISE_SHELL = 'pwsh'
            if (-not (Test-Path -Path Env:/__MISE_ORIG_PATH)) {{
                $env:__MISE_ORIG_PATH = $env:PATH
            }}

            function mise {{
                $arguments = $args

                $previous_out_encoding = $OutputEncoding
                $previous_console_out_encoding = [Console]::OutputEncoding
                $OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)

                function _reset_output_encoding {{
                    $OutputEncoding = $previous_out_encoding
                    [Console]::OutputEncoding = $previous_console_out_encoding
                }}

                if ($arguments.count -eq 0) {{
                    if ($MyInvocation.ExpectingInput) {{
                        $input | & '{exe}'
                    }} else {{
                        & '{exe}'
                    }}
                    _reset_output_encoding
                    return
                }} elseif ($arguments -contains '-h' -or $arguments -contains '--help') {{
                    if ($MyInvocation.ExpectingInput) {{
                        $input | & '{exe}' @arguments
                    }} else {{
                        & '{exe}' @arguments
                    }}
                    _reset_output_encoding
                    return
                }}

                $command = $arguments[0]
                if ($arguments.Length -gt 1) {{
                    $remainingArgs = $arguments[1..($arguments.Length - 1)]
                }} else {{
                    $remainingArgs = @()
                }}

                switch ($command) {{
                    {{ $_ -in 'deactivate', 'shell', 'sh' }} {{
                        if ($MyInvocation.ExpectingInput) {{
                            $input | & '{exe}' $command @remainingArgs | Out-String | Invoke-Expression -ErrorAction SilentlyContinue
                        }} else {{
                            & '{exe}' $command @remainingArgs | Out-String | Invoke-Expression -ErrorAction SilentlyContinue
                        }}
                        _reset_output_encoding
                    }}
                    default {{
                        if ($MyInvocation.ExpectingInput) {{
                            $input | & '{exe}' $command @remainingArgs
                        }} else {{
                            & '{exe}' $command @remainingArgs
                        }}
                        if ($(Test-Path -Path Function:\_mise_hook)){{
                            _mise_hook
                        }}
                        _reset_output_encoding
                    }}
                }}
            }}
            "#});

        if !opts.no_hook_env {
            out.push_str(&formatdoc! {r#"

            function Global:_mise_hook {{
                if ($env:MISE_SHELL -eq "pwsh"){{
                    $status = $global:LASTEXITCODE
                    $output = & '{exe}' hook-env{flags} $args -s pwsh | Out-String
                    if ($output -and $output.Trim()) {{
                        $output | Invoke-Expression
                    }}
                    # mise hook-env will have set $LASTEXITCODE, restore previous value
                    $global:LASTEXITCODE = $status
                }}
            }}

            # Declared up front because the prompt reads it before any directory change
            # has set it, and Set-StrictMode makes reading an unset variable an error.
            $Global:__mise_pwsh_chpwd_handled = $null

            function __enable_mise_chpwd{{
                if ($PSVersionTable.PSVersion.Major -lt 7) {{
                    if ($env:MISE_PWSH_CHPWD_WARNING -ne '0') {{
                        Write-Warning "mise: chpwd functionality requires PowerShell version 7 or higher. Your current version is $($PSVersionTable.PSVersion). You can add `$env:MISE_PWSH_CHPWD_WARNING=0` to your environment to disable this warning."
                    }}
                    return
                }}
                if (-not (Test-Path variable:global:__mise_pwsh_chpwd)){{
                    $Global:__mise_pwsh_chpwd= $true
                    $_mise_chpwd_hook = [EventHandler[System.Management.Automation.LocationChangedEventArgs]] {{
                        param([object] $source, [System.Management.Automation.LocationChangedEventArgs] $eventArgs)
                        end {{
                            _mise_hook
                            # The prompt fires immediately after this handler, and its own
                            # hook-env would find the directory unchanged and early-exit. On
                            # Windows that costs a whole process (~22ms, almost entirely
                            # CreateProcess) to learn nothing. Record the directory and MISE_*
                            # state already handled so the prompt can skip it. $PWD is the new
                            # location by the time this handler runs.
                            $Global:__mise_pwsh_chpwd_handled = [PSCustomObject]@{{
                                Path = $PWD.Path
                                MiseEnv = [string]::Join("`0", [string[]]@(
                                    Get-ChildItem Env:MISE_* |
                                        Sort-Object Name |
                                        ForEach-Object {{ "$($_.Name)`0$($_.Value)" }}
                                ))
                            }}
                        }}
                    }};
                    $__mise_pwsh_previous_chpwd_function=$ExecutionContext.SessionState.InvokeCommand.LocationChangedAction;

                    if ($__mise_pwsh_previous_chpwd_function) {{
                        $ExecutionContext.SessionState.InvokeCommand.LocationChangedAction = [Delegate]::Combine($__mise_pwsh_previous_chpwd_function, $_mise_chpwd_hook)
                    }}
                    else {{
                        $ExecutionContext.SessionState.InvokeCommand.LocationChangedAction = $_mise_chpwd_hook
                    }}
                }}
            }}
            __enable_mise_chpwd
            Remove-Item -ErrorAction SilentlyContinue -Path Function:/__enable_mise_chpwd

            function __enable_mise_prompt {{
                if (-not (Test-Path variable:global:__mise_pwsh_previous_prompt_function)){{
                    $Global:__mise_pwsh_previous_prompt_function=$function:prompt
                    function global:prompt {{
                        if (Test-Path -Path Function:\_mise_hook){{
                            # Skip only when the chpwd handler already ran hook-env for this
                            # exact directory and the MISE_* state has not changed since.
                            $handled = if (Test-Path variable:global:__mise_pwsh_chpwd_handled) {{
                                $Global:__mise_pwsh_chpwd_handled
                            }} else {{
                                $null
                            }}
                            if (Test-Path variable:global:__mise_pwsh_chpwd_handled) {{
                                $Global:__mise_pwsh_chpwd_handled = $null
                            }}
                            if (
                                $null -eq $handled -or
                                $handled.Path -ne $PWD.Path -or
                                $handled.MiseEnv -ne [string]::Join("`0", [string[]]@(
                                    Get-ChildItem Env:MISE_* |
                                        Sort-Object Name |
                                        ForEach-Object {{ "$($_.Name)`0$($_.Value)" }}
                                ))
                            ) {{
                                _mise_hook
                            }}
                        }}
                        & $__mise_pwsh_previous_prompt_function
                    }}
                }}
            }}
            __enable_mise_prompt
            Remove-Item -ErrorAction SilentlyContinue -Path Function:/__enable_mise_prompt

            _mise_hook
            "#});
        }
        if Settings::get().not_found_auto_install {
            out.push_str(&formatdoc! {r#"
            if (-not (Test-Path variable:global:__mise_pwsh_command_not_found)){{
                $Global:__mise_pwsh_command_not_found= $true
                function __enable_mise_command_not_found {{
                    $_mise_pwsh_cmd_not_found_hook = [EventHandler[System.Management.Automation.CommandLookupEventArgs]] {{
                        param([object] $Name, [System.Management.Automation.CommandLookupEventArgs] $eventArgs)
                        end {{
                            # mise's own commands are not tools: `mise-foo` must not be
                            # looked up as something to install, and `deactivate` removes
                            # the wrapper function while leaving this handler registered,
                            # so `mise` itself reaches here too. bash, zsh and fish all
                            # skip these names before calling hook-not-found. `-like`
                            # rather than a prefix match: `mise2` is somebody else's tool.
                            if ($Name -eq 'mise' -or $Name -like 'mise-*') {{ return }}
                            # Only auto-install when the missing command is what the
                            # user actually typed. PSReadLine is absent in
                            # non-interactive sessions, and even when its module is
                            # loaded GetHistoryItems() throws until the line editor
                            # initializes, so treat "cannot tell" as "not typed".
                            $lastCommand = $null
                            try {{
                                $psReadLine = 'Microsoft.PowerShell.PSConsoleReadLine' -as [type]
                                if ($psReadLine) {{
                                    $history = @($psReadLine::GetHistoryItems())
                                    if ($history.Count -gt 0) {{
                                        $lastCommand = $history[-1].CommandLine
                                    }}
                                }}
                            }} catch {{ }}
                            # compare whole tokens: a substring match would fire for
                            # `mise` when the user typed `premise`, while matching only
                            # the first token would miss `... | some-missing-tool`
                            if ($lastCommand -and (($lastCommand -split '\s+') -contains $Name)) {{
                                # `hook-not-found` answers with an exit code and writes nothing to
                                # stdout, and `if (& ...)` in PowerShell tests the *output* rather
                                # than the code: it was false even when a tool had been installed,
                                # and would have been true for a failure that happened to print.
                                # bash, zsh and fish put the command straight into the condition
                                # and get its status; this is the same thing spelled for pwsh.
                                & '{exe}' hook-not-found -s pwsh -- $Name | Out-Null
                                if ($LASTEXITCODE -eq 0){{
                                    # Refresh inline rather than through `_mise_hook`:
                                    # `--no-hook-env` omits that definition while still emitting
                                    # this block, an unresolved name inside a
                                    # CommandNotFoundAction throws out of the handler, and
                                    # skipping the refresh leaves the tool just installed off
                                    # PATH for the handoff below. fish inlines `hook-env` here
                                    # for the same reason.
                                    #
                                    # The MISE_SHELL check is the one `_mise_hook` carries.
                                    # `deactivate` unsets the variable but leaves this handler
                                    # registered, and a CommandNotFoundAction runs in-process:
                                    # without the gate, a deactivated session would get mise's
                                    # PATH and `__MISE_SESSION` re-applied for good.
                                    #
                                    # `--force` because an install just happened: with
                                    # `hook_env.cache_ttl` set and an inherited `__MISE_SESSION`,
                                    # the TTL fast path returns before the check that would
                                    # notice it, and the handoff below would find nothing.
                                    if ($env:MISE_SHELL -eq "pwsh"){{
                                        $output = & '{exe}' hook-env{flags} --force -s pwsh | Out-String
                                        if ($output -and $output.Trim()) {{
                                            $output | Invoke-Expression
                                        }}
                                    }}
                                    if (Get-Command $Name -ErrorAction SilentlyContinue){{
                                        $EventArgs.Command = Get-Command $Name
                                        $EventArgs.StopSearch = $true
                                    }}
                                }}
                            }}
                        }}
                    }}
                    $current_command_not_found_function = $ExecutionContext.SessionState.InvokeCommand.CommandNotFoundAction
                    if ($current_command_not_found_function) {{
                        $ExecutionContext.SessionState.InvokeCommand.CommandNotFoundAction = [Delegate]::Combine($current_command_not_found_function, $_mise_pwsh_cmd_not_found_hook)
                    }}
                    else {{
                        $ExecutionContext.SessionState.InvokeCommand.CommandNotFoundAction = $_mise_pwsh_cmd_not_found_hook
                    }}
                }}
                __enable_mise_command_not_found
                Remove-Item -ErrorAction SilentlyContinue -Path Function:/__enable_mise_command_not_found
            }}
            "#});
        }
        out
    }

    /// `Ignore` rather than `SilentlyContinue`: both keep the error record off the screen, but
    /// only `Ignore` keeps it out of `$Error`. This block is prepended to every activation, and a
    /// session that has merely inherited `__MISE_DIFF` has neither `function:mise` nor
    /// `$global:__mise_pwsh_chpwd_handled` yet -- so those two removals used to leave a shell
    /// with two entries in `$Error` before the user had run anything. The `Env:/` removals do not
    /// error today, the Environment provider being quiet about a missing key, but the intent is
    /// the same "remove if present, never report" and resting it on a per-provider quirk is
    /// fragile.
    fn deactivate(&self) -> String {
        formatdoc! {r#"
        Remove-Item -ErrorAction Ignore function:mise
        Remove-Item -ErrorAction Ignore -Path Env:/MISE_SHELL
        Remove-Item -ErrorAction Ignore -Path Env:/__MISE_DIFF
        Remove-Item -ErrorAction Ignore -Path Env:/__MISE_SESSION
        Remove-Variable -Name __mise_pwsh_chpwd_handled -Scope Global -ErrorAction Ignore
        "#}
    }

    fn set_env(&self, k: &str, v: &str) -> String {
        let k = escape_env_name(k);
        let v = escape_sq(v);
        format!("${{Env:{k}}}='{v}'\n")
    }

    fn prepend_env(&self, k: &str, v: &str) -> String {
        let k = escape_env_name(k);
        let v = escape_sq(v);
        format!("${{Env:{k}}}='{v}'+[IO.Path]::PathSeparator+${{env:{k}}}\n")
    }

    fn unset_env(&self, k: &str) -> String {
        // A cmdlet argument rather than a variable reference, so this one is an ordinary
        // single-quoted string. `-LiteralPath` rather than `-Path` because quoting only settles
        // how PowerShell *parses* the argument -- `Remove-Item` still globs `*`, `?` and `[...]`
        // in a `-Path`, so removing a variable named `*` would take every other one with it.
        let k = escape_sq(k);
        format!("Remove-Item -ErrorAction SilentlyContinue -LiteralPath 'Env:/{k}'\n")
    }
}

impl Display for Pwsh {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "pwsh")
    }
}

/// Quote `input` for a PowerShell single-quoted string literal, without the surrounding quotes.
///
/// Inside `'...'` every character is literal except `'`, which is written by doubling it. A
/// backtick is *not* an escape there — that is only true inside `"..."` — so emitting `` `' ``
/// left the quote closing the literal, and the line failed to parse rather than carrying an
/// apostrophe. Allocates only when there is a quote to double, the way `xonsh_escape_sq` in the
/// xonsh backend does for Python's rules.
fn escape_sq(input: &str) -> Cow<'_, str> {
    if input.contains('\'') {
        Cow::Owned(input.replace('\'', "''"))
    } else {
        Cow::Borrowed(input)
    }
}

/// Quote an environment variable name for the `${Env:NAME}` form.
///
/// The braces are what let a name through that bare `$Env:NAME` cannot parse — anything holding
/// a space, say, which `[env]` in a config accepts. Inside them a backtick escapes the next
/// character, so a backtick and the closing brace are the two that have to be escaped;
/// everything else, apostrophes included, is literal.
fn escape_env_name(name: &str) -> Cow<'_, str> {
    if name.contains(['`', '}']) {
        Cow::Owned(name.replace('`', "``").replace('}', "`}"))
    } else {
        Cow::Borrowed(name)
    }
}

#[cfg(test)]
mod tests {
    use insta::assert_snapshot;
    use std::path::Path;
    use test_log::test;

    use crate::test::replace_path;

    use super::*;

    #[test]
    fn test_activate() {
        // Unset __MISE_ORIG_PATH to avoid PATH restoration logic in output
        unsafe {
            std::env::remove_var("__MISE_ORIG_PATH");
            std::env::remove_var("__MISE_DIFF");
        }

        let pwsh = Pwsh::default();
        let exe = Path::new("/some/dir/mise");
        let opts = ActivateOptions {
            exe: exe.to_path_buf(),
            flags: " --status".into(),
            no_hook_env: false,
            prelude: vec![],
        };
        assert_snapshot!(pwsh.activate(opts));
    }

    /// bash, zsh and fish all skip mise's own names before calling `hook-not-found`.
    /// The guard has to come first: past it the handler pays a full mise startup just to
    /// be told that `mise-foo` is not a tool.
    #[test]
    fn test_activate_command_not_found_skips_mise_itself() {
        let opts = ActivateOptions {
            exe: Path::new("/some/dir/mise").to_path_buf(),
            flags: " --status".into(),
            no_hook_env: false,
            prelude: vec![],
        };
        let script = Pwsh::default().activate(opts);

        let guard = script
            .find("if ($Name -eq 'mise' -or $Name -like 'mise-*') { return }")
            .expect("the command-not-found handler should skip mise's own commands");
        let call = script
            .find("hook-not-found -s pwsh")
            .expect("the command-not-found handler should still call hook-not-found");
        assert!(
            guard < call,
            "the guard has to run before the call it avoids"
        );
    }

    /// The text of the command-not-found handler, from the `hook-not-found` call to the
    /// `$EventArgs` handoff that ends the block.
    fn command_not_found_branch(script: &str) -> &str {
        let start = script
            .find("hook-not-found -s pwsh")
            .expect("activate should emit a command-not-found handler");
        let end = script[start..]
            .find("$EventArgs.StopSearch")
            .expect("the handler should hand the resolved command back");
        &script[start..start + end]
    }

    /// `--no-hook-env` drops the `_mise_hook` definition but still emits the
    /// command-not-found block, so that block has to refresh the environment on its own —
    /// otherwise the tool it just installed is not on PATH when the handoff looks for it.
    #[test]
    fn test_activate_no_hook_env_refreshes_after_auto_install() {
        let opts = ActivateOptions {
            exe: Path::new("/some/dir/mise").to_path_buf(),
            flags: " --status".into(),
            no_hook_env: true,
            prelude: vec![],
        };
        let script = Pwsh::default().activate(opts);

        assert!(!script.contains("function Global:_mise_hook"));
        assert!(script.contains("hook-not-found -s pwsh"));
        // With the definition gone, the only `hook-env` left in the script is this refresh.
        // `--force` so an inherited `__MISE_SESSION` plus `hook_env.cache_ttl` cannot make it
        // exit early on the one call that follows a fresh install.
        assert!(script.contains("hook-env --status --force -s pwsh"));
    }

    /// `deactivate` unsets `MISE_SHELL` but leaves the handler registered, and a
    /// `CommandNotFoundAction` runs in-process: an ungated refresh would re-apply mise's
    /// PATH permanently in a session the user had deactivated. `_mise_hook` carries the
    /// same check, and the refresh must not be reached through it — that indirection is
    /// what `--no-hook-env` removes.
    #[test]
    fn test_activate_command_not_found_refresh_is_gated_on_mise_shell() {
        for no_hook_env in [false, true] {
            let opts = ActivateOptions {
                exe: Path::new("/some/dir/mise").to_path_buf(),
                flags: " --status".into(),
                no_hook_env,
                prelude: vec![],
            };
            let script = Pwsh::default().activate(opts);
            let branch = command_not_found_branch(&script);

            let gate = branch
                .find(r#"if ($env:MISE_SHELL -eq "pwsh"){"#)
                .expect("the refresh should be gated on MISE_SHELL");
            let refresh = branch
                .find("hook-env --status --force -s pwsh")
                .expect("the handler should refresh the environment after an install");
            assert!(gate < refresh, "the gate has to precede what it guards");
            assert!(
                !branch.lines().any(|l| l.trim() == "_mise_hook"),
                "the refresh is inline: routing it through _mise_hook is what --no-hook-env breaks"
            );
        }
    }

    #[test]
    fn test_set_env() {
        assert_snapshot!(Pwsh::default().set_env("FOO", "1"));
    }

    #[test]
    fn test_prepend_env() {
        let pwsh = Pwsh::default();
        assert_snapshot!(replace_path(&pwsh.prepend_env("PATH", "/some/dir:/2/dir")));
    }

    /// The defect: an apostrophe closed the literal, so the line did not parse. Only `'` is
    /// special inside `'...'` -- escaping anything else would be the same mistake in reverse,
    /// turning a literal backtick or `$` into something PowerShell acts on.
    #[test]
    fn test_set_env_escapes_single_quotes_only() {
        let pwsh = Pwsh::default();
        assert_eq!(
            pwsh.set_env("HOME_ISH", r"C:\Users\O'Brien\tools"),
            "${Env:HOME_ISH}='C:\\Users\\O''Brien\\tools'\n"
        );
        // literal inside a single-quoted string, so they pass through untouched
        assert_eq!(
            pwsh.set_env("RAW", "a`b $c \"d\" e\\f"),
            "${Env:RAW}='a`b $c \"d\" e\\f'\n"
        );
        assert_eq!(pwsh.set_env("EMPTY", ""), "${Env:EMPTY}=''\n");
        // two apostrophes in one value, and one at each edge
        assert_eq!(pwsh.set_env("K", "'a'b'"), "${Env:K}='''a''b'''\n");
    }

    /// PATH is the value that matters most here: it carries the user's home directory, so an
    /// apostrophe in a Windows username reached every `hook-env`.
    #[test]
    fn test_prepend_env_escapes_single_quotes() {
        assert_eq!(
            Pwsh::default().prepend_env("PATH", r"C:\Users\O'Brien\bin"),
            "${Env:PATH}='C:\\Users\\O''Brien\\bin'+[IO.Path]::PathSeparator+${env:PATH}\n"
        );
    }

    /// `$Env:NAME` cannot parse a name with a space, which `[env]` in a config accepts; the
    /// braced form can. Inside the braces a backtick escapes the next character, so it and the
    /// closing brace are escaped and an apostrophe is left alone.
    #[test]
    fn test_env_names_use_the_braced_form() {
        let pwsh = Pwsh::default();
        assert_eq!(pwsh.set_env("MY VAR", "x"), "${Env:MY VAR}='x'\n");
        assert_eq!(pwsh.set_env("WEIRD'KEY", "x"), "${Env:WEIRD'KEY}='x'\n");
        assert_eq!(pwsh.set_env("A}B", "x"), "${Env:A`}B}='x'\n");
        assert_eq!(pwsh.set_env("A`B", "x"), "${Env:A``B}='x'\n");
    }

    /// `unset_env` builds a `-Path` argument rather than a variable reference, so it is an
    /// ordinary single-quoted string and takes the value rule, not the name rule.
    #[test]
    fn test_unset_env_quotes_the_path() {
        assert_eq!(
            Pwsh::default().unset_env("MY VAR"),
            "Remove-Item -ErrorAction SilentlyContinue -LiteralPath 'Env:/MY VAR'\n"
        );
        assert_eq!(
            Pwsh::default().unset_env("WEIRD'KEY"),
            "Remove-Item -ErrorAction SilentlyContinue -LiteralPath 'Env:/WEIRD''KEY'\n"
        );
    }

    /// Quoting settles parsing, not globbing: `Remove-Item -Path 'Env:/*'` still matches every
    /// variable and removes them all. Measured -- with `-Path` two unrelated probe variables were
    /// wiped, with `-LiteralPath` they survived and only the one named `*` went.
    #[test]
    fn test_unset_env_does_not_glob_the_name() {
        for name in ["*", "?", "PRE[FIX]"] {
            let out = Pwsh::default().unset_env(name);
            assert!(out.contains("-LiteralPath"), "{out}");
            assert!(!out.contains(" -Path "), "{out}");
            assert!(out.contains(&format!("'Env:/{name}'")), "{out}");
        }
    }

    /// A `$` is legal in a Windows directory name, and the exe path used to be interpolated
    /// into a double-quoted string, where PowerShell expanded it away.
    #[test]
    fn test_activate_invokes_the_exe_through_a_single_quoted_path() {
        unsafe {
            std::env::remove_var("__MISE_ORIG_PATH");
            std::env::remove_var("__MISE_DIFF");
        }
        let out = Pwsh::default().activate(ActivateOptions {
            exe: Path::new(r"C:\Users\me\a$b\mise.exe").to_path_buf(),
            flags: "".into(),
            no_hook_env: false,
            prelude: vec![],
        });
        assert!(out.contains(r"& 'C:\Users\me\a$b\mise.exe'"), "{out}");
        assert!(!out.contains(r#"& "C:\Users\me\a$b\mise.exe""#), "{out}");
    }

    #[test]
    fn test_unset_env() {
        assert_snapshot!(Pwsh::default().unset_env("FOO"));
    }

    /// Pins the exact text of the block `activate` prepends to every session, `-ErrorAction`
    /// values included -- see the test below for what rides on that argument.
    #[test]
    fn test_deactivate() {
        let deactivate = Pwsh::default().deactivate();
        assert_snapshot!(replace_path(&deactivate));
    }

    /// `SilentlyContinue` hides an error record but still appends it to `$Error`; only `Ignore`
    /// keeps it out. This block runs at the top of every activation, and the function and the
    /// global it removes do not exist in a session that has only inherited `__MISE_DIFF` -- so
    /// `SilentlyContinue` here left two entries in `$Error` before the user had run anything.
    #[test]
    fn test_deactivate_does_not_write_to_the_error_collection() {
        let out = Pwsh::default().deactivate();
        assert!(!out.contains("SilentlyContinue"), "{out}");
        assert!(
            out.contains("Remove-Item -ErrorAction Ignore function:mise"),
            "{out}"
        );
        assert!(
            out.contains(
                "Remove-Variable -Name __mise_pwsh_chpwd_handled -Scope Global -ErrorAction Ignore"
            ),
            "{out}"
        );
    }
}