yash-env 0.13.2

Yash shell execution environment interface
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2021 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! This crate defines the shell execution environment.
//!
//! A shell execution environment, [`Env`], is a collection of data that may
//! affect or be affected by the execution of commands. The environment consists
//! of application-managed parts and system-managed parts. Application-managed
//! parts are implemented in pure Rust in this crate. Many application-managed
//! parts like [function]s and [variable]s can be manipulated independently of
//! interactions with the underlying system. System-managed parts, on the other
//! hand, depend on the underlying system. Attributes like the working directory
//! and umask are managed by the system to be accessed only by interaction with
//! the system interface.
//!
//! Traits declared in the [`system`] module define the interface to the
//! system-managed parts of the environment.
//! [`RealSystem`] provides an implementation for them that interacts with
//! the underlying system. [`VirtualSystem`] simulates a system for testing
//! purposes.
//!
//! We assume that the shell process is single-threaded. This means that the
//! shell process itself must not create threads, and all interactions with the
//! system must be performed in the main thread. Using any items in this crate
//! in a multi-threaded context is not supported and may cause undefined
//! behavior. This prerequisite still applies even when a [`VirtualSystem`]
//! simulates concurrent execution of multiple processes, which run as
//! asynchronous tasks.

use self::alias::AliasSet;
use self::any::DataSet;
use self::builtin::Builtin;
use self::function::FunctionSet;
use self::io::Fd;
use self::job::JobList;
use self::job::Pid;
use self::job::ProcessResult;
use self::job::ProcessState;
use self::option::On;
use self::option::OptionSet;
use self::option::{AllExport, ErrExit, Interactive, Monitor};
use self::semantics::Divert;
use self::semantics::ExitStatus;
use self::stack::Frame;
use self::stack::Stack;
use self::system::CaughtSignals;
use self::system::Clock;
use self::system::Close;
use self::system::Concurrent;
use self::system::Dup;
use self::system::Errno;
use self::system::Fstat;
use self::system::GetCwd;
use self::system::GetPid;
use self::system::Isatty;
use self::system::Mode;
use self::system::OfdAccess;
use self::system::Open;
use self::system::OpenFlag;
use self::system::Select;
#[allow(deprecated)]
pub use self::system::SharedSystem;
use self::system::Sigaction;
use self::system::Sigmask;
use self::system::SignalList;
use self::system::Signals;
#[allow(deprecated)]
pub use self::system::System;
use self::system::TcSetPgrp;
use self::system::Wait;
#[cfg(unix)]
pub use self::system::real::RealSystem;
pub use self::system::r#virtual::VirtualSystem;
use self::trap::TrapSet;
use self::variable::PPID;
use self::variable::Scope;
use self::variable::VariableRefMut;
use self::variable::VariableSet;
use std::collections::HashMap;
use std::fmt::Debug;
use std::ops::ControlFlow::{self, Break, Continue};
use std::rc::Rc;
use std::task::Context;
use std::task::Poll;
use std::task::Waker;
pub use unix_path as path;
pub use unix_str as str;

/// Whole shell execution environment.
///
/// The shell execution environment consists of application-managed parts and
/// system-managed parts. Application-managed parts are directly implemented in
/// the `Env` instance. System-managed parts are managed by a [`Concurrent`]
/// wrapping a `System` instance.
///
/// # Cloning
///
/// `Env::clone` effectively clones the application-managed parts of the
/// environment. Since [`Concurrent`] is reference-counted, you will not get a
/// deep copy of the system-managed parts. See also
/// [`clone_with_system`](Self::clone_with_system).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Env<S> {
    /// Aliases defined in the environment
    pub aliases: AliasSet,

    /// Name of the current shell executable or shell script
    ///
    /// Special parameter `0` expands to this value.
    pub arg0: String,

    /// Built-in utilities available in the environment
    pub builtins: HashMap<&'static str, Builtin<S>>,

    /// Exit status of the last executed command
    pub exit_status: ExitStatus,

    /// Functions defined in the environment
    pub functions: FunctionSet<S>,

    /// Jobs managed in the environment
    pub jobs: JobList,

    /// Process group ID of the main shell process
    pub main_pgid: Pid,

    /// Process ID of the main shell process
    ///
    /// This PID represents the value of the `$` special parameter.
    pub main_pid: Pid,

    /// Shell option settings
    pub options: OptionSet,

    /// Runtime execution context stack
    pub stack: Stack,

    /// Traps defined in the environment
    pub traps: TrapSet,

    /// File descriptor to the controlling terminal
    ///
    /// [`get_tty`](Self::get_tty) saves a file descriptor in this variable, so
    /// you don't have to prepare it yourself.
    pub tty: Option<Fd>,

    /// Variables and positional parameters defined in the environment
    pub variables: VariableSet,

    /// Abstract container that can store any type-erased data
    pub any: DataSet,

    /// Interface to the system-managed parts of the environment
    pub system: Rc<Concurrent<S>>,
}

