Debian Codegraph @

rust/chg/src/uihandler.rs

raw
1 // Copyright 2018 Yuya Nishihara <[email protected]>
2 //
3 // This software may be used and distributed according to the terms of the
4 // GNU General Public License version 2 or any later version.
5
6 use std::io;
7 use std::os::unix::io::AsRawFd;
8 use std::os::unix::process::ExitStatusExt;
9 use std::process::Stdio;
10
11 use async_trait::async_trait;
12 use tokio;
13 use tokio::process::Child;
14 use tokio::process::ChildStdin;
15 use tokio::process::Command;
16
17 use crate::message::CommandSpec;
18 use crate::procutil;
19
20 /// Callback to process shell command requests received from server.
21 #[async_trait]
22 pub trait SystemHandler {
23 type PagerStdin: AsRawFd;
24
25 /// Handles pager command request.
26 ///
27 /// Returns the pipe to be attached to the server if the pager is spawned.
28 async fn spawn_pager(
29 &mut self,
30 spec: &CommandSpec,
31 ) -> io::Result<Self::PagerStdin>;
32
33 /// Handles system command request.
34 ///
35 /// Returns command exit code (positive) or signal number (negative).
36 async fn run_system(&mut self, spec: &CommandSpec) -> io::Result<i32>;
37 }
38
39 /// Default cHg implementation to process requests received from server.
40 pub struct ChgUiHandler {
41 pager: Option<Child>,
42 }
43
44 impl ChgUiHandler {
45 pub fn new() -> ChgUiHandler {
46 ChgUiHandler { pager: None }
47 }
48
49 /// Waits until the pager process exits.
50 pub async fn wait_pager(&mut self) -> io::Result<()> {
51 if let Some(p) = self.pager.take() {
52 p.await?;
53 }
54 Ok(())
55 }
56 }
57
58 #[async_trait]
59 impl SystemHandler for ChgUiHandler {
60 type PagerStdin = ChildStdin;
61
62 async fn spawn_pager(
63 &mut self,
64 spec: &CommandSpec,
65 ) -> io::Result<Self::PagerStdin> {
66 let mut pager =
67 new_shell_command(&spec).stdin(Stdio::piped()).spawn()?;
68 let pin = pager.stdin.take().unwrap();
69 procutil::set_blocking_fd(pin.as_raw_fd())?;
70 // TODO: if pager exits, notify the server with SIGPIPE immediately.
71 // otherwise the server won't get SIGPIPE if it does not write
72 // anything. (issue5278)
73 // kill(peerpid, SIGPIPE);
74 self.pager = Some(pager);
75 Ok(pin)
76 }
77
78 async fn run_system(&mut self, spec: &CommandSpec) -> io::Result<i32> {
79 let status = new_shell_command(&spec).spawn()?.await?;
80 let code = status
81 .code()
82 .or_else(|| status.signal().map(|n| -n))
83 .expect("either exit code or signal should be set");
84 Ok(code)
85 }
86 }
87
88 fn new_shell_command(spec: &CommandSpec) -> Command {
89 let mut builder = Command::new("/bin/sh");
90 builder
91 .arg("-c")
92 .arg(&spec.command)
93 .current_dir(&spec.current_dir)
94 .env_clear()
95 .envs(spec.envs.iter().cloned());
96 builder
97 }