index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
gitrs / src / app.rs
-rw-r--r-- blob d0aedeb019650ea8bc23f071f49a3cf1ac7bf01c 6788 bytes (plain)
1
use std::{
2
    collections::HashMap,
3
    fs,
4
    path::{Path, PathBuf},
5
    sync::{Arc, RwLock},
6
    time::Duration,
7
};
8
9
use notify::{
10
    Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher,
11
    event::{CreateKind, ModifyKind, RemoveKind, RenameMode},
12
};
13
use tokio::sync::mpsc;
14
15
use crate::{error::Error, git::repository::Repository};
16
17
pub struct App {
18
    pub repos_dir: String,
19
    pub repos: Arc<RwLock<Vec<Repository>>>,
20
21
    _watcher: RecommendedWatcher,
22
}
23
24
impl App {
25
    pub async fn new(repos_dir: String) -> Self {
26
        let repos: Arc<RwLock<Vec<Repository>>> = Arc::new(RwLock::new(scan_repos(&repos_dir)));
27
        let watch_repos = repos.clone();
28
29
        let (tx, mut rx) = mpsc::unbounded_channel::<Event>();
30
31
        let mut watcher =
32
            notify::recommended_watcher(move |res: notify::Result<Event>| match res {
33
                Ok(event) => {
34
                    let _ = tx.send(event);
35
                }
36
                Err(e) => eprintln!("repo watcher error: {e}"),
37
            })
38
            .expect("Failed to create repo directory watcher");
39
40
        watcher
41
            .watch(Path::new(&repos_dir), RecursiveMode::NonRecursive)
42
            .expect("Failed to watch repos directory");
43
44
        tokio::spawn(async move {
45
            let mut pending_creates: HashMap<PathBuf, tokio::task::JoinHandle<()>> = HashMap::new();
46
47
            while let Some(event) = rx.recv().await {
48
                match event.kind {
49
                    EventKind::Create(CreateKind::Folder) => {
50
                        for path in event.paths {
51
                            if let Some(handle) = pending_creates.remove(&path) {
52
                                handle.abort();
53
                            }
54
55
                            let repos_for_task = watch_repos.clone();
56
                            let path_for_task = path.clone();
57
58
                            let handle = tokio::spawn(async move {
59
                                Self::try_add_repo_when_ready(repos_for_task, path_for_task).await;
60
                            });
61
62
                            pending_creates.insert(path, handle);
63
                        }
64
                    }
65
                    EventKind::Remove(RemoveKind::Folder) => match watch_repos.write() {
66
                        Ok(mut guard) => {
67
                            let before = guard.len();
68
                            let removed: Vec<_> = guard
69
                                .iter()
70
                                .filter(|r| event.paths.contains(&r.path))
71
                                .map(|r| (r.name.clone(), r.path.clone()))
72
                                .collect();
73
74
                            guard.retain(|r| !event.paths.contains(&r.path));
75
76
                            for (name, path) in &removed {
77
                                println!("[watcher] - removed repo: {name} ({path:?})");
78
                            }
79
                            println!("[watcher] repo count now: {} (was {before})", guard.len());
80
                        }
81
                        Err(e) => eprintln!("[watcher] repo cache lock poisoned: {e}"),
82
                    },
83
                    EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => {
84
                        if let [old_path, new_path] = event.paths.as_slice() {
85
                            let (old_path, new_path) = (old_path.clone(), new_path.clone());
86
87
                            match watch_repos.write() {
88
                                Ok(mut guard) => guard.retain(|r| r.path != old_path),
89
                                Err(e) => eprintln!("[watcher] repo cache lock poisoned: {e}"),
90
                            }
91
92
                            let repos_for_task = watch_repos.clone();
93
                            tokio::spawn(async move {
94
                                Self::try_add_repo_when_ready(repos_for_task, new_path).await;
95
                            });
96
97
                            println!("[watcher] ~ rename detected: {old_path:?} -> ...");
98
                        }
99
                    }
100
                    _ => {}
101
                }
102
            }
103
        });
104
105
        Self {
106
            repos_dir,
107
            repos,
108
            _watcher: watcher,
109
        }
110
    }
111
112
    async fn try_add_repo_when_ready(watch_repos: Arc<RwLock<Vec<Repository>>>, path: PathBuf) {
113
        const MAX_ATTEMPTS: u32 = 30; // e.g. 30 * 1s = up to 30s for a big clone
114
        const POLL_INTERVAL: Duration = Duration::from_secs(1);
115
        const QUIET_CHECKS_REQUIRED: u32 = 2; // must succeed N times in a row (dir stopped changing)
116
117
        let mut consecutive_ok = 0;
118
119
        for attempt in 0..MAX_ATTEMPTS {
120
            tokio::time::sleep(POLL_INTERVAL).await;
121
122
            match Repository::open(&path) {
123
                Ok(repo) => {
124
                    consecutive_ok += 1;
125
                    if consecutive_ok >= QUIET_CHECKS_REQUIRED {
126
                        match watch_repos.write() {
127
                            Ok(mut guard) => {
128
                                println!("[watcher] + added repo: {} ({:?})", repo.name, path);
129
                                guard.push(repo);
130
                                println!("[watcher] repo count now: {}", guard.len());
131
                            }
132
                            Err(e) => eprintln!("[watcher] repo cache lock poisoned: {e}"),
133
                        }
134
                        return;
135
                    }
136
                }
137
                Err(_) => {
138
                    // not ready yet (mid-clone) — reset streak and keep polling
139
                    consecutive_ok = 0;
140
                }
141
            }
142
143
            if attempt == MAX_ATTEMPTS - 1 {
144
                eprintln!("[watcher] gave up waiting for repo to become ready: {path:?}");
145
            }
146
        }
147
    }
148
149
    pub fn find_repo(&self, name: &str) -> Option<Repository> {
150
        self.repos
151
            .read()
152
            .ok()?
153
            .iter()
154
            .find(|r| r.name == name)
155
            .cloned()
156
    }
157
158
    pub fn get_repo(&self, name: &str) -> Result<Repository, Error> {
159
        self.find_repo(name)
160
            .ok_or_else(|| Error::NotFound("Repo not found".to_string()))
161
    }
162
}
163
164
fn scan_repos(repos_dir: &str) -> Vec<Repository> {
165
    let entries = fs::read_dir(repos_dir).unwrap();
166
167
    let repos: Vec<Repository> = entries
168
        .filter_map(|e| e.ok())
169
        .filter(|e| e.path().is_dir())
170
        .filter_map(|e| {
171
            let name = e.file_name();
172
            let path = e.path();
173
            match Repository::open(&path) {
174
                Ok(repo) => Some(repo),
175
                Err(e) => {
176
                    eprintln!("Failed to open repo {:?}: {:?}", name, e);
177
                    None
178
                }
179
            }
180
        })
181
        .collect();
182
183
    repos
184
}