-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_util.rs
More file actions
108 lines (90 loc) · 2.92 KB
/
file_util.rs
File metadata and controls
108 lines (90 loc) · 2.92 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
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
use std::path::{Path, PathBuf};
use rohas_parser::{Parser, Schema};
use tracing::info;
pub fn find_config_file(start_dir: &Path) -> Option<PathBuf> {
let mut current = if start_dir.is_absolute() {
start_dir.to_path_buf()
} else {
std::env::current_dir()
.ok()?
.join(start_dir)
.canonicalize()
.ok()?
};
if current.is_file() {
current = current.parent()?.to_path_buf();
}
if current.is_dir() {
if let Ok(entries) = std::fs::read_dir(¤t) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let config_path = path.join("config").join("rohas.toml");
if config_path.exists() {
return Some(config_path);
}
}
}
}
}
loop {
let config_path = current.join("config").join("rohas.toml");
if config_path.exists() {
return Some(config_path);
}
match current.parent() {
Some(parent) => current = parent.to_path_buf(),
None => break,
}
}
None
}
pub fn parse_directory(dir: &PathBuf) -> anyhow::Result<Schema> {
let mut combined_schema = Schema::new();
let mut file_count = 0;
visit_ro_files(dir, &mut |path| {
info!("Parsing: {}", path.display());
match Parser::parse_file(path) {
Ok(schema) => {
// Merge schemas
combined_schema.models.extend(schema.models);
combined_schema.types.extend(schema.types);
combined_schema.inputs.extend(schema.inputs);
combined_schema.apis.extend(schema.apis);
combined_schema.events.extend(schema.events);
combined_schema.crons.extend(schema.crons);
combined_schema.websockets.extend(schema.websockets);
file_count += 1;
Ok(())
}
Err(e) => Err(anyhow::anyhow!("Failed to parse {}: {}", path.display(), e)),
}
})?;
if file_count == 0 {
anyhow::bail!("No .ro files found in {}", dir.display());
}
info!("Parsed {} schema files", file_count);
combined_schema
.validate()
.map_err(|e| anyhow::anyhow!("Schema validation failed: {}", e))?;
Ok(combined_schema)
}
pub fn visit_ro_files<F>(dir: &PathBuf, callback: &mut F) -> anyhow::Result<()>
where
F: FnMut(&PathBuf) -> anyhow::Result<()>,
{
if !dir.is_dir() {
return Ok(());
}
let entries = std::fs::read_dir(dir)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_ro_files(&path, callback)?;
} else if path.extension().and_then(|s| s.to_str()) == Some("ro") {
callback(&path)?;
}
}
Ok(())
}