nu_command/platform/
kill.rs

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
use nu_engine::command_prelude::*;
use std::process::{Command as CommandSys, Stdio};

#[derive(Clone)]
pub struct Kill;

impl Command for Kill {
    fn name(&self) -> &str {
        "kill"
    }

    fn description(&self) -> &str {
        "Kill a process using the process id."
    }

    fn signature(&self) -> Signature {
        let signature = Signature::build("kill")
            .input_output_types(vec![(Type::Nothing, Type::Any)])
            .allow_variants_without_examples(true)
            .required(
                "pid",
                SyntaxShape::Int,
                "Process id of process that is to be killed.",
            )
            .rest("rest", SyntaxShape::Int, "Rest of processes to kill.")
            .switch("force", "forcefully kill the process", Some('f'))
            .switch("quiet", "won't print anything to the console", Some('q'))
            .category(Category::Platform);

        if cfg!(windows) {
            return signature;
        }

        signature.named(
            "signal",
            SyntaxShape::Int,
            "signal decimal number to be sent instead of the default 15 (unsupported on Windows)",
            Some('s'),
        )
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["stop", "end", "close"]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        _input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let pid: i64 = call.req(engine_state, stack, 0)?;
        let rest: Vec<i64> = call.rest(engine_state, stack, 1)?;
        let force: bool = call.has_flag(engine_state, stack, "force")?;
        let signal: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "signal")?;
        let quiet: bool = call.has_flag(engine_state, stack, "quiet")?;

        let mut cmd = if cfg!(windows) {
            let mut cmd = CommandSys::new("taskkill");

            if force {
                cmd.arg("/F");
            }

            cmd.arg("/PID");
            cmd.arg(pid.to_string());

            // each pid must written as `/PID 0` otherwise
            // taskkill will act as `killall` unix command
            for id in &rest {
                cmd.arg("/PID");
                cmd.arg(id.to_string());
            }

            cmd
        } else {
            let mut cmd = CommandSys::new("kill");
            if force {
                if let Some(Spanned {
                    item: _,
                    span: signal_span,
                }) = signal
                {
                    return Err(ShellError::IncompatibleParameters {
                        left_message: "force".to_string(),
                        left_span: call.get_flag_span(stack, "force").ok_or_else(|| {
                            ShellError::GenericError {
                                error: "Flag error".into(),
                                msg: "flag force not found".into(),
                                span: Some(call.head),
                                help: None,
                                inner: vec![],
                            }
                        })?,
                        right_message: "signal".to_string(),
                        right_span: Span::merge(
                            call.get_flag_span(stack, "signal").ok_or_else(|| {
                                ShellError::GenericError {
                                    error: "Flag error".into(),
                                    msg: "flag signal not found".into(),
                                    span: Some(call.head),
                                    help: None,
                                    inner: vec![],
                                }
                            })?,
                            signal_span,
                        ),
                    });
                }
                cmd.arg("-9");
            } else if let Some(signal_value) = signal {
                cmd.arg(format!("-{}", signal_value.item));
            }

            cmd.arg(pid.to_string());

            cmd.args(rest.iter().map(move |id| id.to_string()));

            cmd
        };

        // pipe everything to null
        if quiet {
            cmd.stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null());
        }

        let output = cmd.output().map_err(|e| ShellError::GenericError {
            error: "failed to execute shell command".into(),
            msg: e.to_string(),
            span: Some(call.head),
            help: None,
            inner: vec![],
        })?;

        if !quiet && !output.status.success() {
            return Err(ShellError::GenericError {
                error: "process didn't terminate successfully".into(),
                msg: String::from_utf8(output.stderr).unwrap_or_default(),
                span: Some(call.head),
                help: None,
                inner: vec![],
            });
        }

        let mut output =
            String::from_utf8(output.stdout).map_err(|e| ShellError::GenericError {
                error: "failed to convert output to string".into(),
                msg: e.to_string(),
                span: Some(call.head),
                help: None,
                inner: vec![],
            })?;

        output.truncate(output.trim_end().len());

        if output.is_empty() {
            Ok(Value::nothing(call.head).into_pipeline_data())
        } else {
            Ok(Value::string(output, call.head).into_pipeline_data())
        }
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Kill the pid using the most memory",
                example: "ps | sort-by mem | last | kill $in.pid",
                result: None,
            },
            Example {
                description: "Force kill a given pid",
                example: "kill --force 12345",
                result: None,
            },
            #[cfg(not(target_os = "windows"))]
            Example {
                description: "Send INT signal",
                example: "kill -s 2 12345",
                result: None,
            },
        ]
    }
}

#[cfg(test)]
mod tests {
    use super::Kill;

    #[test]
    fn examples_work_as_expected() {
        use crate::test_examples;
        test_examples(Kill {})
    }
}