summaryrefslogtreecommitdiffstats
path: root/src/shell/history/job.rs
blob: 5c73f4df72ac7ba1925a0373140a76682536ebbd (plain) (blame)
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
use crate::shell::prelude::*;

pub struct Job {}

impl Job {
    pub fn new(
        cmdline: &str,
        env: Env,
        pts: &pty_process::Pts,
        event_w: crate::shell::event::Writer,
    ) -> Result<Self> {
        let (child, fh) = spawn_command(cmdline, &env, pts)?;
        let state = std::sync::Arc::new(std::sync::Mutex::new(
            State::Running((0, 0)),
        ));
        tokio::spawn(Self::task(
            child,
            fh,
            std::sync::Arc::clone(&state),
            env,
            event_w,
        ));
        Ok(Self {
            state,
            start_time,
            start_instant,
        })
    }

    pub fn start_time(&self) -> &time::OffsetDateTime {
        &self.start_time
    }

    pub fn start_instant(&self) -> &std::time::Instant {
        &self.start_instant
    }

    pub fn with_state<T>(&self, f: impl FnOnce(&State) -> T) -> T {
        let state = self.state.lock().unwrap();
        f(&state)
    }

    pub fn with_state_mut<T>(&self, f: impl FnOnce(&mut State) -> T) -> T {
        let mut state = self.state.lock().unwrap();
        f(&mut state)
    }

    pub fn lock_state(&self) -> std::sync::MutexGuard<State> {
        self.state.lock().unwrap()
    }

    pub fn running(&self) -> bool {
        self.with_state(|state| matches!(state, State::Running(..)))
    }

    pub fn set_span(&self, new_span: (usize, usize)) {
        self.with_state_mut(|state| {
            if let State::Running(span) = state {
                *span = new_span;
            }
        });
    }
}