Last active
October 29, 2023 21:46
-
-
Save lemon-sh/1994cbfa6e95daa43fadfe5c09cb82ae to your computer and use it in GitHub Desktop.
Rust program to convert text with ANSI sequences into Minecraft /tellraw JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{stdin, Read}; | |
use cansi::v3::*; | |
use serde::Serialize; | |
fn cansi_to_mc_color(color: Color) -> &'static str { | |
match color { | |
Color::Black => "black", | |
Color::Red => "red", | |
Color::Green => "green", | |
Color::Yellow => "gold", | |
Color::Blue => "blue", | |
Color::Magenta => "light_purple", | |
Color::Cyan => "aqua", | |
Color::White => "white", | |
Color::BrightBlack => "gray", | |
Color::BrightRed => "red", | |
Color::BrightGreen => "green", | |
Color::BrightYellow => "yellow", | |
Color::BrightBlue => "blue", | |
Color::BrightMagenta => "light_purple", | |
Color::BrightCyan => "aqua", | |
Color::BrightWhite => "white", | |
} | |
} | |
fn cansi_intensity_bool(intensity: Intensity) -> bool { | |
match intensity { | |
Intensity::Bold => true, | |
Intensity::Normal => false, | |
Intensity::Faint => false, | |
} | |
} | |
#[derive(Serialize)] | |
struct TellrawBlock<'a> { | |
text: &'a str, | |
#[serde(skip_serializing_if = "Option::is_none")] | |
color: Option<&'a str>, | |
#[serde(skip_serializing_if = "Option::is_none")] | |
underlined: Option<bool>, | |
#[serde(skip_serializing_if = "Option::is_none")] | |
italic: Option<bool>, | |
#[serde(skip_serializing_if = "Option::is_none")] | |
bold: Option<bool>, | |
#[serde(skip_serializing_if = "Option::is_none")] | |
strikethrough: Option<bool>, | |
} | |
fn main() { | |
let mut input = String::new(); | |
stdin().read_to_string(&mut input).unwrap(); | |
let ansi_blocks = categorise_text(&input); | |
let mut tellraw_blocks = Vec::with_capacity(ansi_blocks.len()); | |
for block in ansi_blocks { | |
tellraw_blocks.push(TellrawBlock { | |
text: block.text, | |
color: block.fg.map(cansi_to_mc_color), | |
underlined: block.underline, | |
italic: block.italic, | |
bold: block.intensity.map(cansi_intensity_bool), | |
strikethrough: block.strikethrough, | |
}) | |
} | |
println!("{}", serde_json::to_string(&tellraw_blocks).unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment