Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v2): add pretty printing #701

Merged
merged 3 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ publish = false

[dependencies]
odict = { path = "../lib", features = [
"config",
"charabia",
"search",
"serve",
"dump",
"config",
"charabia",
"search",
"serve",
"dump",
] }
clap = { version = "4.4.18", features = ["derive", "cargo"] }
console = "0.15.8"
once_cell = "1.19.0"
indicatif = "0.17.8"
pulldown-cmark = "0.10.0"
5 changes: 3 additions & 2 deletions cli/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@ impl<'a> CLIContext<'a> {
alias_manager: Lazy::new(|| AliasManager::default()),
reader: Lazy::new(|| DictionaryReader::default()),
writer: Lazy::new(|| DictionaryWriter::default()),
stdout: Term::stdout(),
stderr: Term::stderr(),
stdout: Term::buffered_stdout(),
stderr: Term::buffered_stdout(),
}
}

pub fn println(&mut self, msg: String) {
self.stdout
.write_all(format!("{}\n", msg).as_bytes())
.unwrap();
self.stdout.flush().unwrap();
}
}
43 changes: 43 additions & 0 deletions cli/src/print/md.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use console::Style;
use odict::{MDString, MarkdownStrategy};
use pulldown_cmark::{Event, Parser, Tag};

pub fn print_md(md_string: &MDString) -> String {
let md = md_string.parse(MarkdownStrategy::Disabled);
let parser = Parser::new(&md);
let mut tags_stack = Vec::new();
let mut buffer = String::new();

for event in parser {
match event {
Event::Start(tag) => {
tags_stack.push(tag);
}
Event::End(_) => {
tags_stack.pop();
}
Event::Text(content) => {
let mut style = Style::new();

if tags_stack.contains(&Tag::Emphasis) {
style = style.italic();
}

if tags_stack.contains(&Tag::Strong) {
style = style.bold();
}

if tags_stack.contains(&Tag::Strikethrough) {
style = style.strikethrough();
}

buffer.push_str(&style.apply_to(&content).to_string());
}
Event::Code(content) => buffer.push_str(&content),
Event::SoftBreak => buffer.push(' '),
_ => (),
}
}

buffer.trim().to_string()
}
5 changes: 5 additions & 0 deletions cli/src/print/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod md;
mod pprint;
mod print;

pub use print::*;
236 changes: 236 additions & 0 deletions cli/src/print/pprint.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
use std::{borrow::Cow, error::Error};

use console::{style, Style};
use odict::{
Definition, DefinitionType, Entry, Etymology, Example, Group, MarkdownStrategy, Note, Sense,
};
use once_cell::sync::Lazy;

use crate::CLIContext;

use super::md::print_md;

const STYLE_POS: Lazy<Style> = Lazy::new(|| Style::new().italic());
const STYLE_TITLE: Lazy<Style> = Lazy::new(|| Style::new().bold().underlined());
const STYLE_EXAMPLE_BULLET: Lazy<Style> = Lazy::new(|| Style::new().dim());
const STYLE_EXAMPLE: Lazy<Style> = Lazy::new(|| STYLE_EXAMPLE_BULLET.clone().italic().dim());
const STYLE_EXAMPLE_TARGET: Lazy<Style> = Lazy::new(|| STYLE_EXAMPLE.clone().underlined());

fn divider() -> String {
"─".repeat(32)
}

fn index_to_alpha(i: usize) -> char {
(i as u8 + b'a') as char
}

fn underline_target(example: &str, target: &str) -> String {
let mut parts = Vec::new();
let mut last_index = 0;

for (index, _) in example.match_indices(target) {
parts.push(
STYLE_EXAMPLE
.apply_to(&example[last_index..index])
.to_string(),
);

parts.push(STYLE_EXAMPLE_TARGET.apply_to(target).to_string());

last_index = index + target.len();
}

if last_index < example.len() {
parts.push(STYLE_EXAMPLE.apply_to(&example[last_index..]).to_string());
}

let modified_string = parts.concat();

modified_string
}

fn indent<'a>(s: &'a str, width: usize) -> Cow<'a, str> {
let padding = " ".repeat(width);

s.lines()
.into_iter()
.map(|l| format!("{}{}", padding, l))
.collect::<Vec<String>>()
.join("\n")
.into()
}

fn print_note(
ctx: &CLIContext,
index: usize,
note: &Note,
entry: &Entry,
) -> Result<(), Box<dyn Error>> {
let out = &ctx.stdout;

out.write_line(&indent(
&format!(
"{}. {}",
index_to_alpha(index),
note.value.parse(MarkdownStrategy::Disabled)
),
6,
))?;

if note.examples.len() > 0 {
out.write_line("")?;

for example in (&note).examples.iter() {
print_example(ctx, 9, example, entry)?;
}
}

Ok(())
}

fn print_example(
ctx: &CLIContext,
indent_width: usize,
example: &Example,
entry: &Entry,
) -> Result<(), Box<dyn Error>> {
let out = &ctx.stdout;

let text = &format!(
"{} {}",
STYLE_EXAMPLE_BULLET.apply_to("▸").to_string(),
&underline_target(
&example.value.parse(MarkdownStrategy::Disabled),
&entry.term
)
);

out.write_line(&indent(&text, indent_width))?;

Ok(())
}

