nushell/crates/nu-command/src/platform/sleep.rs

114 lines
3.1 KiB
Rust
Raw Normal View History

use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape,
Type, Value,
};
use std::{
thread,
time::{Duration, Instant},
};
const CTRL_C_CHECK_INTERVAL: Duration = Duration::from_millis(100);
#[derive(Clone)]
pub struct Sleep;
impl Command for Sleep {
fn name(&self) -> &str {
"sleep"
}
fn usage(&self) -> &str {
"Delay for a specified amount of time."
}
fn signature(&self) -> Signature {
Signature::build("sleep")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required("duration", SyntaxShape::Duration, "Time to sleep.")
.rest("rest", SyntaxShape::Duration, "Additional time.")
.category(Category::Platform)
}
fn search_terms(&self) -> Vec<&str> {
vec!["delay", "wait", "timer"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
fn duration_from_i64(val: i64) -> Duration {
Duration::from_nanos(if val < 0 { 0 } else { val as u64 })
}
let duration: i64 = call.req(engine_state, stack, 0)?;
let rest: Vec<i64> = call.rest(engine_state, stack, 1)?;
let total_dur =
duration_from_i64(duration) + rest.into_iter().map(duration_from_i64).sum::<Duration>();
let ctrlc_ref = &engine_state.ctrlc.clone();
let start = Instant::now();
loop {
thread::sleep(CTRL_C_CHECK_INTERVAL.min(total_dur));
if start.elapsed() >= total_dur {
break;
}
if nu_utils::ctrl_c::was_pressed(ctrlc_ref) {
return Err(ShellError::InterruptedByUser {
span: Some(call.head),
});
}
}
Move Value to helpers, separate span call (#10121) # Description As part of the refactor to split spans off of Value, this moves to using helper functions to create values, and using `.span()` instead of matching span out of Value directly. Hoping to get a few more helping hands to finish this, as there are a lot of commands to update :) # User-Facing Changes <!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. --> # Tests + Formatting <!-- Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to check that you're using the standard code style - `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)) - `cargo run -- -c "use std testing; testing run-tests --path crates/nu-std"` to run the tests for the standard library > **Note** > from `nushell` you can also use the `toolkit` as follows > ```bash > use toolkit.nu # or use an `env_change` hook to activate it automatically > toolkit check pr > ``` --> # After Submitting <!-- If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date. --> --------- Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com> Co-authored-by: WindSoilder <windsoilder@outlook.com>
2023-09-03 14:27:29 +00:00
Ok(Value::nothing(call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Sleep for 1sec",
example: "sleep 1sec",
Move Value to helpers, separate span call (#10121) # Description As part of the refactor to split spans off of Value, this moves to using helper functions to create values, and using `.span()` instead of matching span out of Value directly. Hoping to get a few more helping hands to finish this, as there are a lot of commands to update :) # User-Facing Changes <!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. --> # Tests + Formatting <!-- Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to check that you're using the standard code style - `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)) - `cargo run -- -c "use std testing; testing run-tests --path crates/nu-std"` to run the tests for the standard library > **Note** > from `nushell` you can also use the `toolkit` as follows > ```bash > use toolkit.nu # or use an `env_change` hook to activate it automatically > toolkit check pr > ``` --> # After Submitting <!-- If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date. --> --------- Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com> Co-authored-by: WindSoilder <windsoilder@outlook.com>
2023-09-03 14:27:29 +00:00
result: Some(Value::nothing(Span::test_data())),
},
enable/update some example tests so they work again (#10058) # Description This PR updates some `Example` tests so that they work again. The only one I couldn't figure out is the one in the `filter` command. It should work but does not. However, I left the test in because it's valuable, it just has a `None` result. I'd like to fix this but I'm not sure how. # User-Facing Changes <!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. --> # Tests + Formatting <!-- Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect -A clippy::result_large_err` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass - `cargo run -- -c "use std testing; testing run-tests --path crates/nu-std"` to run the tests for the standard library > **Note** > from `nushell` you can also use the `toolkit` as follows > ```bash > use toolkit.nu # or use an `env_change` hook to activate it automatically > toolkit check pr > ``` --> # After Submitting <!-- If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date. -->
2023-08-19 14:06:59 +00:00
Example {
description: "Sleep for 3sec",
example: "sleep 1sec 1sec 1sec",
result: None,
},
Example {
description: "Send output after 1sec",
example: "sleep 1sec; echo done",
result: None,
},
]
}
}
#[cfg(test)]
mod tests {
use super::Sleep;
#[test]
fn examples_work_as_expected() {
use crate::test_examples;
use std::time::Instant;
let start = Instant::now();
test_examples(Sleep {});
let elapsed = start.elapsed();
// only examples with actual output are run
assert!(elapsed >= std::time::Duration::from_secs(1));
assert!(elapsed < std::time::Duration::from_secs(2));
}
}