forked from rescript-lang/rescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.rs
333 lines (292 loc) · 9.98 KB
/
helpers.rs
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use crate::build::packages;
use std::ffi::OsString;
use std::fs;
use std::fs::File;
use std::io::Read;
use std::io::{self, BufRead};
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
pub type StdErr = String;
pub mod emojis {
use console::Emoji;
pub static COMMAND: Emoji<'_, '_> = Emoji("🏃 ", "");
pub static TREE: Emoji<'_, '_> = Emoji("📦 ", "");
pub static SWEEP: Emoji<'_, '_> = Emoji("🧹 ", "");
pub static LOOKING_GLASS: Emoji<'_, '_> = Emoji("🕵️ ", "");
pub static CODE: Emoji<'_, '_> = Emoji("🧱 ", "");
pub static SWORDS: Emoji<'_, '_> = Emoji("🤺 ️", "");
pub static DEPS: Emoji<'_, '_> = Emoji("️🌴 ", "");
pub static CHECKMARK: Emoji<'_, '_> = Emoji("️✅ ", "");
pub static CROSS: Emoji<'_, '_> = Emoji("️🛑 ", "");
pub static SPARKLES: Emoji<'_, '_> = Emoji("✨ ", "");
pub static COMPILE_STATE: Emoji<'_, '_> = Emoji("📝 ", "");
pub static LINE_CLEAR: &str = "\x1b[2K\r";
}
pub trait LexicalAbsolute {
fn to_lexical_absolute(&self) -> std::io::Result<PathBuf>;
}
impl LexicalAbsolute for Path {
fn to_lexical_absolute(&self) -> std::io::Result<PathBuf> {
let mut absolute = if self.is_absolute() {
PathBuf::new()
} else {
std::env::current_dir()?
};
for component in self.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
absolute.pop();
}
component => absolute.push(component.as_os_str()),
}
}
Ok(absolute)
}
}
pub fn package_path(root: &str, package_name: &str) -> String {
format!("{}/node_modules/{}", root, package_name)
}
pub fn get_abs_path(path: &str) -> String {
let abs_path_buf = PathBuf::from(path);
return abs_path_buf
.to_lexical_absolute()
.expect("Could not canonicalize")
.to_str()
.expect("Could not canonicalize")
.to_string();
}
pub fn get_basename(path: &str) -> String {
let path_buf = PathBuf::from(path);
return path_buf
.file_stem()
.expect("Could not get basename")
.to_str()
.expect("Could not get basename 2")
.to_string();
}
pub fn change_extension(path: &str, new_extension: &str) -> String {
let path_buf = PathBuf::from(path);
return path_buf
.with_extension(new_extension)
.to_str()
.expect("Could not change extension")
.to_string();
}
/// Capitalizes the first character in s.
fn capitalize(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
fn add_suffix(base: &str, namespace: &packages::Namespace) -> String {
match namespace {
packages::Namespace::NamespaceWithEntry { namespace: _, entry } if entry == base => base.to_string(),
packages::Namespace::Namespace(_)
| packages::Namespace::NamespaceWithEntry {
namespace: _,
entry: _,
} => base.to_string() + "-" + &namespace.to_suffix().unwrap(),
packages::Namespace::NoNamespace => base.to_string(),
}
}
pub fn module_name_with_namespace(module_name: &str, namespace: &packages::Namespace) -> String {
capitalize(&add_suffix(module_name, namespace))
}
// this doesn't capitalize the module name! if the rescript name of the file is "foo.res" the
// compiler assets are foo-Namespace.cmt and foo-Namespace.cmj, but the module name is Foo
pub fn file_path_to_compiler_asset_basename(path: &str, namespace: &packages::Namespace) -> String {
let base = get_basename(path);
add_suffix(&base, namespace)
}
pub fn file_path_to_module_name(path: &str, namespace: &packages::Namespace) -> String {
capitalize(&file_path_to_compiler_asset_basename(path, namespace))
}
pub fn contains_ascii_characters(str: &str) -> bool {
for chr in str.chars() {
if chr.is_ascii_alphanumeric() {
return true;
}
}
false
}
pub fn create_build_path(build_path: &str) {
fs::DirBuilder::new()
.recursive(true)
.create(PathBuf::from(build_path.to_string()))
.unwrap();
}
pub fn get_bsc(root_path: &str, workspace_root: Option<String>) -> String {
let subfolder = match (std::env::consts::OS, std::env::consts::ARCH) {
("macos", "aarch64") => "darwinarm64",
("macos", _) => "darwin",
("linux", _) => "linux",
("windows", _) => "win32",
_ => panic!("Unsupported architecture"),
};
match (
PathBuf::from(format!(
"{}/node_modules/rescript/{}/bsc.exe",
root_path, subfolder
))
.canonicalize(),
workspace_root.map(|workspace_root| {
PathBuf::from(format!(
"{}/node_modules/rescript/{}/bsc.exe",
workspace_root, subfolder
))
.canonicalize()
}),
) {
(Ok(path), _) => path,
(_, Some(Ok(path))) => path,
_ => panic!("Could not find bsc.exe"),
}
.to_string_lossy()
.to_string()
}
pub fn string_ends_with_any(s: &Path, suffixes: &[&str]) -> bool {
suffixes
.iter()
.any(|&suffix| s.extension().unwrap_or(&OsString::new()).to_str().unwrap_or("") == suffix)
}
pub fn get_compiler_asset(
package: &packages::Package,
namespace: &packages::Namespace,
source_file: &str,
extension: &str,
) -> String {
let namespace = match extension {
"ast" | "iast" => &packages::Namespace::NoNamespace,
_ => namespace,
};
package.get_build_path()
+ "/"
+ &file_path_to_compiler_asset_basename(source_file, namespace)
+ "."
+ extension
}
pub fn canonicalize_string_path(path: &str) -> Option<String> {
return Path::new(path)
.canonicalize()
.ok()
.map(|path| path.to_str().expect("Could not canonicalize").to_string());
}
pub fn get_bs_compiler_asset(
package: &packages::Package,
namespace: &packages::Namespace,
source_file: &str,
extension: &str,
) -> String {
let namespace = match extension {
"ast" | "iast" => &packages::Namespace::NoNamespace,
_ => namespace,
};
let dir = std::path::Path::new(&source_file).parent().unwrap();
std::path::Path::new(&package.get_bs_build_path())
.join(dir)
.join(file_path_to_compiler_asset_basename(source_file, namespace) + extension)
.to_str()
.unwrap()
.to_owned()
}
pub fn get_namespace_from_module_name(module_name: &str) -> Option<String> {
let mut split = module_name.split('-');
let _ = split.next();
split.next().map(|s| s.to_string())
}
pub fn is_interface_ast_file(file: &str) -> bool {
file.ends_with(".iast")
}
pub fn read_lines(filename: String) -> io::Result<io::Lines<io::BufReader<fs::File>>> {
let file = fs::File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
pub fn get_system_time() -> u128 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards");
since_the_epoch.as_millis()
}
pub fn is_interface_file(extension: &str) -> bool {
matches!(extension, "resi" | "mli" | "rei")
}
pub fn is_implementation_file(extension: &str) -> bool {
matches!(extension, "res" | "ml" | "re")
}
pub fn is_source_file(extension: &str) -> bool {
is_interface_file(extension) || is_implementation_file(extension)
}
pub fn is_non_exotic_module_name(module_name: &str) -> bool {
let mut chars = module_name.chars();
if chars.next().unwrap().is_ascii_uppercase() && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
return true;
}
false
}
pub fn get_extension(path: &str) -> String {
let path_buf = PathBuf::from(path);
return path_buf
.extension()
.expect("Could not get extension")
.to_str()
.expect("Could not get extension 2")
.to_string();
}
pub fn format_namespaced_module_name(module_name: &str) -> String {
// from ModuleName-Namespace to Namespace.ModuleName
// also format ModuleName-@Namespace to Namespace.ModuleName
let mut split = module_name.split('-');
let module_name = split.next().unwrap();
let namespace = split.next();
let namespace = namespace.map(|ns| ns.trim_start_matches('@'));
match namespace {
None => module_name.to_string(),
Some(ns) => ns.to_string() + "." + module_name,
}
}
pub fn compute_file_hash(path: &str) -> Option<blake3::Hash> {
match fs::read(path) {
Ok(str) => Some(blake3::hash(&str)),
Err(_) => None,
}
}
fn has_rescript_config(path: &Path) -> bool {
path.join("bsconfig.json").exists() || path.join("rescript.json").exists()
}
pub fn get_workspace_root(package_root: &str) -> Option<String> {
std::path::PathBuf::from(&package_root)
.parent()
.and_then(get_nearest_bsconfig)
}
// traverse up the directory tree until we find a bsconfig.json, if not return None
pub fn get_nearest_bsconfig(path_buf: &Path) -> Option<String> {
let mut current_dir = path_buf.to_owned();
loop {
if has_rescript_config(¤t_dir) {
return Some(current_dir.to_string_lossy().to_string());
}
match current_dir.parent() {
None => return None,
Some(parent) => current_dir = parent.to_path_buf(),
}
}
}
pub fn get_rescript_version(bsc_path: &str) -> String {
let version_cmd = Command::new(bsc_path)
.args(["-v"])
.output()
.expect("failed to find version");
std::str::from_utf8(&version_cmd.stdout)
.expect("Could not read version from rescript")
.replace('\n', "")
.replace("ReScript ", "")
}
pub fn read_file(path: &Path) -> Result<String, std::io::Error> {
let mut file = File::open(path).expect("file not found");
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}