Simplify clear implementation (#11273)

# Description
This PR uses the `crossterm` api to reimplement `clear` command, since
`crossterm` is cross-platform.
This seems to work on linux and windows.

# User-Facing Changes
N/A

# Tests + Formatting
- [x] `cargo fmt --all -- --check` to check standard code formatting
(`cargo fmt --all` applies these changes)
- [x] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used`
to check that you're using the standard code style
- [x] `cargo test --workspace` to check that all tests pass (on Windows
make sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- [x] `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

# After Submitting
N/A
This commit is contained in:
nibon7 2023-12-10 05:24:19 +08:00 committed by GitHub
parent fa5d7babb9
commit ca05553fc6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,9 +1,12 @@
use crossterm::{
cursor::MoveTo,
terminal::{Clear as ClearCommand, ClearType},
QueueableCommand,
};
use nu_protocol::ast::Call; use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{ use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Type};
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value, use std::io::Write;
};
use std::process::Command as CommandSys;
#[derive(Clone)] #[derive(Clone)]
pub struct Clear; pub struct Clear;
@ -25,37 +28,17 @@ impl Command for Clear {
fn run( fn run(
&self, &self,
engine_state: &EngineState, _engine_state: &EngineState,
stack: &mut Stack, _stack: &mut Stack,
call: &Call, _call: &Call,
_input: PipelineData, _input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let span = call.head; std::io::stdout()
.queue(ClearCommand(ClearType::All))?
.queue(MoveTo(0, 0))?
.flush()?;
if cfg!(windows) { Ok(PipelineData::Empty)
CommandSys::new("cmd")
.args(["/C", "cls"])
.status()
.map_err(|e| ShellError::IOErrorSpanned {
msg: e.to_string(),
span,
})?;
} else if cfg!(unix) {
let mut cmd = CommandSys::new("/bin/sh");
if let Some(Value::String { val, .. }) = stack.get_env_var(engine_state, "TERM") {
cmd.env("TERM", val);
}
cmd.args(["-c", "clear"])
.status()
.map_err(|e| ShellError::IOErrorSpanned {
msg: e.to_string(),
span,
})?;
}
Ok(Value::nothing(span).into_pipeline_data())
} }
fn examples(&self) -> Vec<Example> { fn examples(&self) -> Vec<Example> {