mxsh 0.2.0

Embeddable POSIX-style shell parser and runtime
Documentation
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! Policy-oriented configuration types for embedding.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::builtin::BuiltinHost;
use crate::shell;

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ShellOptions(u32);

impl ShellOptions {
    pub const ALLEXPORT: Self = Self(shell::OPT_ALLEXPORT);
    pub const NOTIFY: Self = Self(shell::OPT_NOTIFY);
    pub const NOCLOBBER: Self = Self(shell::OPT_NOCLOBBER);
    pub const ERREXIT: Self = Self(shell::OPT_ERREXIT);
    pub const NOGLOB: Self = Self(shell::OPT_NOGLOB);
    pub const MONITOR: Self = Self(shell::OPT_MONITOR);
    pub const NOEXEC: Self = Self(shell::OPT_NOEXEC);
    pub const IGNOREEOF: Self = Self(shell::OPT_IGNOREEOF);
    pub const NOLOG: Self = Self(shell::OPT_NOLOG);
    pub const VI: Self = Self(shell::OPT_VI);
    pub const NOUNSET: Self = Self(shell::OPT_NOUNSET);
    pub const VERBOSE: Self = Self(shell::OPT_VERBOSE);
    pub const XTRACE: Self = Self(shell::OPT_XTRACE);

    pub const fn empty() -> Self {
        Self(0)
    }

    pub const fn bits(self) -> u32 {
        self.0
    }

    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    pub fn insert(&mut self, other: Self) {
        self.0 |= other.0;
    }

    pub fn remove(&mut self, other: Self) {
        self.0 &= !other.0;
    }

    pub(crate) const fn from_bits(bits: u32) -> Self {
        Self(bits)
    }
}

