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
use rlua::prelude::*; use std::{ fs, io::{self, BufRead} }; use chrono::{DateTime, Local}; use diff_rs::diff; fn time_format(d: &DateTime<Local>) -> String { d.format("%Y-%m-%d %H:%M:%S.%f %z").to_string() } fn mtime(path: &str) -> crate::Result<DateTime<Local>> { Ok(DateTime::from(fs::metadata(path)?.modified()?)) } fn read_file(path: &str) -> io::Result<Vec<String>> { let file = fs::File::open(path)?; let file = io::BufReader::new(file); file.lines().collect() } pub fn init(lua: &Lua) -> crate::Result<()> { let module = lua.create_table()?; module.set("compare_strings", lua.create_function( |_, (left, right): (String, String)| { let prefix = vec![ format!("--- a\t{}", time_format(&Local::now())), format!("+++ b\t{}", time_format(&Local::now())) ]; let diff = diff( &left .split("\n") .map(str::to_owned) .collect::<Vec<_>>(), &right .split("\n") .map(str::to_owned) .collect::<Vec<_>>(), 3 ).map_err(LuaError::external)?; let mut res = String::new(); prefix.iter().cloned().chain(diff).for_each(|s| { res.push_str(&s); res.push('\n') }); Ok(res) })?)?; module.set("compare_files", lua.create_function( |_, (left, right): (String, String)| { let prefix = vec![ format!("--- {}\t{}", &left, time_format(&mtime(&left).map_err(LuaError::external)?)), format!("+++ {}\t{}", &right, time_format(&mtime(&right).map_err(LuaError::external)?)) ]; let left = read_file(&left).map_err(LuaError::external)?; let right = read_file(&right).map_err(LuaError::external)?; let diff = diff(&left, &right, 3).map_err(LuaError::external)?; let mut res = String::new(); prefix.iter().cloned().chain(diff).for_each(|s| { res.push_str(&s); res.push('\n') }); Ok(res) })?)?; lua.globals().set("diff", module)?; Ok(()) }