Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use app_dirs::{AppDataType, AppInfo};
- use std::env;
- use std::fs;
- use std::path::PathBuf;
- use std::str;
- use std::sync::mpsc;
- use std::sync::mpsc::RecvError;
- use std::time::Duration;
- use notify::{RecursiveMode, Watcher};
- // type Sender = mpsc::Sender<notify::DebouncedEvent>;
- type Receiver = mpsc::Receiver<notify::DebouncedEvent>;
- type Event = notify::DebouncedEvent;
- const APP_INFO: AppInfo = AppInfo {
- name: "crash_counter",
- author: "Wagner",
- };
- struct AppPaths {
- crashes_dir: PathBuf,
- count_file: PathBuf,
- }
- fn main() {
- let paths = AppPaths {
- crashes_dir: get_crashes_dir(),
- count_file: get_count_file(),
- };
- // Create a channel to receive the events.
- let (tx, rx) = mpsc::channel();
- // Create a watcher object, delivering debounced events.
- // The notification back-end is selected based on the platform.
- let mut watcher = notify::watcher(tx, Duration::from_secs(10)).unwrap();
- watcher
- .watch(&paths.crashes_dir, RecursiveMode::Recursive)
- .unwrap();
- receive(rx, &paths);
- }
- fn get_crashes_dir() -> PathBuf {
- let temp_dir = env::temp_dir();
- let crashes_dir = temp_dir.join("Unity").join("Editor").join("Crashes");
- if !crashes_dir.exists() {
- println!("Creating directory: {:?}", crashes_dir);
- fs::create_dir_all(&crashes_dir)
- .expect(&format!("Failed to create directory: {:?}", &crashes_dir));
- }
- crashes_dir
- }
- fn get_count_file() -> PathBuf {
- let count_file = app_dirs::app_root(AppDataType::UserData, &APP_INFO)
- .expect("Couldn't create app directory.")
- .join("count.txt");
- if !count_file.exists() {
- std::fs::write(&count_file, b"0")
- .expect(&format!("Failed to write file: {:?}", count_file));
- }
- count_file
- }
- fn receive(rx: Receiver, paths: &AppPaths) {
- println!("Listening for events...");
- loop {
- match rx.recv() {
- Ok(event) => handle_event(event, paths),
- Err(error) => handle_recv_error(error),
- }
- }
- }
- fn handle_event(event: Event, paths: &AppPaths) {
- let read_result = std::fs::read(&paths.count_file);
- let count = match read_result {
- Ok(contents) => str::from_utf8(&contents)
- .expect(&format!("Failed to read file: {:?}", paths.count_file))
- .parse::<u128>()
- .expect(&format!("Failed to parse file: {:?}", paths.count_file)),
- Err(_) => 0,
- } + 1;
- std::fs::write(&paths.count_file, count.to_string())
- .expect(&format!("Failed to write file: {:?}", paths.count_file));
- println!("{:?} | count = {}", event, count);
- }
- fn handle_recv_error(error: RecvError) {
- println!("Watch error: {:?}", error);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement