-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathproject_file_builder.rs
More file actions
75 lines (61 loc) · 2 KB
/
project_file_builder.rs
File metadata and controls
75 lines (61 loc) · 2 KB
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
use error_stack::Result;
use lazy_static::lazy_static;
use regex::Regex;
use std::path::{Path, PathBuf};
use crate::{
cache::{Cache, Caching},
project::{Error, ProjectFile},
};
pub struct ProjectFileBuilder<'a> {
global_cache: &'a Cache,
}
lazy_static! {
static ref TEAM_REGEX: Regex = Regex::new(r#"^(?:#|//) @team (.*)$"#).expect("error compiling regular expression");
}
impl<'a> ProjectFileBuilder<'a> {
pub fn new(global_cache: &'a Cache) -> Self {
Self { global_cache }
}
pub(crate) fn build(&self, path: PathBuf) -> ProjectFile {
if let Ok(Some(cached_project_file)) = self.get_project_file_from_cache(&path) {
return cached_project_file;
}
let project_file = build_project_file_without_cache(&path);
self.save_project_file_to_cache(&path, &project_file);
project_file
}
fn get_project_file_from_cache(&self, path: &Path) -> Result<Option<ProjectFile>, Error> {
self.global_cache.get_file_owner(path).map(|entry| {
entry.map(|e| ProjectFile {
path: path.to_path_buf(),
owner: e.owner,
})
})
}
fn save_project_file_to_cache(&self, path: &Path, project_file: &ProjectFile) {
self.global_cache.write_file_owner(path, project_file.owner.clone());
}
}
pub(crate) fn build_project_file_without_cache(path: &PathBuf) -> ProjectFile {
let content = match std::fs::read_to_string(path) {
Ok(content) => content,
Err(_) => {
return ProjectFile {
path: path.clone(),
owner: None,
};
}
};
let first_line = content.lines().next();
let Some(first_line) = first_line else {
return ProjectFile {
path: path.clone(),
owner: None,
};
};
let owner = TEAM_REGEX
.captures(first_line)
.and_then(|cap| cap.get(1))
.map(|m| m.as_str().to_string());
ProjectFile { path: path.clone(), owner }
}