impl<S> Env<S> {
    /// Creates a new environment with the given system.
    ///
    /// Members of the new environments are default-constructed except that:
    /// - `main_pgid` is initialized as `system.getpgrp()`
    /// - `main_pid` is initialized as `system.getpid()`
    /// - `system` is initialized as `Rc::new(Concurrent::new(system))`
    #[must_use]
    pub fn with_system(system: S) -> Self
    where
        S: GetPid,
    {
        Env {
            aliases: Default::default(),
            arg0: Default::default(),
            builtins: Default::default(),
            exit_status: Default::default(),
            functions: Default::default(),
            jobs: Default::default(),
            main_pgid: system.getpgrp(),
            main_pid: system.getpid(),
            options: Default::default(),
            stack: Default::default(),
            traps: Default::default(),
            tty: Default::default(),
            variables: Default::default(),
            any: Default::default(),
            system: Rc::new(Concurrent::new(system)),
        }
    }

    /// Clones this environment.
    ///
    /// The application-managed parts of the environment are cloned normally.
    /// The system-managed parts are replaced with the provided `System`
    /// instance.
    #[must_use]
    pub fn clone_with_system(&self, system: S) -> Self {
        Env {
            aliases: self.aliases.clone(),
            arg0: self.arg0.clone(),
            builtins: self.builtins.clone(),
            exit_status: self.exit_status,
            functions: self.functions.clone(),
            jobs: self.jobs.clone(),
            main_pgid: self.main_pgid,
            main_pid: self.main_pid,
            options: self.options,
            stack: self.stack.clone(),
            traps: self.traps.clone(),
            tty: self.tty,
            variables: self.variables.clone(),
            any: self.any.clone(),
            system: Rc::new(Concurrent::new(system)),
        }
    }
}

impl Env<VirtualSystem> {
    /// Creates a new environment with a default-constructed [`VirtualSystem`].
    #[must_use]
    pub fn new_virtual() -> Self {
        Env::with_system(VirtualSystem::default())
    }
}

impl<S> Env<S> {
    /// Initializes default variables.
    ///
    /// This function assigns the following variables to `self`:
    ///
    /// - `IFS=' \t\n'`
    /// - `OPTIND=1`
    /// - `PS1='$ '`
    /// - `PS2='> '`
    /// - `PS4='+ '`
    /// - `PPID=(parent process ID)`
    /// - `PWD=(current working directory)` (See [`Env::prepare_pwd`])
    ///
    /// This function ignores any errors that may occur.
    ///
    /// TODO: PS1 should be set to `"# "` for root users.
    pub fn init_variables(&mut self)
    where
        S: Fstat + GetCwd + GetPid,
    {
        self.variables.init();

        self.variables
            .get_or_new(PPID, Scope::Global)
            .assign(self.system.getppid().to_string(), None)
            .ok();

        self.prepare_pwd().ok();
    }

    /// Waits for some signals to be caught in the current process.
    ///
    /// Returns an array of signals caught.
    ///
    /// This function is a wrapper for [`Concurrent::wait_for_signals`].
    /// Before the function returns, it passes the results to
    /// [`TrapSet::catch_signal`] so the trap set can remember the signals
    /// caught to be handled later.
    pub async fn wait_for_signals(&mut self) -> Rc<SignalList> {
        let result = self.system.wait_for_signals().await;
        for signal in result.iter().copied() {
            self.traps.catch_signal(signal);
        }
        result
    }

