Change closure from Fn to FnMut. (#5)

* Using FnMut, so works
* Using FnMut for watch() and reopen_if_log_rotated()
* adding fn to force reopen
* adding actions to closure

Co-authored-by: noyez <brad@bkn.local>
Co-authored-by: noyez <brad@bkn.localdomain>
Co-authored-by: Bradley Noyes <b@noyes.dev>
This commit is contained in:
noyez 2020-08-21 02:42:11 -04:00 committed by GitHub
parent 7c288c8d1e
commit 6f8f9bd75d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 8 deletions

View file

@ -1,6 +1,6 @@
[package]
name = "logwatcher"
version = "0.1.0"
version = "0.1.1"
authors = ["Aravinda VK <mail@aravindavk.in>"]
description = "A lib to watch log files for new Changes, just like tail -f"

View file

@ -8,6 +8,11 @@ use std::os::unix::fs::MetadataExt;
use std::thread::sleep;
use std::time::Duration;
pub enum LogWatcherAction{
None,
SeekToEnd,
}
pub struct LogWatcher {
filename: String,
inode: u64,
@ -40,9 +45,9 @@ impl LogWatcher {
})
}
fn reopen_if_log_rotated<F: ?Sized>(&mut self, callback: &F)
fn reopen_if_log_rotated<F: ?Sized>(&mut self, callback: &mut F)
where
F: Fn(String),
F: FnMut(String) -> LogWatcherAction,
{
loop {
match File::open(self.filename.clone()) {
@ -78,9 +83,9 @@ impl LogWatcher {
}
}
pub fn watch<F: ?Sized>(&mut self, callback: &F)
pub fn watch<F: ?Sized>(&mut self, callback: &mut F)
where
F: Fn(String),
F: FnMut(String) -> LogWatcherAction,
{
loop {
let mut line = String::new();
@ -90,7 +95,15 @@ impl LogWatcher {
if len > 0 {
self.pos += len as u64;
self.reader.seek(SeekFrom::Start(self.pos)).unwrap();
callback(line.replace("\n", ""));
match callback(line.replace("\n", ""))
{
LogWatcherAction::SeekToEnd => {
println!("SeekToEnd");
self.reader.seek(SeekFrom::End(0)).unwrap();
}
LogWatcherAction::None => {
}
}
line.clear();
} else {
if self.finish {

View file

@ -2,7 +2,7 @@ use std::env::args;
use std::process::exit;
extern crate logwatcher;
use logwatcher::LogWatcher;
use logwatcher::{LogWatcher, LogWatcherAction};
fn main() {
let filename = match args().nth(1) {
@ -15,7 +15,8 @@ fn main() {
let mut log_watcher = LogWatcher::register(filename).unwrap();
log_watcher.watch(&|line: String| {
log_watcher.watch(&mut move |line: String| {
println!("Line {}", line);
LogWatcherAction::None
});
}