fn print_definition(
ctx: &CLIContext,
index: usize,
indent_width: usize,
use_alpha: bool,
definition: &Definition,
entry: &Entry,
) -> Result<(), Box<dyn Error>> {
let out = &ctx.stdout;

let numbering = match use_alpha {
false => (index + 1).to_string(),
true => index_to_alpha(index).to_string(),
};

let text = &format!("{}. {}", numbering, print_md(&definition.value));

out.write_line(&indent(text, indent_width))?;

for example in (&definition).examples.iter() {
print_example(ctx, indent_width + 3, example, entry)?;
}

if definition.notes.len() > 0 {
let header = &format!("\n{}\n\n", STYLE_TITLE.apply_to("Notes"));

out.write_line(&indent(header, indent_width + 3))?;

for (ndx, note) in (&definition).notes.iter().enumerate() {
print_note(ctx, ndx, note, entry)?;
}

out.write_line("")?;
}

Ok(())
}

fn print_group(
ctx: &CLIContext,
index: usize,
group: &Group,
entry: &Entry,
) -> Result<(), Box<dyn Error>> {
let out = &ctx.stdout;

let text = &format!(
"{}. {}",
index + 1,
group.description.parse(MarkdownStrategy::Disabled)
);

out.write_line(&indent(text, 2))?;

for (idx, definition) in group.definitions.iter().enumerate() {
print_definition(ctx, idx, 5, true, definition, entry)?;
}

Ok(())
}
fn print_sense(ctx: &CLIContext, sense: &Sense, entry: &Entry) -> Result<(), Box<dyn Error>> {
let out = &ctx.stdout;

out.write_line(&format!(
"\n{}\n",
STYLE_POS.apply_to(sense.pos.to_string()).italic()
))?;

for (idx, dt) in sense.definitions.iter().enumerate() {
match dt {
DefinitionType::Definition(d) => print_definition(ctx, idx, 2, false, d, entry)?,
DefinitionType::Group(g) => print_group(ctx, idx, g, entry)?,
}
}

Ok(())
}

fn print_ety(ctx: &CLIContext, etymology: &Etymology, entry: &Entry) -> Result<(), Box<dyn Error>> {
let out = &ctx.stdout;

if let Some(desc) = &etymology.description {
out.write_line(&format!("\n{}", &desc.parse(MarkdownStrategy::Disabled)))?;
}

for sense in etymology.senses.values() {
print_sense(ctx, sense, entry)?;
}

Ok(())
}

pub(super) fn pretty_print(
ctx: &CLIContext,
entries: Vec<Vec<Entry>>,
) -> Result<(), Box<dyn Error>> {
let out = &ctx.stdout;

for entry in entries.iter().flat_map(|e| e) {
out.write_line("")?;
out.write_line(&divider())?;
out.write_line(&format!("{}", style(&entry.term).bold()))?;
out.write_line(&divider())?;

let ety_count = entry.etymologies.len();

for (idx, etymology) in entry.etymologies.iter().enumerate() {
if ety_count > 1 {
out.write_line(
&STYLE_TITLE
.apply_to(&format!("\nEtymology #{}", idx + 1))
.to_string(),
)?;
}

print_ety(ctx, etymology, &entry)?;
}
}

out.flush()?;
// skin.print_text(&output);

Ok(())
}
3 changes: 2 additions & 1 deletion cli/src/print.rs → cli/src/print/print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use odict::{
Entry,
};

use super::pprint::pretty_print;
use crate::{enums::PrintFormat, CLIContext};

fn print_json(ctx: &mut CLIContext, entries: Vec<Vec<Entry>>) -> Result<(), Box<dyn Error>> {
Expand All @@ -30,7 +31,7 @@ pub fn print_entries(
format: &PrintFormat,
) -> Result<(), Box<dyn Error>> {
match format {
PrintFormat::Print => {}
PrintFormat::Print => pretty_print(ctx, entries)?,
PrintFormat::JSON => print_json(ctx, entries)?,
PrintFormat::XML => print_xml(ctx, entries)?,
}
Expand Down
2 changes: 1 addition & 1 deletion lib/src/json/definition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct DefinitionJSON {
pub value: MDString,

#[serde(skip_serializing_if = "Vec::is_empty")]
pub examples: Vec<String>,
pub examples: Vec<MDString>,

#[serde(skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<NoteJSON>,
Expand Down
3 changes: 1 addition & 2 deletions lib/src/json/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ pub struct GroupJSON {
#[serde(skip_serializing_if = "Option::is_none")]
id: Option<String>,

#[serde(skip_serializing_if = "Option::is_none")]
description: Option<MDString>,
description: MDString,

#[serde(skip_serializing_if = "Vec::is_empty")]
definitions: Vec<DefinitionJSON>,
Expand Down
2 changes: 1 addition & 1 deletion lib/src/json/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub struct NoteJSON {
value: MDString,

#[serde(skip_serializing_if = "Vec::is_empty")]
examples: Vec<String>,
examples: Vec<MDString>,
}

impl From<Note> for NoteJSON {
Expand Down
4 changes: 2 additions & 2 deletions lib/src/models/definition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ serializable! {
#[serde(rename = "@value")]
pub value: MDString,

#[serde(default)]
#[serde(default, rename="example")]
pub examples: Vec<Example>,

#[serde(default)]
#[serde(default, rename="note")]
pub notes: Vec<Note>,
}
}
Loading
Loading