    /// Waits for a specific signal to be caught in the current process.
    ///
    /// This function calls [`wait_for_signals`](Self::wait_for_signals)
    /// repeatedly until it returns results containing the specified `signal`.
    pub async fn wait_for_signal(&mut self, signal: signal::Number) {
        while !self.wait_for_signals().await.contains(&signal) {}
    }

    /// Returns signals that have been caught.
    ///
    /// This function is similar to
    /// [`wait_for_signals`](Self::wait_for_signals) but does not wait for
    /// signals to be caught. Instead, it only checks if any signals have been
    /// caught but not yet consumed in the [`Concurrent`] instance. If no
    /// signals have been caught, it returns `None`.
    pub fn poll_signals(&mut self) -> Option<Rc<SignalList>>
    where
        S: Select + CaughtSignals + Clock,
    {
        let system = Rc::clone(&self.system);

        let mut future = std::pin::pin!(self.wait_for_signals());
        let mut context = Context::from_waker(Waker::noop());

        // Check if the result is ready before peeking the system
        if let Poll::Ready(signals) = future.as_mut().poll(&mut context) {
            return Some(signals);
        }

        // Peek to handle any pending signals
        system.peek();

        // Check again if the result is ready after peeking
        if let Poll::Ready(signals) = future.poll(&mut context) {
            return Some(signals);
        }

        None
    }

    /// Whether error messages should be printed in color
    ///
    /// This function decides whether messages printed to the standard error
    /// should contain ANSI color escape sequences. The result is true only if
    /// the standard error is a terminal.
    ///
    /// The current implementation simply checks if the standard error is a
    /// terminal. This will be changed in the future to support user
    /// configuration.
    #[must_use]
    fn should_print_error_in_color(&self) -> bool
    where
        S: Isatty,
    {
        // TODO Enable color depending on user config (force/auto/never)
        // TODO Check if the terminal really supports color (needs terminfo)
        self.system.isatty(Fd::STDERR)
    }

    /// Returns a file descriptor to the controlling terminal.
    ///
    /// This function returns `self.tty` if it is `Some` FD. Otherwise, it
    /// opens `/dev/tty` and saves the new FD to `self.tty` before returning it.
    pub async fn get_tty(&mut self) -> Result<Fd, Errno>
    where
        S: Open + Dup + Close,
    {
        if let Some(fd) = self.tty {
            return Ok(fd);
        }

        let first_fd = {
            // POSIX.1-2024 Job control specifications are written in the
            // assumption that a job-control shell may not have a control
            // terminal. The shell should not make an arbitrary terminal its
            // control terminal, so we open /dev/tty with NoCtty.
            let mut result = self
                .system
                .open(
                    c"/dev/tty",
                    OfdAccess::ReadWrite,
                    OpenFlag::CloseOnExec | OpenFlag::NoCtty,
                    Mode::empty(),
                )
                .await;
            if result == Err(Errno::EINVAL) {
                // However, some systems do not support NoCtty. In that case,
                // we open /dev/tty without NoCtty.
                result = self
                    .system
                    .open(
                        c"/dev/tty",
                        OfdAccess::ReadWrite,
                        OpenFlag::CloseOnExec.into(),
                        Mode::empty(),
                    )
                    .await;
            }
            result?
        };

        let final_fd = io::move_fd_internal(&self.system, first_fd);
        self.tty = final_fd.ok();
        final_fd
    }

    /// Ensures the shell is in the foreground.
    ///
    /// If the current process belongs to the same process group as the session
    /// leader, this function forces the current process to be in the foreground
    /// by calling [`job::tcsetpgrp_with_block`]. Otherwise, this function
    /// suspends the process until it is resumed in the foreground by another
    /// job-controlling process (see [`job::tcsetpgrp_without_block`]).
    ///
    /// This function returns an error if the process does not have a controlling
    /// terminal, that is, [`get_tty`](Self::get_tty) returns `Err(_)`.
    ///
    /// # Note on POSIX conformance
    ///
    /// This function implements part of the initialization of the job-control
    /// shell. POSIX says that the shell should bring itself into the foreground
    /// only if it is started as the controlling process (that is, the session
    /// leader) for the terminal session. However, this function also brings the
    /// shell into the foreground if the shell is in the same process group as
    /// the session leader because it is unlikely that there is another
    /// job-controlling process that can bring the shell into the foreground.
    pub async fn ensure_foreground(&mut self) -> Result<(), Errno>
    where
        S: Open + Dup + Close + GetPid + Signals + Sigmask + Sigaction + TcSetPgrp,
    {
        let fd = self.get_tty().await?;

        if self.system.getsid(Pid(0)) == Ok(self.main_pgid) {
            job::tcsetpgrp_with_block(&self.system, fd, self.main_pgid).await
        } else {
            job::tcsetpgrp_without_block(&self.system, fd, self.main_pgid).await
        }
    }

