Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use app_dirs::{AppDataType, AppInfo};
- use std::env;
- use std::error::Error;
- use std::fs;
- use std::path::PathBuf;
- use std::str;
- use std::sync::mpsc;
- use std::time::Duration;
- use notify::{RecursiveMode, Watcher};
- 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() -> Result<(), Box<dyn Error>> {
- 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))?;
- watcher.watch(&paths.crashes_dir, RecursiveMode::Recursive)?;
- receive(rx, &paths)?;
- Ok(())
- }
- fn get_crashes_dir() -> Result<PathBuf, Box<dyn Error>> {
- 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)?;
- }
- Ok(crashes_dir)
- }
- fn get_count_file() -> Result<PathBuf, Box<dyn Error>> {
- let count_file = app_dirs::app_root(AppDataType::UserData, &APP_INFO)?.join("count.txt");
- if !count_file.exists() {
- fs::write(&count_file, b"0")?;
- }
- Ok(count_file)
- }
- fn receive(rx: Receiver, paths: &AppPaths) -> Result<(), Box<dyn Error>> {
- println!("Listening for events...");
- loop {
- match rx.recv() {
- Ok(event) => handle_event(event, paths)?,
- Err(error) => println!("Watch error: {:?}", error),
- }
- }
- }
- fn handle_event(event: Event, paths: &AppPaths) -> Result<(), Box<dyn Error>> {
- let count = match fs::read(&paths.count_file) {
- Ok(contents) => str::from_utf8(&contents)?.parse::<u128>()?,
- Err(_) => 0,
- } + 1;
- std::fs::write(&paths.count_file, count.to_string())?;
- println!("{:?} | count = {}", event, count);
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement