nushell/crates/nu-command/src/core_commands/source.rs

71 lines
2.1 KiB
Rust
Raw Normal View History

2021-10-06 04:29:05 +02:00
use nu_engine::{eval_block, CallExt};
2021-10-02 04:17:32 +02:00
use nu_protocol::ast::Call;
2021-10-25 18:58:58 +02:00
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, SyntaxShape};
2021-09-11 06:54:24 +02:00
/// Source a file for environment variables.
2021-10-25 06:01:02 +02:00
#[derive(Clone)]
2021-09-11 06:54:24 +02:00
pub struct Source;
impl Command for Source {
fn name(&self) -> &str {
"source"
}
fn signature(&self) -> Signature {
Signature::build("source")
.required(
"filename",
SyntaxShape::Filepath,
"the filepath to the script file to source",
)
.category(Category::Core)
2021-09-11 06:54:24 +02:00
}
fn usage(&self) -> &str {
"Runs a script file in the current context."
}
fn run(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-09-11 06:54:24 +02:00
call: &Call,
2021-10-25 06:01:02 +02:00
input: PipelineData,
) -> Result<PipelineData, ShellError> {
2021-10-06 04:29:05 +02:00
// Note: this hidden positional is the block_id that corresponded to the 0th position
// it is put here by the parser
2021-10-25 08:31:39 +02:00
let block_id: i64 = call.req(engine_state, stack, 1)?;
2021-10-06 04:29:05 +02:00
2021-10-25 08:31:39 +02:00
let block = engine_state.get_block(block_id as usize).clone();
eval_block(
engine_state,
stack,
&block,
input,
call.redirect_stdout,
call.redirect_stderr,
)
2021-09-11 06:54:24 +02:00
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Runs foo.nu in the current context",
example: r#"source foo.nu"#,
result: None,
},
Example {
description: "Runs foo.nu in current context and call the command defined, suppose foo.nu has content: `def say-hi [] { echo 'Hi!' }`",
example: r#"source ./foo.nu; say-hi"#,
result: None,
},
Example {
description: "Runs foo.nu in current context and call the `main` command automatically, suppose foo.nu has content: `def main [] { echo 'Hi!' }`",
example: r#"source ./foo.nu"#,
result: None,
},
]
}
2021-09-11 06:54:24 +02:00
}