    /// Waits for a subshell to terminate, suspend, or resume.
    ///
    /// This function waits for a subshell to change its execution state. The
    /// `target` parameter specifies which child to wait for:
    ///
    /// - `-1`: any child
    /// - `0`: any child in the same process group as the current process
    /// - `pid`: the child whose process ID is `pid`
    /// - `-pgid`: any child in the process group whose process group ID is `pgid`
    ///
    /// When [`self.system.wait`](system::Wait::wait) returned a new state of the
    /// target, it is sent to `self.jobs` ([`JobList::update_status`]) before
    /// being returned from this function.
    ///
    /// If there is no matching target, this function returns
    /// `Err(Errno::ECHILD)`.
    ///
    /// If the target subshell is not job-controlled, you may want to use
    /// [`wait_for_subshell_to_finish`](Self::wait_for_subshell_to_finish)
    /// instead.
    pub async fn wait_for_subshell(&mut self, target: Pid) -> Result<(Pid, ProcessState), Errno>
    where
        S: Signals + Sigmask + Sigaction + Wait,
    {
        // We need to set the internal disposition before calling `wait` so we don't
        // miss any `SIGCHLD` that may arrive between `wait` and `wait_for_signal`.
        self.traps
            .enable_internal_disposition_for_sigchld(&self.system)
            .await?;

        loop {
            if let Some((pid, state)) = self.system.wait(target)? {
                self.jobs.update_status(pid, state);
                return Ok((pid, state));
            }
            self.wait_for_signal(S::SIGCHLD).await;
        }
    }

    /// Wait for a subshell to terminate or suspend.
    ///
    /// This function is similar to
    /// [`wait_for_subshell`](Self::wait_for_subshell), but returns only when
    /// the target is finished (either exited or killed by a signal) or
    /// suspended.
    pub async fn wait_for_subshell_to_halt(
        &mut self,
        target: Pid,
    ) -> Result<(Pid, ProcessResult), Errno>
    where
        S: Signals + Sigmask + Sigaction + Wait,
    {
        loop {
            let (pid, state) = self.wait_for_subshell(target).await?;
            if let ProcessState::Halted(result) = state {
                return Ok((pid, result));
            }
        }
    }

    /// Wait for a subshell to terminate.
    ///
    /// This function is similar to
    /// [`wait_for_subshell`](Self::wait_for_subshell), but returns only when
    /// the target is finished (either exited or killed by a signal).
    ///
    /// Returns the process ID of the awaited process and its exit status.
    pub async fn wait_for_subshell_to_finish(
        &mut self,
        target: Pid,
    ) -> Result<(Pid, ExitStatus), Errno>
    where
        S: Signals + Sigmask + Sigaction + Wait,
    {
        loop {
            let (pid, result) = self.wait_for_subshell_to_halt(target).await?;
            if !result.is_stopped() {
                return Ok((pid, result.into()));
            }
        }
    }

    /// Applies all job status updates to jobs in `self.jobs`.
    ///
    /// This function calls [`self.system.wait`](system::Wait::wait) repeatedly until
    /// all status updates available are applied to `self.jobs`
    /// ([`JobList::update_status`]).
    ///
    /// Note that updates of subshells that are not managed in `self.jobs` are
    /// lost when you call this function.
    pub fn update_all_subshell_statuses(&mut self)
    where
        S: Wait,
    {
        while let Ok(Some((pid, state))) = self.system.wait(Pid::ALL) {
            self.jobs.update_status(pid, state);
        }
    }
}

