Skip to content

Instantly share code, notes, and snippets.

@matematikaadit
Last active January 7, 2017 21:20
Show Gist options
  • Save matematikaadit/7083050a98113f3bb72f3d62615411b0 to your computer and use it in GitHub Desktop.
Save matematikaadit/7083050a98113f3bb72f3d62615411b0 to your computer and use it in GitHub Desktop.
Fixing irc log

Commands:

wget -O original.log url/to/raw
cargo build --release
target/release/fixlog original.log > fixed.log
[package]
name = "fixlog"
version = "0.1.0"
license = "MIT"
authors = ["Adit Cahya Ramadhan <[email protected]>"]
[[bin]]
name = "fixlog"
path = "main.rs"
[dependencies]
regex = "0.2.1"
extern crate regex;
use regex::{Regex, Captures};
use std::io::Read;
use std::fs::File;
use std::env;
macro_rules! debug {
($($arg:tt)*) => {
{
use std::io::Write;
let _ = writeln!(std::io::stderr(), $($arg)*);
}
}
}
fn replace_lines() {
let re = Regex::new(
r"(?xm) # insignificant whitespace and multiline mode
^ # treated as the `start` of the line
(?P<before>
\[ # start with opening square bracket
# Date part
\d{4} # year
-
\d{2} # month
-
) # end of before named capture
(?P<day>\d{2}) # day
(?-x: ) # separated by space
# Time part
(?P<hour>\d{2}) # hour
(?P<after>
:
\d{2} # minutes
:
\d{2} # seconds
(?-x: )
# Time zone part
[A-Z]+ # time zone abbrev
\] # end of square bracket
.* # and anything after that
) # end of `after` named capture
$ # end of the line
"
).expect("Regex error");
let buffer = file_content();
let mut total = 0;
let mut prev: Option<(u8, u8)> = None;
let mut hourtime = false;
let result = re.replace_all(&buffer, |cap: &Captures| {
total += 1;
let day = cap.name("day").unwrap().as_str().parse().unwrap();
let mut hour = cap.name("hour").unwrap().as_str().parse().unwrap();
if prev > Some((day, hour)) {
hour += 12;
} else if let Some((prevday, _)) = prev {
if (prevday + 1 == day || hourtime) && hour >= 12 {
hourtime = true;
hour -= 12;
} else {
hourtime = false;
}
}
prev = Some((day, hour));
let before = cap.name("before").unwrap().as_str();
let after = cap.name("after").unwrap().as_str();
format!("{before}{day:02} {hour:02}{after}",
before=before,
after=after,
day=day,
hour=hour
)
});
debug!("Total lines: {}", total);
print!("{}", result);
}
fn file_content() -> String {
let filename = env::args().nth(1).expect("No filename supplied");
debug!("Filename: {}", filename);
let mut file = File::open(filename).expect("Can't open file");
let mut buffer = String::new();
file.read_to_string(&mut buffer).unwrap();
buffer
}
fn main() {
replace_lines();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment