Skip to content

Colorized General MeTTa-run formatter #12

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

Merged
merged 4 commits into from
Aug 23, 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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ After running the setup script, you can start using Metta directly from the term
```bash
metta-run example.metta fct
```
- To format any output you get from metta-run:

```bash
metta-run example.metta f
```

- To run Metta without automatically activating the Python environment (you need to activate it manually first):

Expand Down
2 changes: 2 additions & 0 deletions metta-run/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ edition = "2021"
[dependencies]
chrono = "0.4.38"
clap = { version = "4.5.13", features = ["derive"] }
colored = "2.1.0"
regex = "1.10.6"
15 changes: 10 additions & 5 deletions metta-run/src/formatters/commands.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use clap::Subcommand;

use super::{binary_tree_formatter, constraint_tree_formatter, guardset_tree_formatter};
use super::{binary_tree_formatter, constraint_tree_formatter,guardset_tree_formatter, output_formater};

#[derive(Subcommand, Debug, Clone)]
pub enum FormatterCommands {
#[command(name = "f", about = "Format metta outputs")]
F,
#[command(name = "fbt", about = "Format binary tree")]
Fbt,

Expand All @@ -14,10 +16,13 @@ pub enum FormatterCommands {
Fgt,
}

pub fn format(metta_output: String, command: FormatterCommands) {
pub fn format(metta_output: (String, String), command: FormatterCommands) {
let (ref metta_output_stderr, ref metta_output_str) = metta_output;
let metta_augmented = format!("{}{}", metta_output_stderr, metta_output_str);
match command {
FormatterCommands::Fbt => binary_tree_formatter::format(metta_output),
FormatterCommands::Fct => constraint_tree_formatter::format(metta_output),
FormatterCommands::Fgt => guardset_tree_formatter::format(metta_output),
FormatterCommands::F => output_formater::format(metta_output),
FormatterCommands::Fbt => binary_tree_formatter::format(metta_augmented),
FormatterCommands::Fct => constraint_tree_formatter::format(metta_augmented),
FormatterCommands::Fgt => guardset_tree_formatter::format(metta_augmented),
}
}
1 change: 1 addition & 0 deletions metta-run/src/formatters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod binary_tree_formatter;
pub mod commands;
pub mod constraint_tree_formatter;
pub mod guardset_tree_formatter;
pub mod output_formater;
78 changes: 78 additions & 0 deletions metta-run/src/formatters/output_formater.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// use crate::runners;
use colored::Colorize;
use regex::Regex;

pub fn format(metta_output: (String, String)) {
let mut indent_level = 0;
let (metta_err, metta_str) = metta_output;


if !metta_err.is_empty() {
if let Some(last_line) = metta_err.lines().last() {
println!("{}", last_line.red());
}
}
if !metta_str.is_empty() {
selective_print(split_outputs(metta_str))
}
}

fn selective_print(outputs: Vec<String>) {
for output in outputs {
let formatted = prettify(&output);
let flag = ".";
if output.contains("(Error") {
println!("{} [{}]",flag.dimmed().bold().blue(), formatted.red());
} else {
println!("{} [{}]",flag.dimmed().bold().blue(), formatted.green());
}
}
}

fn split_outputs(output: String) -> Vec<String> {
// Define the regex pattern to match substrings in the form of [ SOMETHING]
let re = Regex::new(r"\[([^\]]+)\]").unwrap();

// Find all matches and collect them into a vector
let matches: Vec<String> = re
.captures_iter(&output)
.map(|caps| caps.get(1).map_or("", |m| m.as_str()).to_string())
.collect();

return matches;
}

fn prettify(input: &str) -> String {
let mut prettified = String::new();
let mut indent_level = 0;

for line in input.chars() {
match line {
'(' => {
prettified.push(line);
prettified.push('\n');
indent_level += 2;
prettified.push_str(&" ".repeat(indent_level));
}
')' => {
prettified.push('\n');
indent_level -= 2;
prettified.push_str(&" ".repeat(indent_level));
prettified.push(line);
}
';' => {
prettified.push('\n');
prettified.push_str(&" ".repeat(indent_level));
prettified.push(line);
}
' ' if prettified.ends_with('\n') => {
prettified.push_str(&" ".repeat(indent_level));
}
_ => {
prettified.push(line);
}
}
}

prettified
}
6 changes: 4 additions & 2 deletions metta-run/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,17 @@ fn main() -> io::Result<()> {

let start_time = tools::logger::start_timer();
let metta_output = runners::metta::run(file);
let (ref metta_output_stderr,ref metta_output_str) = metta_output;
let metta_augmented_output = format!("{}{}",metta_output_stderr,metta_output_str);

let _ = tools::logger::stop_timer(start_time, &metta_output);
let _ = tools::logger::stop_timer(start_time, &metta_augmented_output);

if let Some(command) = args.commands {
match command {
Commands::Format(command) => format(metta_output, command),
}
} else {
println!("{}", metta_output);
println!("{}", metta_augmented_output);
}
Ok(())
}
12 changes: 3 additions & 9 deletions metta-run/src/runners/metta.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::process::{Command, Stdio};
use std::{env, fs};

pub fn run(file_path: String) -> String {
pub fn run(file_path: String) -> (String , String) {
// cehck if the file exists
if !fs::metadata(&file_path).is_ok() {
eprintln!("File not found: {}", file_path);
Expand All @@ -25,19 +25,13 @@ pub fn run(file_path: String) -> String {
let metta_output_str = String::from_utf8_lossy(&metta_output.stdout);
let metta_output_stderr = String::from_utf8_lossy(&metta_output.stderr);

if !metta_output.status.success() {
eprintln!("{}", metta_output_stderr);
std::process::exit(1);
}

// Deactivate the virtual environment
Command::new("bash")
.arg("-c")
.arg("deactivate")
.output()
.expect("Failed to deactivate virtual environment");

format!("{}{}", metta_output_stderr, metta_output_str)
.trim()
.to_string()
( metta_output_stderr.trim().to_string(), metta_output_str.trim().to_string())

}
1 change: 0 additions & 1 deletion metta-run/tests/resources/binary_tree.metta
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
!(TreeNode (Value Nil False ROOT) Nil (Cons NilNode (Cons (TreeNode (Value Nil True OR) Nil (Cons (TreeNode (Value a False LITERAL) Nil Nil) (Cons (TreeNode (Value Nil True AND) Nil (Cons (TreeNode (Value b False LITERAL) Nil Nil) (Cons (TreeNode (Value c False LITERAL) Nil Nil) Nil))) Nil))) Nil)))

Loading