impl<S> Env<S> {
    /// Tests whether the current environment is an interactive shell.
    ///
    /// This function returns true if and only if:
    ///
    /// - the [`Interactive`] option is `On` in `self.options`, and
    /// - the current context is not in a subshell (no `Frame::Subshell` in `self.stack`).
    #[must_use]
    pub fn is_interactive(&self) -> bool {
        self.options.get(Interactive) == On && !self.stack.contains(&Frame::Subshell)
    }

    /// Tests whether the shell is performing job control.
    ///
    /// This function returns true if and only if:
    ///
    /// - the [`Monitor`] option is `On` in `self.options`, and
    /// - the current context is not in a subshell (no `Frame::Subshell` in `self.stack`).
    #[must_use]
    pub fn controls_jobs(&self) -> bool {
        self.options.get(Monitor) == On && !self.stack.contains(&Frame::Subshell)
    }

    /// Get an existing variable or create a new one.
    ///
    /// This method is a thin wrapper around [`VariableSet::get_or_new`].
    /// If the [`AllExport`] option is on, the variable is
    /// [exported](VariableRefMut::export) before being returned from the
    /// method.
    ///
    /// You should prefer using this method over [`VariableSet::get_or_new`] to
    /// make sure that the [`AllExport`] option is applied.
    pub fn get_or_create_variable<N>(&mut self, name: N, scope: Scope) -> VariableRefMut<'_>
    where
        N: Into<String>,
    {
        let mut variable = self.variables.get_or_new(name, scope);
        if self.options.get(AllExport) == On {
            variable.export(true);
        }
        variable
    }

    /// Tests whether the [`ErrExit`] option is applicable in the current context.
    ///
    /// This function returns true if and only if:
    /// - the [`ErrExit`] option is on, and
    /// - the current stack has no [`Condition`] frame.
    ///
    /// [`Condition`]: Frame::Condition
    pub fn errexit_is_applicable(&self) -> bool {
        self.options.get(ErrExit) == On && !self.stack.contains(&Frame::Condition)
    }

    /// Returns a `Divert` if the shell should exit because of the [`ErrExit`]
    /// shell option.
    ///
    /// The function returns `Break(Divert::Exit(None))` if the [`errexit`
    /// option is applicable](Self::errexit_is_applicable) and the current
    /// `self.exit_status` is non-zero. Otherwise, it returns `Continue(())`.
    pub fn apply_errexit(&self) -> ControlFlow<Divert> {
        if !self.exit_status.is_successful() && self.errexit_is_applicable() {
            Break(Divert::Exit(None))
        } else {
            Continue(())
        }
    }

    /// Updates the exit status from the given result.
    ///
    /// If `result` is a `Break(divert)` where `divert.exit_status()` is `Some`
    /// exit status, this function sets `self.exit_status` to that exit status.
    pub fn apply_result(&mut self, result: crate::semantics::Result) {
        match result {
            Continue(_) => {}
            Break(divert) => {
                if let Some(exit_status) = divert.exit_status() {
                    self.exit_status = exit_status;
                }
            }
        }
    }
}

pub mod alias;
pub mod any;
pub mod builtin;
pub mod decl_util;
pub mod function;
pub mod input;
pub mod io;
pub mod job;
pub mod option;
pub mod parser;
pub mod prompt;
pub mod pwd;
pub mod semantics;
pub mod signal;
pub mod source;
pub mod stack;
pub mod subshell;
pub mod system;
pub mod trap;
pub mod variable;
pub mod waker;

