Skip to content

Commit

Permalink
chore(terminal): Use 'wrap' semantics for terminal width (#426)
Browse files Browse the repository at this point in the history
  • Loading branch information
scarmuega authored Sep 10, 2022
1 parent f45b080 commit 66e91c3
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 39 deletions.
2 changes: 2 additions & 0 deletions book/src/sinks/terminal.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ A sink that outputs each event into the terminal through stdout using fancy colo
[sink]
type = "Terminal"
throttle_min_span_millis = 500
wrap = true
```

- `type` (required): the literal value `Terminal`.
- `throttle_min_span_millis` (optional, default = `500`): the amount of time (milliseconds) to wait between printing each event into the console. This is used to facilitate the reading for human following the output.
- `wrap` (optional, default = `false`): a true value indicates that long output text should break and continue in the following line. If false, lines will be truncated to fit in the available terminal width.
2 changes: 1 addition & 1 deletion book/src/usage/watch.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ oura watch [OPTIONS] <socket>
- `--magic <magic>`: the magic number of the network you're connecting to. Possible values are `mainnet`, `testnet`, `preview`, `preprod` or a numeric value. If omitted, the value `mainnet` is used as default.
- `--mode <mode>`: an option to force the which set of mini-protocols to use when connecting to the Cardano node. Possible values: `node` and `client`. If omitted, _Oura_ will infer the standard protocols for the specified bearer.
- `--since <slot>,<hash>`: an option to specify from which point in the chain _Oura_ should start reading from. The point is referenced by passing the slot of the block followed by a comma and the hash of the block (`<slot>,<hash>`). If omitted, _Oura_ will start reading from the tail (tip) of the node.

- `--wrap`: indicates that long output text should break and continue in the following line. If omitted, lines will be truncated to fit in the available terminal width.

## Examples

Expand Down
17 changes: 7 additions & 10 deletions src/bin/oura/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,7 @@ pub fn run(args: &ArgMatches) -> Result<(), Error> {
false => None,
};

let terminal_width = match args.is_present("terminal-width") {
true => Some(args.value_of_t("terminal-width")?),
false => None
};
let wrap = args.is_present("wrap");

let mapper = MapperConfig {
include_block_end_events: true,
Expand Down Expand Up @@ -119,7 +116,7 @@ pub fn run(args: &ArgMatches) -> Result<(), Error> {

let sink_setup = oura::sinks::terminal::Config {
throttle_min_span_millis: throttle,
terminal_width: terminal_width
wrap: Some(wrap),
};

let (source_handle, source_output) = match source_setup {
Expand Down Expand Up @@ -159,16 +156,16 @@ pub(crate) fn command_definition<'a>() -> clap::Command<'a> {
.help("milliseconds to wait between output lines (for easier reading)"),
)
.arg(
clap::Arg::new("terminal-width")
.long("terminal-width")
.takes_value(true)
.help("width of the terminal"),
clap::Arg::new("wrap")
.long("wrap")
.short('w')
.takes_value(false)
.help("long text output should break and continue in the following line"),
)
.arg(
clap::Arg::new("mode")
.long("mode")
.takes_value(true)
.possible_values(&["node", "client"]),
)

}
26 changes: 8 additions & 18 deletions src/sinks/terminal/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ pub struct LogLine {
tx_idx: Option<usize>,
block_num: Option<u64>,
content: String,
max_width: usize,
max_width: Option<usize>,
}

impl LogLine {
fn new_raw(
source: &Event,
prefix: &'static str,
color: Color,
max_width: usize,
max_width: Option<usize>,
content: String,
) -> Self {
LogLine {
Expand All @@ -41,7 +41,7 @@ impl LogLine {
}

impl LogLine {
pub fn new(source: &Event, max_width: usize, utils: &Utils) -> LogLine {
pub fn new(source: &Event, max_width: Option<usize>, utils: &Utils) -> LogLine {
match &source.data {
EventData::Block(BlockRecord {
era,
Expand Down Expand Up @@ -361,8 +361,6 @@ impl LogLine {

impl Display for LogLine {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let flex_width = self.max_width - 40;

format!(
"BLOCK:{:0>7} █ TX:{:0>2}",
self.block_num
Expand All @@ -387,20 +385,12 @@ impl Display for LogLine {
f.write_char(' ')?;

{
let max_width = std::cmp::min(self.content.len(), flex_width);
let available_width = self.max_width.map(|x| x - 35);

match self.content.len() {
x if x > max_width => {
let wrapped: String = self.content
.chars()
.enumerate()
.fold(String::new(), |acc, (i, c)| {
if i != 0 && i % max_width == 0 {
format!("{}\n{}", acc, c)
} else {
format!("{}{}", acc, c)
}
});
match available_width {
Some(width) if width < self.content.len() => {
let wrapped = &self.content[..width];
let wrapped = format!("{wrapped}...");
wrapped.with(Color::Grey).fmt(f)?;
}
_ => {
Expand Down
11 changes: 5 additions & 6 deletions src/sinks/terminal/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use super::format::*;

pub fn reducer_loop(
throttle_min_span: Duration,
terminal_width: Option<u16>,
wrap: bool,
input: StageReceiver,
utils: Arc<Utils>,
) -> Result<(), Error> {
Expand All @@ -28,14 +28,13 @@ pub fn reducer_loop(
))?;

for evt in input.iter() {

let width = match terminal_width {
Some(w) => w,
None => crossterm::terminal::size()?.0
let width = match wrap {
true => None,
false => Some(crossterm::terminal::size()?.0 as usize),
};

throttle.wait_turn();
let line = LogLine::new(&evt, width as usize, &utils);
let line = LogLine::new(&evt, width, &utils);

let result = stdout.execute(Print(line));

Expand Down
7 changes: 3 additions & 4 deletions src/sinks/terminal/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const THROTTLE_MIN_SPAN_MILLIS: u64 = 300;
#[derive(Default, Debug, Deserialize)]
pub struct Config {
pub throttle_min_span_millis: Option<u64>,
pub terminal_width: Option<u16>
pub wrap: Option<bool>,
}

impl SinkProvider for WithUtils<Config> {
Expand All @@ -25,12 +25,11 @@ impl SinkProvider for WithUtils<Config> {
.unwrap_or(THROTTLE_MIN_SPAN_MILLIS),
);

let terminal_width = self.inner.terminal_width;

let wrap = self.inner.wrap.unwrap_or(false);
let utils = self.utils.clone();

let handle = std::thread::spawn(move || {
reducer_loop(throttle_min_span, terminal_width, input, utils).expect("terminal sink loop failed");
reducer_loop(throttle_min_span, wrap, input, utils).expect("terminal sink loop failed");
});

Ok(handle)
Expand Down

0 comments on commit 66e91c3

Please sign in to comment.