add -n flag to print to print without a newline (#5458)

* add -n flag to print to print without a newline

* clippy
This commit is contained in:
Darren Schroeder 2022-05-06 15:33:00 -05:00 committed by GitHub
parent fbdb125141
commit 2dfd975940
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 28 additions and 7 deletions

View file

@ -16,6 +16,11 @@ impl Command for Print {
fn signature(&self) -> Signature {
Signature::build("print")
.rest("rest", SyntaxShape::Any, "the values to print")
.switch(
"no_newline",
"print without inserting a newline for the line ending",
Some('n'),
)
.category(Category::Strings)
}
@ -31,10 +36,13 @@ impl Command for Print {
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
let no_newline = call.has_flag("no_newline");
let head = call.head;
for arg in args {
arg.into_pipeline_data().print(engine_state, stack)?;
arg.into_pipeline_data()
.print(engine_state, stack, no_newline)?;
}
Ok(PipelineData::new(head))

View file

@ -237,7 +237,7 @@ pub fn eval_source(
set_last_exit_code(stack, 0);
}
if let Err(err) = pipeline_data.print(engine_state, stack) {
if let Err(err) = pipeline_data.print(engine_state, stack, false) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);

View file

@ -216,7 +216,7 @@ impl Command for Watch {
match eval_result {
Ok(val) => {
val.print(engine_state, stack)?;
val.print(engine_state, stack, false)?;
}
Err(err) => {
let working_set = StateWorkingSet::new(engine_state);

View file

@ -416,12 +416,16 @@ impl PipelineData {
}
}
pub fn print(self, engine_state: &EngineState, stack: &mut Stack) -> Result<(), ShellError> {
pub fn print(
self,
engine_state: &EngineState,
stack: &mut Stack,
no_newline: bool,
) -> Result<(), ShellError> {
// If the table function is in the declarations, then we can use it
// to create the table value that will be printed in the terminal
let config = engine_state.get_config();
let stdout = std::io::stdout();
if let PipelineData::ExternalStream {
@ -460,11 +464,15 @@ impl PipelineData {
let working_set = StateWorkingSet::new(engine_state);
format_error(&working_set, &error)
} else if no_newline {
item.into_string("", config)
} else {
item.into_string("\n", config)
};
out.push('\n');
if !no_newline {
out.push('\n');
}
match stdout.lock().write_all(out.as_bytes()) {
Ok(_) => (),
@ -479,10 +487,15 @@ impl PipelineData {
let working_set = StateWorkingSet::new(engine_state);
format_error(&working_set, &error)
} else if no_newline {
item.into_string("", config)
} else {
item.into_string("\n", config)
};
out.push('\n');
if !no_newline {
out.push('\n');
}
match stdout.lock().write_all(out.as_bytes()) {
Ok(_) => (),