/codeframe

Capture pretty code-frames.

Primary LanguageRustMIT LicenseMIT

Codeframe

Crates.io Rust CI

Capture pretty code-frames.

capture_codeframe!()

capture_codeframe!() makes use of line! and file! to capture the codeframe from the place it was originally invoked.

Imagine having a macro assert_equal!(left, right) that checks whether left is equal to right. We can use capture_codeframe!() to get code-frame of assert_equal!(left, right) invocation with some context.

It also accepts Color argument (capture_codeframe!(Color::Blue)) which will default to Color::Red.

use codeframe::{capture_codeframe, Color};

macro_rules! assert_equal {
    ($left:expr, $right:expr) => {{
        if $left != $right {
            let codeframe = capture_codeframe!(Color::Red);
            println!("Left does not match Right");
            if let Some(codeframe) = codeframe {
                println!("{}", codeframe)
            }
        } else {
            println!("Left and right are equal");
        }
    }};
}

fn with_context() {
    super::setup_test_env();
    assert_equal!(1, 2);
}

Note let codeframe = capture_codeframe!(Color::Red); in the assert_equal macro. This captures the code-frame where it was originally invoked. In our case, assert_equal!(1, 2);. So the output would be:

Output

Usage

  • capture_codeframe!()
  • capture_codeframe!(Color::Red)
  • capture_codeframe!(Color::Blue)

View currently supported colors

Codeframe with Snippets

You can also capture codeframes with code snippet by making use of the Builder Pattern.

let raw_lines = "macro_rules! test_simple_style {
    ($string:expr, $style:ident) => {
        #[test]
        fn $style() {
            assert_eq!(
                s.$style().to_string(),
                ansi_term::Style::new().$style().paint(s).to_string()
            )
        }
    };
}".to_owned();
let codeframe = Codeframe::new(raw_lines, 5).set_color(Color::Red).capture();

if let Some(codeframe) = codeframe {
    println!("{}", codeframe)
}

The Builder takes raw lines and line number(to highlight) as mandatory arguments. You can additionaly set the highlight color using set_color(Color::Red). This will result with the following:

Output

Usage

  • Codeframe::new(raw_lines, 5).capture();
  • Codeframe::new(raw_lines, 5).set_color(Color::Red).capture();
  • Codeframe::new(raw_lines, 5).set_color(Color::Blue).capture();

View currently supported colors

Return Type

Option<String>

Colors Supported

  • Black
  • Red
  • Green
  • Yellow
  • Blue
  • Magenta or (Purple)
  • Cyan
  • White

Features

Macro

Builder Pattern