impl Default for ShellOptions {
    fn default() -> Self {
        Self::empty()
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ShellOptionSpec {
    pub option: ShellOptions,
    pub short_name: Option<char>,
    pub long_name: Option<String>,
}

impl ShellOptionSpec {
    pub fn new(option: ShellOptions) -> Self {
        Self {
            option,
            short_name: None,
            long_name: None,
        }
    }

    pub fn with_short_name(mut self, short_name: char) -> Self {
        self.short_name = Some(short_name);
        self
    }

    pub fn with_long_name(mut self, long_name: impl Into<String>) -> Self {
        self.long_name = Some(long_name.into());
        self
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShellOptionSchema {
    options: Vec<ShellOptionSpec>,
}

impl ShellOptionSchema {
    pub fn empty() -> Self {
        Self {
            options: Vec::new(),
        }
    }

    pub fn options(&self) -> &[ShellOptionSpec] {
        &self.options
    }

    pub fn with_option(mut self, option: ShellOptionSpec) -> Self {
        self.set_option(option);
        self
    }

    pub fn set_option(&mut self, option: ShellOptionSpec) -> Option<ShellOptionSpec> {
        let replaced = self.remove_option(option.option);
        if let Some(short_name) = option.short_name {
            self.options
                .retain(|existing| existing.short_name != Some(short_name));
        }
        if let Some(long_name) = option.long_name.as_deref() {
            self.options
                .retain(|existing| existing.long_name.as_deref() != Some(long_name));
        }
        self.options.push(option);
        replaced
    }

    pub fn remove_option(&mut self, option: ShellOptions) -> Option<ShellOptionSpec> {
        let index = self
            .options
            .iter()
            .position(|existing| existing.option == option)?;
        Some(self.options.remove(index))
    }

    pub(crate) fn find_short_option(&self, short_name: char) -> Option<&ShellOptionSpec> {
        self.options
            .iter()
            .find(|option| option.short_name == Some(short_name))
    }

    pub(crate) fn find_long_option(&self, long_name: &str) -> Option<&ShellOptionSpec> {
        self.options
            .iter()
            .find(|option| option.long_name.as_deref() == Some(long_name))
    }
}

impl Default for ShellOptionSchema {
    fn default() -> Self {
        Self::empty()
            .with_option(
                ShellOptionSpec::new(ShellOptions::ALLEXPORT)
                    .with_short_name('a')
                    .with_long_name("allexport"),
            )
            .with_option(
                ShellOptionSpec::new(ShellOptions::NOTIFY)
                    .with_short_name('b')
                    .with_long_name("notify"),
            )
            .with_option(
                ShellOptionSpec::new(ShellOptions::NOCLOBBER)
                    .with_short_name('C')
                    .with_long_name("noclobber"),
            )
            .with_option(
                ShellOptionSpec::new(ShellOptions::ERREXIT)
                    .with_short_name('e')
                    .with_long_name("errexit"),
            )
            .with_option(
                ShellOptionSpec::new(ShellOptions::NOGLOB)
                    .with_short_name('f')
                    .with_long_name("noglob"),
            )
            .with_option(
                ShellOptionSpec::new(ShellOptions::MONITOR)
                    .with_short_name('m')
                    .with_long_name("monitor"),
            )
            .with_option(
                ShellOptionSpec::new(ShellOptions::NOEXEC)
                    .with_short_name('n')
                    .with_long_name("noexec"),
            )
            .with_option(ShellOptionSpec::new(ShellOptions::IGNOREEOF).with_long_name("ignoreeof"))
            .with_option(ShellOptionSpec::new(ShellOptions::NOLOG).with_long_name("nolog"))
            .with_option(ShellOptionSpec::new(ShellOptions::VI).with_long_name("vi"))
            .with_option(
                ShellOptionSpec::new(ShellOptions::NOUNSET)
                    .with_short_name('u')
                    .with_long_name("nounset"),
            )
            .with_option(
                ShellOptionSpec::new(ShellOptions::VERBOSE)
                    .with_short_name('v')
                    .with_long_name("verbose"),
            )
            .with_option(
                ShellOptionSpec::new(ShellOptions::XTRACE)
                    .with_short_name('x')
                    .with_long_name("xtrace"),
            )
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VariableAttributes(u32);

impl VariableAttributes {
    pub const EXPORT: Self = Self(shell::VAR_EXPORT);
    pub const READONLY: Self = Self(shell::VAR_READONLY);

    pub const fn empty() -> Self {
        Self(0)
    }

    pub const fn bits(self) -> u32 {
        self.0
    }

    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    pub fn insert(&mut self, other: Self) {
        self.0 |= other.0;
    }
}

impl Default for VariableAttributes {
    fn default() -> Self {
        Self::empty()
    }
}

/// Configured language toggles for shell parsing.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ShellLanguage {
    alias_expansion: bool,
    function_definitions: bool,
}

impl ShellLanguage {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn alias_expansion_enabled(&self) -> bool {
        self.alias_expansion
    }

    pub fn function_definitions_enabled(&self) -> bool {
        self.function_definitions
    }

    pub fn with_alias_expansion_enabled(mut self, enabled: bool) -> Self {
        self.alias_expansion = enabled;
        self
    }

    pub fn with_function_definitions_enabled(mut self, enabled: bool) -> Self {
        self.function_definitions = enabled;
        self
    }
}

impl Default for ShellLanguage {
    fn default() -> Self {
        Self {
            alias_expansion: true,
            function_definitions: true,
        }
    }
}

/// Configured startup source locations for shell session initialization.
///
/// Relative user profile paths are resolved against `$HOME`. The interactive
/// env hook reads the file named by the configured environment variable.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartupSources {
    system_profile: Option<PathBuf>,
    user_profile: Option<PathBuf>,
    env_file_var: Option<String>,
}

impl StartupSources {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn system_profile(&self) -> Option<&Path> {
        self.system_profile.as_deref()
    }

    pub fn user_profile(&self) -> Option<&Path> {
        self.user_profile.as_deref()
    }

    pub fn env_file_var(&self) -> Option<&str> {
        self.env_file_var.as_deref()
    }

    pub fn with_system_profile<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.system_profile = Some(path.into());
        self
    }

    pub fn without_system_profile(mut self) -> Self {
        self.system_profile = None;
        self
    }

    pub fn with_user_profile<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.user_profile = Some(path.into());
        self
    }

    pub fn without_user_profile(mut self) -> Self {
        self.user_profile = None;
        self
    }

    pub fn with_env_file_var(mut self, env_file_var: impl Into<String>) -> Self {
        self.env_file_var = Some(env_file_var.into());
        self
    }

    pub fn without_env_file_var(mut self) -> Self {
        self.env_file_var = None;
        self
    }
}

impl Default for StartupSources {
    fn default() -> Self {
        Self {
            system_profile: Some(PathBuf::from("/etc/profile")),
            user_profile: Some(PathBuf::from(".profile")),
            env_file_var: Some("ENV".to_string()),
        }
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum StartupPolicy {
    #[default]
    None,
    PosixLoginFiles,
    InteractiveEnvHook,
    PosixLoginFilesAndInteractiveEnvHook,
}

impl StartupPolicy {
    pub(crate) const fn should_source_profile(self) -> bool {
        matches!(
            self,
            Self::PosixLoginFiles | Self::PosixLoginFilesAndInteractiveEnvHook
        )
    }

    pub(crate) const fn should_source_env(self) -> bool {
        matches!(
            self,
            Self::InteractiveEnvHook | Self::PosixLoginFilesAndInteractiveEnvHook
        )
    }
}

/// Security-sensitive execution and frontend behaviors that hosts may restrict.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ShellSecurityPolicy {
    allow_implicit_history_file: bool,
    allow_ambient_fds: bool,
    allow_background_jobs: bool,
    allow_source_builtin: bool,
    allow_process_control_builtins: bool,
    allow_path_search: bool,
    allow_redirect_target_symlinks: bool,
}

impl ShellSecurityPolicy {
    /// Allow the stock shell behavior, including ambient env/fd/file hooks.
    pub const fn permissive() -> Self {
        Self {
            allow_implicit_history_file: true,
            allow_ambient_fds: true,
            allow_background_jobs: true,
            allow_source_builtin: true,
            allow_process_control_builtins: true,
            allow_path_search: true,
            allow_redirect_target_symlinks: true,
        }
    }

    /// Disable the most common host-global and ambient hooks for shared tenancy.
    pub const fn multi_tenant() -> Self {
        Self {
            allow_implicit_history_file: false,
            allow_ambient_fds: false,
            allow_background_jobs: false,
            allow_source_builtin: false,
            allow_process_control_builtins: false,
            allow_path_search: false,
            allow_redirect_target_symlinks: false,
        }
    }

    pub const fn allow_implicit_history_file(self) -> bool {
        self.allow_implicit_history_file
    }

    pub const fn allow_ambient_fds(self) -> bool {
        self.allow_ambient_fds
    }

    pub const fn allow_background_jobs(self) -> bool {
        self.allow_background_jobs
    }

    pub const fn allow_source_builtin(self) -> bool {
        self.allow_source_builtin
    }

    pub const fn allow_process_control_builtins(self) -> bool {
        self.allow_process_control_builtins
    }

    pub const fn allow_path_search(self) -> bool {
        self.allow_path_search
    }

    pub const fn allow_redirect_target_symlinks(self) -> bool {
        self.allow_redirect_target_symlinks
    }

    pub const fn with_implicit_history_file(mut self, allow: bool) -> Self {
        self.allow_implicit_history_file = allow;
        self
    }

    pub const fn with_ambient_fds(mut self, allow: bool) -> Self {
        self.allow_ambient_fds = allow;
        self
    }

    pub const fn with_background_jobs(mut self, allow: bool) -> Self {
        self.allow_background_jobs = allow;
        self
    }

    pub const fn with_source_builtin(mut self, allow: bool) -> Self {
        self.allow_source_builtin = allow;
        self
    }

    pub const fn with_process_control_builtins(mut self, allow: bool) -> Self {
        self.allow_process_control_builtins = allow;
        self
    }

    pub const fn with_path_search(mut self, allow: bool) -> Self {
        self.allow_path_search = allow;
        self
    }

    pub const fn with_redirect_target_symlinks(mut self, allow: bool) -> Self {
        self.allow_redirect_target_symlinks = allow;
        self
    }
}

impl Default for ShellSecurityPolicy {
    fn default() -> Self {
        Self::permissive()
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShellIdentity {
    name: String,
    history_env_var: String,
    machine_payload_fd_env_var: String,
    default_history_file: String,
}

impl ShellIdentity {
    pub fn named(name: impl Into<String>) -> Self {
        let name = name.into();
        let env_prefix = name
            .chars()
            .map(|ch| {
                if ch.is_ascii_alphanumeric() {
                    ch.to_ascii_uppercase()
                } else {
                    '_'
                }
            })
            .collect::<String>();
        Self {
            history_env_var: format!("{env_prefix}_HISTORY_FILE"),
            machine_payload_fd_env_var: format!("{env_prefix}_MACHINE_PAYLOAD_FD"),
            default_history_file: format!(".{name}_history"),
            name,
        }
    }

    pub fn with_history_env_var(mut self, history_env_var: impl Into<String>) -> Self {
        self.history_env_var = history_env_var.into();
        self
    }

    pub fn with_machine_payload_fd_env_var(
        mut self,
        machine_payload_fd_env_var: impl Into<String>,
    ) -> Self {
        self.machine_payload_fd_env_var = machine_payload_fd_env_var.into();
        self
    }

    pub fn with_default_history_file(mut self, default_history_file: impl Into<String>) -> Self {
        self.default_history_file = default_history_file.into();
        self
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn history_env_var(&self) -> &str {
        &self.history_env_var
    }

    pub fn machine_payload_fd_env_var(&self) -> &str {
        &self.machine_payload_fd_env_var
    }

    pub fn default_history_file(&self) -> &str {
        &self.default_history_file
    }
}

impl Default for ShellIdentity {
    fn default() -> Self {
        Self::named("mxsh")
    }
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum BackgroundLauncher {
    #[default]
    CurrentExecutable,
    Program {
        program: String,
        args: Vec<String>,
    },
}

impl BackgroundLauncher {
    pub(crate) fn machine_command(&self, shell_name: &str) -> Option<(String, Vec<String>)> {
        match self {
            Self::CurrentExecutable => {
                let program = shell::resolve_machine_program_path(shell_name)?;
                Ok::<_, ()>((program.clone(), vec![program, "--machine".to_string()])).ok()
            }
            Self::Program { program, args } => {
                let mut argv = Vec::with_capacity(args.len() + 2);
                argv.push(program.clone());
                argv.extend(args.iter().cloned());
                argv.push("--machine".to_string());
                Some((program.clone(), argv))
            }
        }
    }
}

type CommandOverrideMatcher = dyn Fn(&[String]) -> bool + Send + Sync + 'static;
type CommandOverrideCallback =
    dyn for<'a> Fn(&mut BuiltinHost<'a>, &[String]) -> i32 + Send + Sync + 'static;

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PortableCommandOverride {
    PrintfUsage,
}

#[derive(Clone)]
pub struct CommandOverride {
    matcher: Arc<CommandOverrideMatcher>,
    handler: Arc<CommandOverrideCallback>,
    portable: Option<PortableCommandOverride>,
}

impl CommandOverride {
    pub fn new<F>(handler: F) -> Self
    where
        F: for<'a> Fn(&mut BuiltinHost<'a>, &[String]) -> i32 + Send + Sync + 'static,
    {
        Self {
            matcher: Arc::new(|_argv| true),
            handler: Arc::new(handler),
            portable: None,
        }
    }

    pub(crate) fn portable<F>(portable: PortableCommandOverride, handler: F) -> Self
    where
        F: for<'a> Fn(&mut BuiltinHost<'a>, &[String]) -> i32 + Send + Sync + 'static,
    {
        Self {
            matcher: Arc::new(|_argv| true),
            handler: Arc::new(handler),
            portable: Some(portable),
        }
    }

    pub fn with_matcher<M>(mut self, matcher: M) -> Self
    where
        M: Fn(&[String]) -> bool + Send + Sync + 'static,
    {
        self.matcher = Arc::new(matcher);
        self
    }

    pub(crate) fn matches(&self, argv: &[String]) -> bool {
        (self.matcher)(argv)
    }

    pub(crate) fn run(&self, context: &mut BuiltinHost<'_>, argv: &[String]) -> i32 {
        (self.handler)(context, argv)
    }

    pub(crate) fn portable_kind(&self) -> Option<PortableCommandOverride> {
        self.portable
    }
}

impl fmt::Debug for CommandOverride {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CommandOverride").finish_non_exhaustive()
    }
}

#[derive(Clone)]
pub struct CommandPolicy {
    unspecified_utilities: HashSet<String>,
    overrides: HashMap<String, CommandOverride>,
    command_not_found_handler: Option<Arc<CommandOverrideCallback>>,
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PortableCommandPolicy {
    unspecified_utilities: Vec<String>,
    overrides: Vec<(String, PortableCommandOverride)>,
}

impl CommandPolicy {
    pub fn empty() -> Self {
        Self {
            unspecified_utilities: HashSet::new(),
            overrides: HashMap::new(),
            command_not_found_handler: None,
        }
    }

    pub fn clear_unspecified_utilities(mut self) -> Self {
        self.unspecified_utilities.clear();
        self
    }

    pub fn add_unspecified_utility(mut self, name: impl Into<String>) -> Self {
        self.unspecified_utilities.insert(name.into());
        self
    }

    pub fn remove_unspecified_utility(mut self, name: &str) -> Self {
        self.unspecified_utilities.remove(name);
        self
    }

    pub fn register_override(
        mut self,
        name: impl Into<String>,
        command_override: CommandOverride,
    ) -> Self {
        self.overrides.insert(name.into(), command_override);
        self
    }

    pub fn remove_override(mut self, name: &str) -> Self {
        self.overrides.remove(name);
        self
    }

    pub(crate) fn is_unspecified_utility(&self, name: &str) -> bool {
        self.unspecified_utilities.contains(name)
    }

    pub(crate) fn override_for(&self, name: &str) -> Option<&CommandOverride> {
        self.overrides.get(name)
    }

    /// Register a fallback handler invoked when a command is not found in PATH.
    pub fn register_command_not_found_handler<F>(mut self, handler: F) -> Self
    where
        F: for<'a> Fn(&mut BuiltinHost<'a>, &[String]) -> i32 + Send + Sync + 'static,
    {
        self.command_not_found_handler = Some(Arc::new(handler));
        self
    }

    /// Remove the command-not-found handler.
    pub fn remove_command_not_found_handler(mut self) -> Self {
        self.command_not_found_handler = None;
        self
    }

    pub(crate) fn command_not_found_handler(&self) -> Option<&Arc<CommandOverrideCallback>> {
        self.command_not_found_handler.as_ref()
    }

    pub(crate) fn portable_background_checkpoint<I>(
        &self,
        non_portable_builtin_names: I,
    ) -> PortableCommandPolicy
    where
        I: IntoIterator<Item = String>,
    {
        let mut unspecified_utilities = self.unspecified_utilities.clone();
        unspecified_utilities.extend(non_portable_builtin_names);
        let mut overrides = Vec::with_capacity(self.overrides.len());
        for (name, command_override) in &self.overrides {
            let Some(portable) = command_override.portable_kind() else {
                unspecified_utilities.insert(name.clone());
                continue;
            };
            overrides.push((name.clone(), portable));
        }
        let mut unspecified_utilities = unspecified_utilities.into_iter().collect::<Vec<_>>();
        unspecified_utilities.sort();
        overrides.sort_by(|left, right| left.0.cmp(&right.0));
        PortableCommandPolicy {
            unspecified_utilities,
            overrides,
        }
    }

    #[cfg(any(
        feature = "frontend",
        all(test, feature = "test-support", feature = "unix-runtime")
    ))]
    pub(crate) fn from_portable_background_checkpoint(checkpoint: PortableCommandPolicy) -> Self {
        let mut policy = Self::empty();
        for name in checkpoint.unspecified_utilities {
            policy.unspecified_utilities.insert(name);
        }
        for (name, portable) in checkpoint.overrides {
            policy
                .overrides
                .insert(name, portable_command_override(portable));
        }
        policy
    }
}

impl Default for CommandPolicy {
    fn default() -> Self {
        let mut policy = Self::empty();
        for name in shell::default_unspecified_utility_names() {
            policy.unspecified_utilities.insert((*name).to_string());
        }
        policy.overrides.insert(
            "printf".to_string(),
            portable_command_override(PortableCommandOverride::PrintfUsage),
        );
        policy
    }
}

fn portable_command_override(portable: PortableCommandOverride) -> CommandOverride {
    match portable {
        PortableCommandOverride::PrintfUsage => {
            CommandOverride::portable(portable, |context, _argv| {
                let _ = context.write_stderr("printf: usage: printf [-v var] format [arguments]");
                2
            })
            .with_matcher(|argv| argv.len() == 1)
        }
    }
}

impl fmt::Debug for CommandPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut unspecified = self.unspecified_utilities.iter().collect::<Vec<_>>();
        unspecified.sort();
        let mut overrides = self.overrides.keys().collect::<Vec<_>>();
        overrides.sort();
        f.debug_struct("CommandPolicy")
            .field("unspecified_utilities", &unspecified)
            .field("override_names", &overrides)
            .finish()
    }
}