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

210 lines
7.0 KiB
Rust

#[cfg(windows)]
use itertools::Itertools;
use nu_engine::CallExt;
#[cfg(all(
unix,
not(target_os = "macos"),
not(target_os = "windows"),
not(target_os = "android"),
))]
use nu_protocol::Span;
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, Example, IntoInterruptiblePipelineData, PipelineData, Record, ShellError, Signature,
Type, Value,
};
#[cfg(all(
unix,
not(target_os = "macos"),
not(target_os = "windows"),
not(target_os = "android"),
))]
use procfs::WithCurrentSystemInfo;
use std::time::Duration;
#[derive(Clone)]
pub struct Ps;
impl Command for Ps {
fn name(&self) -> &str {
"ps"
}
fn signature(&self) -> Signature {
Signature::build("ps")
.input_output_types(vec![(Type::Nothing, Type::Table(vec![]))])
.switch(
"long",
"list all available columns for each entry",
Some('l'),
)
.filter()
.category(Category::System)
}
fn usage(&self) -> &str {
"View information about system processes."
}
fn search_terms(&self) -> Vec<&str> {
vec!["procedures", "operations", "tasks", "ops"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_ps(engine_state, stack, call)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "List the system processes",
example: "ps",
result: None,
},
Example {
description: "List the top 5 system processes with the highest memory usage",
example: "ps | sort-by mem | last 5",
result: None,
},
Example {
description: "List the top 3 system processes with the highest CPU usage",
example: "ps | sort-by cpu | last 3",
result: None,
},
Example {
description: "List the system processes with 'nu' in their names",
example: "ps | where name =~ 'nu'",
result: None,
},
Example {
description: "Get the parent process id of the current nu process",
example: "ps | where pid == $nu.pid | get ppid",
result: None,
},
]
}
}
fn run_ps(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let mut output = vec![];
let span = call.head;
let long = call.has_flag(engine_state, stack, "long")?;
for proc in nu_system::collect_proc(Duration::from_millis(100), false) {
let mut record = Record::new();
record.push("pid", Value::int(proc.pid() as i64, span));
record.push("ppid", Value::int(proc.ppid() as i64, span));
record.push("name", Value::string(proc.name(), span));
#[cfg(not(windows))]
{
// Hide status on Windows until we can find a good way to support it
record.push("status", Value::string(proc.status(), span));
}
record.push("cpu", Value::float(proc.cpu_usage(), span));
record.push("mem", Value::filesize(proc.mem_size() as i64, span));
record.push("virtual", Value::filesize(proc.virtual_size() as i64, span));
if long {
record.push("command", Value::string(proc.command(), span));
#[cfg(all(
unix,
not(target_os = "macos"),
not(target_os = "windows"),
not(target_os = "android"),
))]
{
let proc_stat = proc
.curr_proc
.stat()
.map_err(|e| ShellError::GenericError {
error: "Error getting process stat".into(),
msg: e.to_string(),
span: Some(Span::unknown()),
help: None,
inner: vec![],
})?;
// If we can't get the start time, just use the current time
let proc_start = proc_stat
.starttime()
.get()
.unwrap_or_else(|_| chrono::Local::now());
record.push("start_time", Value::date(proc_start.into(), span));
record.push("user_id", Value::int(proc.curr_proc.owner() as i64, span));
// These work and may be helpful, but it just seemed crowded
// record.push("group_id", Value::int(proc_stat.pgrp as i64, span));
// record.push("session_id", Value::int(proc_stat.session as i64, span));
// This may be helpful for ctrl+z type of checking, once we get there
// record.push("tpg_id", Value::int(proc_stat.tpgid as i64, span));
record.push("priority", Value::int(proc_stat.priority, span));
record.push("process_threads", Value::int(proc_stat.num_threads, span));
record.push("cwd", Value::string(proc.cwd(), span));
}
#[cfg(windows)]
{
//TODO: There's still more information we can cram in there if we want to
// see the ProcessInfo struct for more information
record.push(
"start_time",
Value::date(proc.start_time.fixed_offset(), span),
);
record.push(
"user",
Value::string(
proc.user.clone().name.unwrap_or("unknown".to_string()),
span,
),
);
record.push(
"user_sid",
Value::string(
proc.user
.clone()
.sid
.iter()
.map(|r| r.to_string())
.join("-"),
span,
),
);
record.push("priority", Value::int(proc.priority as i64, span));
record.push("cwd", Value::string(proc.cwd(), span));
record.push(
"environment",
Value::list(
proc.environ()
.iter()
.map(|x| Value::string(x.to_string(), span))
.collect(),
span,
),
);
}
#[cfg(target_os = "macos")]
{
record.push("cwd", Value::string(proc.cwd(), span));
}
}
output.push(Value::record(record, span));
}
Ok(output
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone()))
}