2023-08-29 23:46:50 +02:00
|
|
|
use nu_cmd_base::hook::{eval_env_change_hook, eval_hook};
|
2022-07-29 22:42:00 +02:00
|
|
|
use nu_engine::eval_block;
|
|
|
|
use nu_parser::parse;
|
|
|
|
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet};
|
2022-12-24 14:41:57 +01:00
|
|
|
use nu_protocol::{CliError, PipelineData, Value};
|
2023-05-10 14:05:01 +02:00
|
|
|
use nu_std::load_standard_library;
|
2023-08-19 15:23:11 +02:00
|
|
|
use std::io::{self, BufRead, Read, Write};
|
2022-07-29 22:42:00 +02:00
|
|
|
|
2022-02-02 21:59:01 +01:00
|
|
|
/// Echo's value of env keys from args
|
|
|
|
/// Example: nu --testbin env_echo FOO BAR
|
|
|
|
/// If it it's not present echo's nothing
|
2022-10-20 14:56:44 +02:00
|
|
|
pub fn echo_env(to_stdout: bool) {
|
2022-02-02 21:59:01 +01:00
|
|
|
let args = args();
|
|
|
|
for arg in args {
|
|
|
|
if let Ok(v) = std::env::var(arg) {
|
2022-10-20 14:56:44 +02:00
|
|
|
if to_stdout {
|
2023-01-30 02:37:54 +01:00
|
|
|
println!("{v}");
|
2022-10-20 14:56:44 +02:00
|
|
|
} else {
|
2023-01-30 02:37:54 +01:00
|
|
|
eprintln!("{v}");
|
2022-10-20 14:56:44 +02:00
|
|
|
}
|
2022-02-02 21:59:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-19 15:23:11 +02:00
|
|
|
/// Cross platform echo using println!()
|
|
|
|
/// Example: nu --testbin echo a b c
|
|
|
|
/// a b c
|
2022-02-02 21:59:01 +01:00
|
|
|
pub fn cococo() {
|
|
|
|
let args: Vec<String> = args();
|
|
|
|
|
|
|
|
if args.len() > 1 {
|
|
|
|
// Write back out all the arguments passed
|
|
|
|
// if given at least 1 instead of chickens
|
|
|
|
// speaking co co co.
|
|
|
|
println!("{}", &args[1..].join(" "));
|
|
|
|
} else {
|
|
|
|
println!("cococo");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-19 15:23:11 +02:00
|
|
|
/// Cross platform cat (open a file, print the contents) using read_to_string and println!()
|
2022-02-02 21:59:01 +01:00
|
|
|
pub fn meow() {
|
|
|
|
let args: Vec<String> = args();
|
|
|
|
|
|
|
|
for arg in args.iter().skip(1) {
|
|
|
|
let contents = std::fs::read_to_string(arg).expect("Expected a filepath");
|
2023-01-30 02:37:54 +01:00
|
|
|
println!("{contents}");
|
2022-02-02 21:59:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-19 15:23:11 +02:00
|
|
|
/// Cross platform cat (open a file, print the contents) using read() and write_all() / binary
|
2022-03-27 04:35:59 +02:00
|
|
|
pub fn meowb() {
|
|
|
|
let args: Vec<String> = args();
|
|
|
|
|
|
|
|
let stdout = io::stdout();
|
|
|
|
let mut handle = stdout.lock();
|
|
|
|
|
|
|
|
for arg in args.iter().skip(1) {
|
|
|
|
let buf = std::fs::read(arg).expect("Expected a filepath");
|
|
|
|
handle.write_all(&buf).expect("failed to write to stdout");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Relays anything received on stdin to stdout
|
|
|
|
pub fn relay() {
|
|
|
|
io::copy(&mut io::stdin().lock(), &mut io::stdout().lock())
|
|
|
|
.expect("failed to copy stdin to stdout");
|
|
|
|
}
|
|
|
|
|
2023-08-19 15:23:11 +02:00
|
|
|
/// Cross platform echo but concats arguments without space and NO newline
|
|
|
|
/// nu --testbin nonu a b c
|
|
|
|
/// abc
|
2022-02-02 21:59:01 +01:00
|
|
|
pub fn nonu() {
|
2023-01-30 02:37:54 +01:00
|
|
|
args().iter().skip(1).for_each(|arg| print!("{arg}"));
|
2022-02-02 21:59:01 +01:00
|
|
|
}
|
|
|
|
|
2023-08-19 15:23:11 +02:00
|
|
|
/// Repeat a string or char N times
|
|
|
|
/// nu --testbin repeater a 5
|
|
|
|
/// aaaaa
|
|
|
|
/// nu --testbin repeater test 5
|
|
|
|
/// testtesttesttesttest
|
2022-02-02 21:59:01 +01:00
|
|
|
pub fn repeater() {
|
|
|
|
let mut stdout = io::stdout();
|
|
|
|
let args = args();
|
|
|
|
let mut args = args.iter().skip(1);
|
|
|
|
let letter = args.next().expect("needs a character to iterate");
|
|
|
|
let count = args.next().expect("need the number of times to iterate");
|
|
|
|
|
|
|
|
let count: u64 = count.parse().expect("can't convert count to number");
|
|
|
|
|
|
|
|
for _ in 0..count {
|
2023-01-30 02:37:54 +01:00
|
|
|
let _ = write!(stdout, "{letter}");
|
2022-02-02 21:59:01 +01:00
|
|
|
}
|
|
|
|
let _ = stdout.flush();
|
|
|
|
}
|
|
|
|
|
2023-08-19 15:23:11 +02:00
|
|
|
/// A version of repeater that can output binary data, even null bytes
|
special-case ExternalStream in bytes starts-with (#8203)
# Description
`bytes starts-with` converts the input into a `Value` before running
.starts_with to find if the binary matches. This has two side effects:
it makes the code simpler, only dealing in whole values, and simplifying
a lot of input pipeline handling and value transforming it would
otherwise have to do. _Especially_ in the presence of a cell path to
drill into. It also makes buffers the entire input into memory, which
can take up a lot of memory when dealing with large files, especially if
you only want to check the first few bytes (like for a magic number).
This PR adds a special branch on PipelineData::ExternalStream with a
streaming version of starts_with.
# User-Facing Changes
Opening large files and running bytes starts-with on them will not take
a long time.
# 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` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
# Drawbacks
Streaming checking is more complicated, and there may be bugs. I tested
it with multiple chunks with string data and binary data and it seems to
work alright up to 8k and over bytes, though.
The existing `operate` method still exists because the way it handles
cell paths and values is complicated. This causes some "code
duplication", or at least some intent duplication, between the value
code and the streaming code. This might be worthwhile considering the
performance gains (approaching infinity on larger inputs).
Another thing to consider is that my ExternalStream branch considers
string data as valid input. The operate branch only parses Binary
values, so it would fail. `open` is kind of unpredictable on whether it
returns string data or binary data, even when passing `--raw`. I think
this can be a problem but not really one I'm trying to tackle in this
PR, so, it's worth considering.
2023-02-26 15:17:44 +01:00
|
|
|
pub fn repeat_bytes() {
|
|
|
|
let mut stdout = io::stdout();
|
|
|
|
let args = args();
|
|
|
|
let mut args = args.iter().skip(1);
|
|
|
|
|
|
|
|
while let (Some(binary), Some(count)) = (args.next(), args.next()) {
|
|
|
|
let bytes: Vec<u8> = (0..binary.len())
|
|
|
|
.step_by(2)
|
|
|
|
.map(|i| {
|
|
|
|
u8::from_str_radix(&binary[i..i + 2], 16)
|
|
|
|
.expect("binary string is valid hexadecimal")
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
let count: u64 = count.parse().expect("repeat count must be a number");
|
|
|
|
|
|
|
|
for _ in 0..count {
|
|
|
|
stdout
|
|
|
|
.write_all(&bytes)
|
|
|
|
.expect("writing to stdout must not fail");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let _ = stdout.flush();
|
|
|
|
}
|
|
|
|
|
2023-08-19 15:23:11 +02:00
|
|
|
/// Another type of echo that outputs a parameter per line, looping infinitely
|
2022-02-02 21:59:01 +01:00
|
|
|
pub fn iecho() {
|
|
|
|
// println! panics if stdout gets closed, whereas writeln gives us an error
|
|
|
|
let mut stdout = io::stdout();
|
|
|
|
let _ = args()
|
|
|
|
.iter()
|
|
|
|
.skip(1)
|
|
|
|
.cycle()
|
2023-01-30 02:37:54 +01:00
|
|
|
.try_for_each(|v| writeln!(stdout, "{v}"));
|
2022-02-02 21:59:01 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn fail() {
|
|
|
|
std::process::exit(1);
|
|
|
|
}
|
|
|
|
|
2023-08-19 15:23:11 +02:00
|
|
|
/// With no parameters, will chop a character off the end of each line
|
2022-02-02 21:59:01 +01:00
|
|
|
pub fn chop() {
|
|
|
|
if did_chop_arguments() {
|
|
|
|
// we are done and don't care about standard input.
|
|
|
|
std::process::exit(0);
|
|
|
|
}
|
|
|
|
|
|
|
|
// if no arguments given, chop from standard input and exit.
|
|
|
|
let stdin = io::stdin();
|
|
|
|
let mut stdout = io::stdout();
|
|
|
|
|
|
|
|
for given in stdin.lock().lines().flatten() {
|
|
|
|
let chopped = if given.is_empty() {
|
|
|
|
&given
|
|
|
|
} else {
|
|
|
|
let to = given.len() - 1;
|
|
|
|
&given[..to]
|
|
|
|
};
|
|
|
|
|
2023-01-30 02:37:54 +01:00
|
|
|
if let Err(_e) = writeln!(stdout, "{chopped}") {
|
2022-02-02 21:59:01 +01:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
std::process::exit(0);
|
|
|
|
}
|
|
|
|
|
2022-07-29 22:42:00 +02:00
|
|
|
fn outcome_err(
|
|
|
|
engine_state: &EngineState,
|
|
|
|
error: &(dyn miette::Diagnostic + Send + Sync + 'static),
|
|
|
|
) -> ! {
|
|
|
|
let working_set = StateWorkingSet::new(engine_state);
|
|
|
|
|
|
|
|
eprintln!("Error: {:?}", CliError(error, &working_set));
|
|
|
|
|
|
|
|
std::process::exit(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn outcome_ok(msg: String) -> ! {
|
2023-01-30 02:37:54 +01:00
|
|
|
println!("{msg}");
|
2022-07-29 22:42:00 +02:00
|
|
|
|
|
|
|
std::process::exit(0);
|
|
|
|
}
|
|
|
|
|
2023-06-14 23:12:55 +02:00
|
|
|
/// Generate a minimal engine state with just `nu-cmd-lang`, `nu-command`, and `nu-cli` commands.
|
|
|
|
fn get_engine_state() -> EngineState {
|
|
|
|
let engine_state = nu_cmd_lang::create_default_context();
|
|
|
|
let engine_state = nu_command::add_shell_command_context(engine_state);
|
|
|
|
nu_cli::add_cli_context(engine_state)
|
|
|
|
}
|
|
|
|
|
2022-07-29 22:42:00 +02:00
|
|
|
pub fn nu_repl() {
|
|
|
|
//cwd: &str, source_lines: &[&str]) {
|
|
|
|
let cwd = std::env::current_dir().expect("Could not get current working directory.");
|
|
|
|
let source_lines = args();
|
|
|
|
|
2023-06-14 23:12:55 +02:00
|
|
|
let mut engine_state = get_engine_state();
|
2022-07-29 22:42:00 +02:00
|
|
|
let mut stack = Stack::new();
|
|
|
|
|
2023-05-10 14:05:01 +02:00
|
|
|
engine_state.add_env_var("PWD".into(), Value::test_string(cwd.to_string_lossy()));
|
2022-07-29 22:42:00 +02:00
|
|
|
|
|
|
|
let mut last_output = String::new();
|
|
|
|
|
2023-05-10 14:05:01 +02:00
|
|
|
load_standard_library(&mut engine_state).expect("Could not load the standard library.");
|
|
|
|
|
2022-07-29 22:42:00 +02:00
|
|
|
for (i, line) in source_lines.iter().enumerate() {
|
2023-01-24 12:23:42 +01:00
|
|
|
let cwd = nu_engine::env::current_dir(&engine_state, &stack)
|
|
|
|
.unwrap_or_else(|err| outcome_err(&engine_state, &err));
|
2022-07-29 22:42:00 +02:00
|
|
|
|
|
|
|
// Before doing anything, merge the environment from the previous REPL iteration into the
|
|
|
|
// permanent state.
|
2023-06-04 21:04:28 +02:00
|
|
|
if let Err(err) = engine_state.merge_env(&mut stack, &cwd) {
|
2022-07-29 22:42:00 +02:00
|
|
|
outcome_err(&engine_state, &err);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for pre_prompt hook
|
|
|
|
let config = engine_state.get_config();
|
|
|
|
if let Some(hook) = config.hooks.pre_prompt.clone() {
|
2023-08-27 13:55:20 +02:00
|
|
|
if let Err(err) = eval_hook(
|
|
|
|
&mut engine_state,
|
|
|
|
&mut stack,
|
|
|
|
None,
|
|
|
|
vec![],
|
|
|
|
&hook,
|
|
|
|
"pre_prompt",
|
|
|
|
) {
|
2022-07-29 22:42:00 +02:00
|
|
|
outcome_err(&engine_state, &err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for env change hook
|
|
|
|
let config = engine_state.get_config();
|
|
|
|
if let Err(err) = eval_env_change_hook(
|
|
|
|
config.hooks.env_change.clone(),
|
|
|
|
&mut engine_state,
|
|
|
|
&mut stack,
|
|
|
|
) {
|
|
|
|
outcome_err(&engine_state, &err);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for pre_execution hook
|
|
|
|
let config = engine_state.get_config();
|
2023-03-16 23:45:35 +01:00
|
|
|
|
2023-06-11 00:38:11 +02:00
|
|
|
engine_state
|
|
|
|
.repl_state
|
2023-03-16 23:45:35 +01:00
|
|
|
.lock()
|
2023-06-11 00:38:11 +02:00
|
|
|
.expect("repl state mutex")
|
|
|
|
.buffer = line.to_string();
|
2023-03-16 23:45:35 +01:00
|
|
|
|
2022-07-29 22:42:00 +02:00
|
|
|
if let Some(hook) = config.hooks.pre_execution.clone() {
|
2023-08-27 13:55:20 +02:00
|
|
|
if let Err(err) = eval_hook(
|
|
|
|
&mut engine_state,
|
|
|
|
&mut stack,
|
|
|
|
None,
|
|
|
|
vec![],
|
|
|
|
&hook,
|
|
|
|
"pre_execution",
|
|
|
|
) {
|
2022-07-29 22:42:00 +02:00
|
|
|
outcome_err(&engine_state, &err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Eval the REPL line
|
|
|
|
let (block, delta) = {
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
2023-04-07 02:35:45 +02:00
|
|
|
let block = parse(
|
2022-07-29 22:42:00 +02:00
|
|
|
&mut working_set,
|
2023-01-30 02:37:54 +01:00
|
|
|
Some(&format!("line{i}")),
|
2022-07-29 22:42:00 +02:00
|
|
|
line.as_bytes(),
|
|
|
|
false,
|
|
|
|
);
|
|
|
|
|
2023-04-07 02:35:45 +02:00
|
|
|
if let Some(err) = working_set.parse_errors.first() {
|
|
|
|
outcome_err(&engine_state, err);
|
2022-07-29 22:42:00 +02:00
|
|
|
}
|
|
|
|
(block, working_set.render())
|
|
|
|
};
|
|
|
|
|
|
|
|
if let Err(err) = engine_state.merge_delta(delta) {
|
|
|
|
outcome_err(&engine_state, &err);
|
|
|
|
}
|
|
|
|
|
2022-12-07 19:31:57 +01:00
|
|
|
let input = PipelineData::empty();
|
2022-07-29 22:42:00 +02:00
|
|
|
let config = engine_state.get_config();
|
|
|
|
|
|
|
|
match eval_block(&engine_state, &mut stack, &block, input, false, false) {
|
|
|
|
Ok(pipeline_data) => match pipeline_data.collect_string("", config) {
|
|
|
|
Ok(s) => last_output = s,
|
|
|
|
Err(err) => outcome_err(&engine_state, &err),
|
|
|
|
},
|
|
|
|
Err(err) => outcome_err(&engine_state, &err),
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(cwd) = stack.get_env_var(&engine_state, "PWD") {
|
2023-01-24 12:23:42 +01:00
|
|
|
let path = cwd
|
|
|
|
.as_string()
|
|
|
|
.unwrap_or_else(|err| outcome_err(&engine_state, &err));
|
2022-07-29 22:42:00 +02:00
|
|
|
let _ = std::env::set_current_dir(path);
|
|
|
|
engine_state.add_env_var("PWD".into(), cwd);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
outcome_ok(last_output)
|
|
|
|
}
|
|
|
|
|
2022-02-02 21:59:01 +01:00
|
|
|
fn did_chop_arguments() -> bool {
|
|
|
|
let args: Vec<String> = args();
|
|
|
|
|
|
|
|
if args.len() > 1 {
|
|
|
|
let mut arguments = args.iter();
|
|
|
|
arguments.next();
|
|
|
|
|
|
|
|
for arg in arguments {
|
|
|
|
let chopped = if arg.is_empty() {
|
2022-02-24 20:02:28 +01:00
|
|
|
arg
|
2022-02-02 21:59:01 +01:00
|
|
|
} else {
|
|
|
|
let to = arg.len() - 1;
|
|
|
|
&arg[..to]
|
|
|
|
};
|
|
|
|
|
2023-01-30 02:37:54 +01:00
|
|
|
println!("{chopped}");
|
2022-02-02 21:59:01 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
2023-02-24 21:39:52 +01:00
|
|
|
pub fn input_bytes_length() {
|
|
|
|
let stdin = io::stdin();
|
|
|
|
let count = stdin.lock().bytes().count();
|
|
|
|
|
|
|
|
println!("{}", count);
|
|
|
|
}
|
|
|
|
|
2022-02-02 21:59:01 +01:00
|
|
|
fn args() -> Vec<String> {
|
|
|
|
// skip (--testbin bin_name args)
|
|
|
|
std::env::args().skip(2).collect()
|
|
|
|
}
|