nushell/crates/nu-command/src/platform/kill.rs
Artemiy 1867bb1a88
Fix incorrect handling of boolean flags for builtin commands (#11492)
# Description
Possible fix of #11456
This PR fixes a bug where builtin commands did not respect the logic of
dynamically passed boolean flags. The reason is
[has_flag](6f59abaf43/crates/nu-protocol/src/ast/call.rs (L204C5-L212C6))
method did not evaluate and take into consideration expression used with
flag.

To address this issue a solution is proposed:
1. `has_flag` method is moved to `CallExt` and new logic to evaluate
expression and check if it is a boolean value is added
2. `has_flag_const` method is added to `CallExt` which is a constant
version of `has_flag`
3. `has_named` method is added to `Call` which is basically the old
logic of `has_flag`
4. All usages of `has_flag` in code are updated, mostly to pass
`engine_state` and `stack` to new `has_flag`. In `run_const` commands it
is replaced with `has_flag_const`. And in a few select places: parser,
`to nuon` and `into string` old logic via `has_named` is used.

# User-Facing Changes
Explicit values of boolean flags are now respected in builtin commands.
Before:

![image](https://github.com/nushell/nushell/assets/17511668/f9fbabb2-3cfd-43f9-ba9e-ece76d80043c)
After:

![image](https://github.com/nushell/nushell/assets/17511668/21867596-2075-437f-9c85-45563ac70083)

Another example:
Before:

![image](https://github.com/nushell/nushell/assets/17511668/efdbc5ca-5227-45a4-ac5b-532cdc2bbf5f)
After:

![image](https://github.com/nushell/nushell/assets/17511668/2907d5c5-aa93-404d-af1c-21cdc3d44646)


# Tests + Formatting
Added test reproducing some variants of original issue.
2024-01-11 17:19:48 +02:00

206 lines
6.6 KiB
Rust

use nu_engine::CallExt;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{ast::Call, span};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, ShellError,
Signature, Spanned, SyntaxShape, Type, Value,
};
use std::process::{Command as CommandSys, Stdio};
#[derive(Clone)]
pub struct Kill;
impl Command for Kill {
fn name(&self) -> &str {
"kill"
}
fn usage(&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_named_arg("force")
.ok_or_else(|| ShellError::GenericError {
error: "Flag error".into(),
msg: "flag force not found".into(),
span: Some(call.head),
help: None,
inner: vec![],
})?
.span,
right_message: "signal".to_string(),
right_span: span(&[
call.get_named_arg("signal")
.ok_or_else(|| ShellError::GenericError {
error: "Flag error".into(),
msg: "flag signal not found".into(),
span: Some(call.head),
help: None,
inner: vec![],
})?
.span,
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 val = String::from(
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![],
})?
.trim_end(),
);
if val.is_empty() {
Ok(Value::nothing(call.head).into_pipeline_data())
} else {
Ok(vec![Value::string(val, call.head)]
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()))
}
}
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 {})
}
}