forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_target.rs
More file actions
235 lines (213 loc) · 7.54 KB
/
Copy pathcli_target.rs
File metadata and controls
235 lines (213 loc) · 7.54 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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use std::fs;
use camino::Utf8PathBuf;
use common::{InputDb, config::Config};
use resolver::{ResolutionHandler, Resolver};
use resolver::{
files::ancestor_fe_toml_dirs,
ingot::{FeTomlProbe, infer_config_kind},
};
use smol_str::SmolStr;
use url::Url;
use crate::DriverDataBase;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CliTarget {
StandaloneFile(Utf8PathBuf),
Directory(Utf8PathBuf),
}
struct ResolvedMember {
path: Utf8PathBuf,
url: Url,
}
struct ConfigProbe;
impl ResolutionHandler<resolver::files::FilesResolver> for ConfigProbe {
type Item = FeTomlProbe;
fn handle_resolution(
&mut self,
_description: &Url,
resource: resolver::files::FilesResource,
) -> Self::Item {
for file in &resource.files {
if file.path.as_str().ends_with("fe.toml") {
return FeTomlProbe::Present {
kind_hint: infer_config_kind(&file.content),
};
}
}
FeTomlProbe::Missing
}
}
pub fn resolve_cli_target(
db: &mut DriverDataBase,
path: &Utf8PathBuf,
force_standalone: bool,
) -> Result<CliTarget, String> {
let arg = path.as_str();
let is_name = is_name_candidate(arg);
let path_exists = path.exists();
if path.is_file() {
if path.file_name() == Some("fe.toml") {
return Err(format!(
"fe.toml file paths are not accepted: {path}. Pass the containing directory instead"
));
}
if path.extension() == Some("fe") {
// If the file lives under an ingot, operate from that directory so imports resolve
// in context. For workspace roots, prefer treating the file as standalone unless
// the user explicitly targets the workspace.
if !force_standalone
&& let Ok(canonical) = path.canonicalize_utf8()
&& let Some(root) = ancestor_fe_toml_dirs(canonical.as_std_path())
.first()
.and_then(|root| Utf8PathBuf::from_path_buf(root.to_path_buf()).ok())
{
let config_path = root.join("fe.toml");
if let Ok(content) = fs::read_to_string(&config_path)
&& matches!(Config::parse(&content), Ok(Config::Ingot(_)))
{
return Ok(CliTarget::Directory(root));
}
}
return Ok(CliTarget::StandaloneFile(path.clone()));
}
return Err("Path must be either a .fe file or a directory containing fe.toml".into());
}
let name_match = if is_name {
resolve_member_by_name(db, arg)?
} else {
None
};
let path_member = if is_name && path_exists {
resolve_member_by_path(db, path)?
} else {
None
};
if path_exists && name_match.is_some() {
match (&name_match, &path_member) {
(Some(name_member), Some(path_member)) => {
if name_member.url == path_member.url {
return Ok(CliTarget::Directory(path_member.path.clone()));
}
return Err(format!(
"Argument \"{arg}\" matches a workspace member name but does not match the provided path"
));
}
(Some(_), None) => {
return Err(format!(
"Argument \"{arg}\" matches a workspace member name but does not match the provided path"
));
}
_ => {}
}
}
if let Some(name_member) = name_match {
return Ok(CliTarget::Directory(name_member.path));
}
if path_exists {
if path.is_dir() && path.join("fe.toml").is_file() {
return Ok(CliTarget::Directory(path.clone()));
}
return Err("Path must be either a .fe file or a directory containing fe.toml".into());
}
Err("Path must be either a .fe file or a directory containing fe.toml".into())
}
fn is_name_candidate(value: &str) -> bool {
!value.is_empty() && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn resolve_member_by_name(
db: &mut DriverDataBase,
name: &str,
) -> Result<Option<ResolvedMember>, String> {
let cwd = std::env::current_dir()
.map_err(|err| format!("Failed to read current directory: {err}"))?;
let cwd = Utf8PathBuf::from_path_buf(cwd)
.map_err(|_| "Current directory is not valid UTF-8".to_string())?;
let workspace_root = find_workspace_root(db, &cwd)?;
let Some(workspace_root) = workspace_root else {
return Ok(None);
};
let workspace_url = dir_url(&workspace_root)?;
let mut matches =
db.dependency_graph()
.workspace_members_by_name(db, &workspace_url, &SmolStr::new(name));
if matches.is_empty() {
return Ok(None);
}
if matches.len() > 1 {
return Err(format!(
"Multiple workspace members named \"{name}\"; specify a path instead"
));
}
let member = matches.pop().map(|member| ResolvedMember {
path: workspace_root.join(member.path.as_str()),
url: member.url,
});
Ok(member)
}
fn resolve_member_by_path(
db: &mut DriverDataBase,
path: &Utf8PathBuf,
) -> Result<Option<ResolvedMember>, String> {
if !path.is_dir() {
return Ok(None);
}
let workspace_root = find_workspace_root(db, path)?;
let Some(workspace_root) = workspace_root else {
return Ok(None);
};
let workspace_url = dir_url(&workspace_root)?;
let members = db
.dependency_graph()
.workspace_member_records(db, &workspace_url);
let canonical = path
.canonicalize_utf8()
.map_err(|_| format!("Invalid or non-existent directory path: {path}"))?;
let target_url = Url::from_directory_path(canonical.as_str())
.map_err(|_| format!("Invalid directory path: {path}"))?;
Ok(members
.into_iter()
.find(|member| member.url == target_url)
.map(|member| ResolvedMember {
path: workspace_root.join(member.path.as_str()),
url: member.url,
}))
}
fn find_workspace_root(
db: &mut DriverDataBase,
start: &Utf8PathBuf,
) -> Result<Option<Utf8PathBuf>, String> {
let dirs = ancestor_fe_toml_dirs(start.as_std_path());
for dir in dirs {
let dir = Utf8PathBuf::from_path_buf(dir)
.map_err(|_| "Encountered non UTF-8 workspace path".to_string())?;
let url = dir_url(&dir)?;
let mut resolver = resolver::ingot::minimal_files_resolver();
let summary = resolver
.resolve(&mut ConfigProbe, &url)
.map_err(|err| err.to_string())?;
if summary.kind_hint() == Some(resolver::ingot::ConfigKind::Workspace) {
if db
.dependency_graph()
.workspace_member_records(db, &url)
.is_empty()
{
let _ = crate::init_ingot(db, &url);
}
return Ok(Some(dir));
}
}
Ok(None)
}
fn dir_url(path: &Utf8PathBuf) -> Result<Url, String> {
let canonical_path = match path.canonicalize_utf8() {
Ok(path) => path,
Err(_) => {
let cwd = std::env::current_dir()
.map_err(|err| format!("Failed to read current directory: {err}"))?;
let cwd = Utf8PathBuf::from_path_buf(cwd)
.map_err(|_| "Current directory is not valid UTF-8".to_string())?;
cwd.join(path)
}
};
Url::from_directory_path(canonical_path.as_str())
.map_err(|_| format!("Invalid or non-existent directory path: {path}"))
}