1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
//! A debug crate for rust inspired by NodeJS [debug](https://github.com/visionmedia/debug) module.
//!
//! ## Features
//! * colored
//! * including crate name, file name and line
//! * filtered by glob patterns.
//!
//! ## Usage
//! Here is an simple example in examples folder:
//!
//! ```rust
//! #[macro_use]
//! extern crate debug_rs;
//!
//!
//! fn main() {
//!     debug!(666, 33, "aaa");
//!
//!     debug!(vec![1, 2, 3]);
//! }
//! ```
//!
//! Then run it:
//!
//! ```sh
//! DEBUG=* cargo run
//! ```

#[macro_use]
extern crate lazy_static;
extern crate colored;
extern crate globset;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use globset::{Glob, GlobMatcher};
use colored::*;

lazy_static!{
    static ref DEBUG_MATHERS: (Vec<GlobMatcher>, Vec<GlobMatcher>) = ::std::env::var("DEBUG")
        .unwrap_or(String::new())
        .as_str()
        .split(',')
        .fold((vec![], vec![]), |mut acc, s| {
            if s.len() > 1 && &s[0..1] == "-" {
                acc.1.push(Glob::new(&s[1..])
                            .unwrap()
                            .compile_matcher());
            } else if s.len() > 0 {
                acc.0.push(Glob::new(s)
                            .unwrap()
                            .compile_matcher());
            }
            acc
        });
}

fn get_color(s: &str) -> &str {
    let colors = vec![
        "black",
        "red",
        "green",
        "yellow",
        "blue",
        "magenta",
        "cyan",
        "white",
    ];
    let mut hasher = DefaultHasher::new();
    s.hash(&mut hasher);
    let hash = hasher.finish() as usize;
    return colors[hash % colors.len()];
}

pub fn debug_meta(pkg: &str, file: &str, line: u32) {
    print!(
        "{}:{}:L{} ",
        String::from(pkg).color(get_color(pkg)).bold(),
        String::from(file).color(get_color(file)),
        line
    );
}

pub fn is_debug(pkg_name: &str, file: &str) -> bool {
    let meta = format!("{}:{}", pkg_name, file);
    return !DEBUG_MATHERS.1.iter().any(|g| g.is_match(&meta)) &&
        DEBUG_MATHERS.0.iter().any(|g| g.is_match(&meta));
}

/// Debug variables depends on environment variable `DEBUG`, using glob pattern to filter output.
///
/// e.g.
///
/// ```
///   #[macro_use]
/// extern crate debug_rs;
///
/// fn main() {
///     debug!(666, 33, "aaa");
///
///     debug!(vec![1, 2, 3]);
/// }
/// ```
///
/// Then running:
///
/// ```sh
/// DEBUG=*,-not_this cargo run // for *unix
/// // or
/// set DEBUG=*,-not_this; cargo run // for windows
/// // or
/// $env:DEBUG = "*,-not_this"; cargo run // for PowerShell
/// ```
///
#[macro_export]
macro_rules! debug {
    ( $( $x:expr ),* ) => {
        #[cfg(any(not(feature = "debug_build_only"), debug_assertions))]
        #[cfg(not(feature = "disable"))]
        {
            let pkg_name = env!("CARGO_PKG_NAME");
            let file = file!();
            if $crate::is_debug(pkg_name, file) {
                $crate::debug_meta(pkg_name, file, line!());
                $(
                    print!(" {:?}", $x);
                )*
                print!("\n");
            }
        }
    };
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        debug!("aaa", 123, "bbb");

        debug!(vec![1, 2, 3]);
    }
}