Skip to content

Commit

Permalink
Fix typos and simplify command meta passing
Browse files Browse the repository at this point in the history
  • Loading branch information
jpikl committed May 10, 2024
1 parent e2e8b22 commit 25f64ad
Show file tree
Hide file tree
Showing 16 changed files with 52 additions and 58 deletions.
2 changes: 1 addition & 1 deletion docs/reference/rew-x.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ rew x -s bash '{# for((i=0;i<3;i++)); do echo $i; done}. {}'

The `:` marker is a hint that an expression does not consume stdin. Without it, the overall execution might get stuck forever due to blocked IO calls.

Only external commands need `:` to be explicitely specified. For built-in commands, `:` is detected automatically.
Only external commands need `:` to be explicitly specified. For built-in commands, `:` is detected automatically.

```sh
rew x '{seq 1..3} {: !seq 1 3} {:# echo 1; echo 2; echo 3}'
Expand Down
4 changes: 2 additions & 2 deletions docs/reference/rew.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,9 @@ Can be also set using `REW_BUF_MODE` environment variable.

Size of a buffer used for IO operations.

Smaller values will reduce memory consumption but could negatively affect througput.
Smaller values will reduce memory consumption but could negatively affect throughput.

Larger values will increase memory consumption but may improve troughput in some cases.
Larger values will increase memory consumption but may improve throughput in some cases.

Certain commands (which can only operate with whole lines) won't be able to fetch a line bigger than this limit and will abort their execution instead.

Expand Down
2 changes: 1 addition & 1 deletion snapshots/error.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion snapshots/examples.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions snapshots/help.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 3 additions & 3 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::colors::BOLD;
use crate::colors::RESET;
use crate::command;
use crate::commands::METAS;
use crate::env;
use clap::command;
use clap::crate_description;
Expand All @@ -11,14 +11,14 @@ use clap::Command;

const REFERENCE_URL: &str = "https://jpikl.github.io/rew/reference";

pub fn build(metas: &[&'static command::Meta]) -> Command {
pub fn build() -> Command {
let mut app = command!()
.version(get_version())
.about(crate_description!().replace(". ", ".\n"))
.after_help(get_after_help(None))
.subcommand_required(true);

for meta in metas {
for meta in METAS {
let command = meta.build().after_help(get_after_help(Some(meta.name)));
app = app.subcommand(command);
}
Expand Down
4 changes: 2 additions & 2 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ mod trim;
mod upper;
mod x;

pub const COMMANDS: &[&Meta] = &[
pub const METAS: &[&Meta] = &[
&ascii::META,
&cat::META,
&first::META,
Expand All @@ -33,5 +33,5 @@ pub const COMMANDS: &[&Meta] = &[
];

pub fn get_meta(name: &str) -> Option<&'static Meta> {
COMMANDS.iter().find(|meta| meta.name == name).copied()
METAS.iter().find(|meta| meta.name == name).copied()
}
14 changes: 7 additions & 7 deletions src/commands/x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ const EXAMPLES: &[Example] = command_examples! [
},
"The `:` marker is a hint that an expression does not consume stdin. \
Without it, the overall execution might get stuck forever due to blocked IO calls.\n\n\
Only external commands need `:` to be explicitely specified. \
Only external commands need `:` to be explicitly specified. \
For built-in commands, `:` is detected automatically.": {
args: &["{seq 1..3} {: !seq 1 3} {:# echo 1; echo 2; echo 3}"],
input: &[],
Expand Down Expand Up @@ -240,7 +240,7 @@ fn eval_pattern(context: &Context, pattern: &Pattern, shell: &Shell) -> Result<(
}
}

// Helper thead forwards main process stdin to every child process.
// Helper thread forwards main process stdin to every child process.
let thread_context = context.clone();
let thread = thread::spawn(move || forward_input(&thread_context, consumers));

Expand All @@ -249,8 +249,8 @@ fn eval_pattern(context: &Context, pattern: &Pattern, shell: &Shell) -> Result<(
wait_children(children)?;

if thread.is_finished() {
// Join the thread only if it actually endeded.
// Otherwise, this would be stucked forewer!
// Join the thread only if it actually ended.
// Otherwise, this would be stuck forever!
thread.join().map_err(resume_unwind)?
} else {
// The helper thread is blocked on read from stdin.
Expand Down Expand Up @@ -283,7 +283,7 @@ fn build_pipeline(env: &Env, shell: &Shell, expr: &Expression) -> Result<Pipelin
pipeline = pipeline.add_command(command.build(env)?, command.stdin_mode())?;
}
if pipeline.is_empty() {
let command = Command::internal(&cat::META);
let command = Command::internal(&cat::META, &[]);
pipeline = pipeline.add_command(command.build(env)?, command.stdin_mode())?;
}
}
Expand All @@ -294,7 +294,7 @@ fn build_pipeline(env: &Env, shell: &Shell, expr: &Expression) -> Result<Pipelin

fn forward_input(context: &Context, mut stdins: Vec<Option<Spawned<ChildStdin>>>) -> Result<()> {
if stdins.iter().all(Option::is_none) {
return Ok(()); // None of the child proceses use stdin.
return Ok(()); // None of the child processes use stdin.
}

let mut reader = context.byte_chunk_reader();
Expand Down Expand Up @@ -362,7 +362,7 @@ fn wait_children(mut children: Vec<Spawned<Child>>) -> Result<()> {
}

// Give the remaining child processes some extra time to finish.
// Needed especialy in case program exists with error on Windows.
// Needed especially in case program exists with error on Windows.
thread::sleep(Duration::from_millis(100));

// Just kill the ones which did not terminate on their own.
Expand Down
6 changes: 3 additions & 3 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub const ENV_BUF_SIZE: &str = "REW_BUF_SIZE";
// Internal env variables:
//
// When `rew` is spawned as a child of some parent `rew` process,
// it recieves the parent's name through this environment variable.
// it receives the parent's name through this environment variable.
pub const ENV_SPAWNED_BY: &str = "_REW_SPAWNED_BY";

#[derive(Clone, Copy, ValueEnum, Display, Debug, IsVariant, PartialEq, Eq)]
Expand Down Expand Up @@ -64,9 +64,9 @@ pub struct Args {

/// Size of a buffer used for IO operations.
///
/// Smaller values will reduce memory consumption but could negatively affect througput.
/// Smaller values will reduce memory consumption but could negatively affect throughput.
///
/// Larger values will increase memory consumption but may improve troughput in some cases.
/// Larger values will increase memory consumption but may improve throughput in some cases.
///
/// Certain commands (which can only operate with whole lines) won't be able to fetch
/// a line bigger than this limit and will abort their execution instead.
Expand Down
3 changes: 1 addition & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use rew::app;
use rew::commands::get_meta;
use rew::commands::COMMANDS;
use rew::error::Reporter;
use std::io;
use std::process::ExitCode;

fn main() -> ExitCode {
let app = app::build(COMMANDS);
let app = app::build();
let reporter = Reporter::new(&app);

let matches = match app.try_get_matches() {
Expand Down
2 changes: 1 addition & 1 deletion src/pager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Pager {
stdin
.context
.apply_to_err(err)
.context("failed to write to child process stdin")
.context("failed to write to pager process stdin")
})
});

Expand Down
52 changes: 24 additions & 28 deletions src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,46 +36,42 @@ pub enum Command {
}

impl Command {
pub fn internal(meta: &'static Meta) -> Self {
Self::Internal {
meta,
args: Vec::new(),
}
}

pub fn detect(name: &str, args: &[String], external: bool) -> Self {
if external {
return Self::External {
name: name.to_string(),
args: args.to_vec(),
};
return Self::external(name, args);
}

if name == crate_name!() {
if let Some((name, args)) = args.split_first() {
if let Some(meta) = get_meta(name) {
return Self::Internal {
meta,
args: args.to_vec(),
};
return Self::internal(meta, args);
}
}

return Self::UnknownInternal {
args: args.to_vec(),
};
return Self::unknown_internal(args);
}

if let Some(meta) = get_meta(name) {
return Self::Internal {
meta,
args: args.to_vec(),
};
return Self::internal(meta, args);
}

Self::external(name, args)
}

pub fn internal(meta: &'static Meta, args: impl Into<Vec<String>>) -> Self {
Self::Internal {
meta,
args: args.into(),
}
}

pub fn unknown_internal(args: impl Into<Vec<String>>) -> Self {
Self::UnknownInternal { args: args.into() }
}

pub fn external(name: impl Into<String>, args: impl Into<Vec<String>>) -> Self {
Self::External {
name: name.to_string(),
args: args.to_vec(),
name: name.into(),
args: args.into(),
}
}

Expand All @@ -93,14 +89,14 @@ impl Command {
pub fn build(&self, env: &Env) -> Result<process::Command> {
match self {
Command::Internal { meta, args } => {
let mut command = internal_command()?;
let mut command = new_internal_command()?;
command.arg(meta.name);
command.args(args);
command.envs(env.internal());
Ok(command)
}
Command::UnknownInternal { args } => {
let mut command = internal_command()?;
let mut command = new_internal_command()?;
command.args(args);
command.envs(env.internal());
Ok(command)
Expand All @@ -115,7 +111,7 @@ impl Command {
}
}

fn internal_command() -> Result<process::Command> {
fn new_internal_command() -> Result<process::Command> {
let program = current_exe().context("could not detect current executable")?;
Ok(process::Command::new(program))
}
Expand Down
2 changes: 1 addition & 1 deletion src/spawn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl Spawned<Child> {
fn wait_context(&self, error: impl Into<Error>) -> Error {
self.context
.apply_to_err(error)
.context("child proces execution failed")
.context("child process execution failed")
}

pub fn kill(&mut self) -> Result<()> {
Expand Down
2 changes: 1 addition & 1 deletion src/stdbuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl StdBuf {

// This is probably the least invasive way how to force output line buffering on external commands (which use libc).
// 1. Run `stdbuf [args] env` and extract relevant environment variables from its output.
// 2. Run the external command with those same enviroment variables (as `stdbuf` would do).
// 2. Run the external command with those same environment variables (as `stdbuf` would do).
//
// Alternatively we could:
// a) Run external commands directly under `stdbuf`. This produces rather confusing error messages
Expand Down
2 changes: 1 addition & 1 deletion tests/examples.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::env;

#[test]
fn examples() {
for meta in rew::commands::COMMANDS {
for meta in rew::commands::METAS {
for example in meta.examples {
// Such examples require coreutils with NUL separator support
// which are not available on MacOS by default.
Expand Down
3 changes: 1 addition & 2 deletions xtask/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use command::Adapter;
use docs::generate_reference;
use docs::generate_summary;
use rew::app;
use rew::commands::COMMANDS;
use std::env;
use std::fs::create_dir_all;
use std::path::Path;
Expand Down Expand Up @@ -39,7 +38,7 @@ fn main() -> anyhow::Result<()> {

let cli = Cli::parse();

let mut app = app::build(COMMANDS);
let mut app = app::build();
app.build();

match cli.task {
Expand Down

0 comments on commit 25f64ad

Please sign in to comment.