#[cfg(any(test, feature = "yash-executor"))]
mod executor_helper;
#[cfg(any(test, feature = "test-helper"))]
pub mod test_helper;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::MIN_INTERNAL_FD;
    use crate::job::Job;
    use crate::source::Location;
    use crate::subshell::Subshell;
    use crate::system::r#virtual::Inode;
    use crate::system::r#virtual::SIGCHLD;
    use crate::test_helper::in_virtual_system;
    use crate::trap::Action;
    use futures_executor::LocalPool;
    use futures_util::FutureExt as _;
    use std::cell::RefCell;

    #[test]
    fn wait_for_signal_remembers_signal_in_trap_set() {
        in_virtual_system(|mut env, state| async move {
            env.traps
                .set_action(
                    &env.system,
                    SIGCHLD,
                    Action::Command("".into()),
                    Location::dummy(""),
                    false,
                )
                .await
                .unwrap();
            {
                let mut state = state.borrow_mut();
                let process = state.processes.get_mut(&env.main_pid).unwrap();
                assert!(process.blocked_signals().contains(&SIGCHLD));
                let _ = process.raise_signal(SIGCHLD);
            }
            env.wait_for_signal(SIGCHLD).await;

            let trap_state = env.traps.get_state(SIGCHLD).0.unwrap();
            assert!(trap_state.pending);
        })
    }

    fn poll_signals_env() -> (Env<VirtualSystem>, VirtualSystem) {
        let system = VirtualSystem::new();
        let mut env = Env::with_system(system.clone());
        env.traps
            .set_action(
                &env.system,
                SIGCHLD,
                Action::Command("".into()),
                Location::dummy(""),
                false,
            )
            .now_or_never()
            .unwrap()
            .unwrap();
        (env, system)
    }

    #[test]
    fn poll_signals_none() {
        let mut env = poll_signals_env().0;
        let result = env.poll_signals();
        assert_eq!(result, None);
    }

    #[test]
    fn poll_signals_some() {
        let (mut env, system) = poll_signals_env();
        {
            let mut state = system.state.borrow_mut();
            let process = state.processes.get_mut(&system.process_id).unwrap();
            assert!(process.blocked_signals().contains(&SIGCHLD));
            let _ = process.raise_signal(SIGCHLD);
        }

        let result = env.poll_signals().unwrap();
        assert_eq!(result.as_slice(), [SIGCHLD]);
    }

    #[test]
    fn get_tty_opens_tty() {
        let system = VirtualSystem::new();
        let tty = Rc::new(RefCell::new(Inode::new([])));
        system
            .state
            .borrow_mut()
            .file_system
            .save("/dev/tty", Rc::clone(&tty))
            .unwrap();
        let mut env = Env::with_system(system.clone());

        let fd = env.get_tty().now_or_never().unwrap().unwrap();
        assert!(
            fd >= MIN_INTERNAL_FD,
            "get_tty returned {fd}, which should be >= {MIN_INTERNAL_FD}"
        );
        system
            .with_open_file_description(fd, |ofd| {
                assert!(Rc::ptr_eq(ofd.inode(), &tty));
                Ok(())
            })
            .unwrap();

        system.state.borrow_mut().file_system = Default::default();

        // get_tty returns cached FD
        let fd = env.get_tty().now_or_never().unwrap().unwrap();
        system
            .with_open_file_description(fd, |ofd| {
                assert!(Rc::ptr_eq(ofd.inode(), &tty));
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn start_and_wait_for_subshell() {
        in_virtual_system(|mut env, _state| async move {
            let subshell = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(42) })
            });
            let (pid, _) = subshell.start(&mut env).await.unwrap();
            let result = env.wait_for_subshell(pid).await;
            assert_eq!(result, Ok((pid, ProcessState::exited(42))));
        });
    }

    #[test]
    fn start_and_wait_for_subshell_with_job_list() {
        in_virtual_system(|mut env, _state| async move {
            let subshell = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(42) })
            });
            let (pid, _) = subshell.start(&mut env).await.unwrap();
            let mut job = Job::new(pid);
            job.name = "my job".to_string();
            let job_index = env.jobs.add(job.clone());
            let result = env.wait_for_subshell(pid).await;
            assert_eq!(result, Ok((pid, ProcessState::exited(42))));
            job.state = ProcessState::exited(42);
            assert_eq!(env.jobs[job_index], job);
        });
    }

    #[test]
    fn wait_for_subshell_no_subshell() {
        let system = VirtualSystem::new();
        let mut executor = LocalPool::new();
        system.state.borrow_mut().executor = Some(Rc::new(executor.spawner()));
        let mut env = Env::with_system(system);
        executor.run_until(async move {
            let result = env.wait_for_subshell(Pid::ALL).await;
            assert_eq!(result, Err(Errno::ECHILD));
        });
    }

    #[test]
    fn update_all_subshell_statuses_without_subshells() {
        let mut env = Env::new_virtual();
        env.update_all_subshell_statuses();
    }

    #[test]
    fn update_all_subshell_statuses_with_subshells() {
        let system = VirtualSystem::new();
        let mut executor = futures_executor::LocalPool::new();
        system.state.borrow_mut().executor = Some(Rc::new(executor.spawner()));

        let mut env = Env::with_system(system);

        let [job_1, job_2, job_3] = executor.run_until(async {
            // Run a subshell.
            let subshell_1 = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(12) })
            });
            let (pid_1, _) = subshell_1.start(&mut env).await.unwrap();

            // Run another subshell.
            let subshell_2 = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(35) })
            });
            let (pid_2, _) = subshell_2.start(&mut env).await.unwrap();

            // This one will never finish.
            let subshell_3 =
                Subshell::new(|_env, _job_control| Box::pin(futures_util::future::pending()));
            let (pid_3, _) = subshell_3.start(&mut env).await.unwrap();

            // Yet another subshell. We don't make this into a job.
            let subshell_4 = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(100) })
            });
            let (_pid_4, _) = subshell_4.start(&mut env).await.unwrap();

            // Create jobs.
            let job_1 = env.jobs.add(Job::new(pid_1));
            let job_2 = env.jobs.add(Job::new(pid_2));
            let job_3 = env.jobs.add(Job::new(pid_3));
            [job_1, job_2, job_3]
        });

        // Let the jobs (except job_3) finish.
        executor.run_until_stalled();

        // We're not yet updated.
        assert_eq!(env.jobs[job_1].state, ProcessState::Running);
        assert_eq!(env.jobs[job_2].state, ProcessState::Running);
        assert_eq!(env.jobs[job_3].state, ProcessState::Running);

        env.update_all_subshell_statuses();

        // Now we have the results.
        // TODO assert_eq!(env.jobs[job_1].state, ProcessState::Exited(ExitStatus(12)));
        // TODO assert_eq!(env.jobs[job_2].state, ProcessState::Exited(ExitStatus(35)));
        assert_eq!(env.jobs[job_3].state, ProcessState::Running);
    }

    #[test]
    fn get_or_create_variable_with_all_export_off() {
        let mut env = Env::new_virtual();
        let mut a = env.get_or_create_variable("a", Scope::Global);
        assert!(!a.is_exported);
        a.export(true);
        let a = env.get_or_create_variable("a", Scope::Global);
        assert!(a.is_exported);
    }

    #[test]
    fn get_or_create_variable_with_all_export_on() {
        let mut env = Env::new_virtual();
        env.options.set(AllExport, On);
        let mut a = env.get_or_create_variable("a", Scope::Global);
        assert!(a.is_exported);
        a.export(false);
        let a = env.get_or_create_variable("a", Scope::Global);
        assert!(a.is_exported);
    }

    #[test]
    fn errexit_on() {
        let mut env = Env::new_virtual();
        env.exit_status = ExitStatus::FAILURE;
        env.options.set(ErrExit, On);
        assert_eq!(env.apply_errexit(), Break(Divert::Exit(None)));
    }

    #[test]
    fn errexit_with_zero_exit_status() {
        let mut env = Env::new_virtual();
        env.options.set(ErrExit, On);
        assert_eq!(env.apply_errexit(), Continue(()));
    }

    #[test]
    fn errexit_in_condition() {
        let mut env = Env::new_virtual();
        env.exit_status = ExitStatus::FAILURE;
        env.options.set(ErrExit, On);
        let env = env.push_frame(Frame::Condition);
        assert_eq!(env.apply_errexit(), Continue(()));
    }

    #[test]
    fn errexit_off() {
        let mut env = Env::new_virtual();
        env.exit_status = ExitStatus::FAILURE;
        assert_eq!(env.apply_errexit(), Continue(()));
    }

    #[test]
    fn apply_result_with_continue() {
        let mut env = Env::new_virtual();
        env.apply_result(Continue(()));
        assert_eq!(env.exit_status, ExitStatus::default());
    }

    #[test]
    fn apply_result_with_divert_without_exit_status() {
        let mut env = Env::new_virtual();
        env.apply_result(Break(Divert::Exit(None)));
        assert_eq!(env.exit_status, ExitStatus::default());
    }

    #[test]
    fn apply_result_with_divert_with_exit_status() {
        let mut env = Env::new_virtual();
        env.apply_result(Break(Divert::Exit(Some(ExitStatus(67)))));
        assert_eq!(env.exit_status, ExitStatus(67));
    }
}