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
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use crate::watcher;
use crate::TimeTracker;
use log::{debug, error, log, trace};
use notify::DebouncedEvent;
use std::collections::HashMap;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::mpsc::channel;
use std::sync::mpsc::TryRecvError;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;

mod git;

impl<'a> TimeTracker<'a> {
    pub fn track(&self) {
        let (tx, rx) = channel();

        let mut watchers = vec![]; // need to keep ownership of watchers so they aren't dropped at end of for-loop

        for track_path in &self.config.track_paths {
            // errors are silent here, but reported by timetrack config
            if let Ok(watcher) = watcher::get_watcher(track_path, tx.clone()) {
                watchers.push(watcher);
            }
        }

        let mut first_record_time;
        let write_delay = Duration::from_secs(2);

        loop {
            let mut events = vec![];

            // block waiting for the first event
            match rx.recv() {
                Ok(event) => {
                    first_record_time = Instant::now();
                    events.push(event);

                    // wait a small amount of additional time to see if other events come in
                    loop {
                        match rx.try_recv() {
                            Ok(event) => events.push(event),
                            Err(TryRecvError::Empty) => thread::sleep(Duration::from_millis(100)),
                            Err(e) => println!("watch error: {:?}", e),
                        };

                        if first_record_time.elapsed() >= write_delay {
                            break;
                        }
                    }
                }
                Err(e) => println!("watch error: {:?}", e),
            }

            events
                .iter()
                .filter_map(get_path_from_event)
                .filter_map(|path| match self.extract_project_name(path) {
                    None => None,
                    Some(project) => {
                        trace!("File change detected on {:?}", path);
                        Some((project, path))
                    }
                })
                .fold(HashMap::new(), |mut acc, (project, path)| {
                    acc.entry(project)
                        .or_insert_with(Vec::new)
                        .push(path.to_string_lossy().into_owned());

                    acc
                })
                .into_iter()
                .filter_map(|(project, paths)| {
                    let dir = match &paths.get(0) {
                        Some(path) => path.split(&project).next().unwrap().to_owned() + &project,
                        None => panic!("This vec should never be empty"),
                    };
                    if git::contains_file_which_would_not_be_ignored(dir, &paths) {
                        debug!("Found non-ignored changes for {:?}", project);
                        Some(project)
                    } else {
                        debug!("All changes to {:?} were git ignored", project);
                        None
                    }
                })
                .for_each(|project| self.store_project(&project));
        }
    }

    fn extract_project_name<T>(&self, path: T) -> Option<String>
    where
        T: AsRef<Path>,
    {
        let path = path.as_ref();
        let raw_data_file_path = PathBuf::from(&self.config.raw_data_path);
        // TODO handle file system separators in platform independent way
        if path != raw_data_file_path {
            for track_path in &self.config.track_paths {
                if let Ok(path) = path.strip_prefix(track_path) {
                    return Some(
                        path.components()
                            .next()
                            .expect("Path only contained root path")
                            .as_os_str()
                            .to_string_lossy()
                            .to_string(),
                    );
                };
            }

            panic!("Failed processing path which was not in configured track paths");
        }

        None
    }

    fn store_project(&self, project_name: &str) {
        let mut file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .append(true)
            .open(&self.config.raw_data_path)
            .unwrap();
        let time = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let log = format!("{}/{}", project_name, time);
        debug!("Log stored: {}", log);
        writeln!(&mut file, "{}", log).unwrap_or_else(|_| error!("Failed to write raw data"));
    }
}

fn get_path_from_event(event: &DebouncedEvent) -> Option<&Path> {
    match event {
        DebouncedEvent::Create(path) |
        DebouncedEvent::Write(path) |
        DebouncedEvent::Chmod(path) |
        DebouncedEvent::Remove(path) |
        DebouncedEvent::Rename(_, path) => { Some(path.as_ref()) }, // TODO use both paths from rename?
        DebouncedEvent::NoticeWrite(_) | // NoticeWrite and NoticeRemove both create duplicate entries for our use case
        DebouncedEvent::NoticeRemove(_) |
        DebouncedEvent::Rescan |
        DebouncedEvent::Error(_, _) => { None },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Configuration;

    #[test]
    fn extract_project_name_some() {
        let config = get_mock_config();
        let event_path = PathBuf::from(
            config
                .track_paths
                .get(0)
                .unwrap()
                .clone()
                .join("testProj/file1.rs"),
        );

        let tracker = TimeTracker::new(&config);

        assert_eq!(
            Some("testProj".to_string()),
            tracker.extract_project_name(event_path)
        );
    }

    #[test]
    fn extract_project_name_multiple_paths() {
        let config = get_mock_config();
        let event_path = PathBuf::from(
            config
                .track_paths
                .get(1)
                .unwrap()
                .clone()
                .join("testOtherProj/file1.rs"),
        );

        let tracker = TimeTracker::new(&config);

        assert_eq!(
            Some("testOtherProj".to_string()),
            tracker.extract_project_name(event_path)
        );
    }

    #[test]
    fn extract_project_name_none() {
        let config = get_mock_config();
        let event_path = PathBuf::from(config.raw_data_path.clone());

        let tracker = TimeTracker::new(&config);

        assert_eq!(None, tracker.extract_project_name(event_path));
    }

    fn get_mock_config() -> Configuration {
        Configuration::new_mock_config(
            vec![
                PathBuf::from("/Users/josh/Projects"),
                PathBuf::from("/Users/josh/OtherProjects"),
            ],
            PathBuf::from("/Users/josh/.timetrack_raw"),
            PathBuf::from("/Users/josh/.timetrack_processed"),
        )
    }
}