-
Notifications
You must be signed in to change notification settings - Fork 482
Expand file tree
/
Copy pathbuild.rs
More file actions
618 lines (557 loc) · 19.5 KB
/
build.rs
File metadata and controls
618 lines (557 loc) · 19.5 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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
pub mod build_types;
pub mod clean;
pub mod compile;
pub mod compiler_info;
pub mod deps;
pub mod logs;
pub mod namespaces;
pub mod packages;
pub mod parse;
pub mod read_compile_state;
use self::parse::parser_args;
use crate::build::compile::{mark_modules_with_deleted_deps_dirty, mark_modules_with_expired_deps_dirty};
use crate::build::compiler_info::{CompilerCheckResult, verify_compiler_info, write_compiler_info};
use crate::helpers::emojis::*;
use crate::helpers::{self};
use crate::lock::{LockKind, drop_lock, get_lock_or_exit};
use crate::project_context::ProjectContext;
use crate::sourcedirs;
use anyhow::{Context, Result, anyhow};
use build_types::*;
use console::style;
use indicatif::{ProgressBar, ProgressStyle};
use log::log_enabled;
use serde::Serialize;
use std::fmt;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
fn is_dirty(module: &Module) -> bool {
match module.source_type {
SourceType::SourceFile(SourceFile {
implementation: Implementation {
parse_dirty: true, ..
},
..
}) => true,
SourceType::SourceFile(SourceFile {
interface: Some(Interface {
parse_dirty: true, ..
}),
..
}) => true,
SourceType::SourceFile(_) => false,
SourceType::MlMap(MlMap {
parse_dirty: dirty, ..
}) => dirty,
}
}
#[derive(Serialize, Debug, Clone)]
pub struct CompilerArgs {
pub compiler_args: Vec<String>,
pub parser_args: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompilationOutcome {
Clean,
Warnings,
}
fn has_output(output: &str) -> bool {
helpers::contains_ascii_characters(output)
}
fn has_config_warnings(build_state: &BuildCommandState) -> bool {
build_state.packages.iter().any(|(_, package)| {
package.is_local_dep
&& (!package.config.get_unsupported_fields().is_empty()
|| !package.config.get_unknown_fields().is_empty())
})
}
pub fn format_finished_compilation_message(
compilation_kind: Option<&str>,
outcome: CompilationOutcome,
duration: Duration,
) -> String {
let compilation_kind = compilation_kind
.map(|kind| format!("{kind} "))
.unwrap_or_default();
let (status, warning_suffix) = match outcome {
CompilationOutcome::Clean => (CHECKMARK, ""),
CompilationOutcome::Warnings => (WARNING, " with warnings"),
};
format!(
"{LINE_CLEAR}{status}Finished {compilation_kind}compilation{warning_suffix} in {:.2}s",
duration.as_secs_f64()
)
}
pub fn get_compiler_args(rescript_file_path: &Path) -> Result<String> {
let filename = &helpers::get_abs_path(rescript_file_path);
let current_package = helpers::get_abs_path(
&helpers::get_nearest_config(rescript_file_path).expect("Couldn't find package root"),
);
let project_context = ProjectContext::new(¤t_package)?;
let is_type_dev = match filename.strip_prefix(¤t_package) {
Err(_) => false,
Ok(relative_path) => project_context
.current_config
.find_is_type_dev_for_path(relative_path),
};
// make PathBuf from package root and get the relative path for filename
let relative_filename = filename.strip_prefix(PathBuf::from(¤t_package)).unwrap();
let file_path = PathBuf::from(¤t_package).join(filename);
let contents = helpers::read_file(&file_path).expect("Error reading file");
let (ast_path, parser_args) = parser_args(
&project_context,
&project_context.current_config,
relative_filename,
&contents,
/* is_local_dep */ true,
/* warn_error_override */ None,
)?;
let is_interface = filename.to_string_lossy().ends_with('i');
let has_interface = if is_interface {
true
} else {
let mut interface_filename = filename.to_string_lossy().to_string();
interface_filename.push('i');
PathBuf::from(&interface_filename).exists()
};
let compiler_args = compile::compiler_args(
&project_context.current_config,
&ast_path,
relative_filename,
is_interface,
has_interface,
&project_context,
&None,
is_type_dev,
true,
None, // No warn_error_override for compiler-args command
&[], // Source dirs not available outside full build; gentype falls back to defaults.
)?;
let result = serde_json::to_string_pretty(&CompilerArgs {
compiler_args,
parser_args,
})?;
Ok(result)
}
pub fn get_compiler_info(project_context: &ProjectContext) -> Result<CompilerInfo> {
let bsc_path = helpers::get_bsc();
let bsc_hash = helpers::compute_file_hash(&bsc_path).ok_or(anyhow!(
"Failed to compute bsc hash for {}",
bsc_path.to_string_lossy()
))?;
let runtime_path = compile::get_runtime_path(&project_context.current_config, project_context)?;
Ok(CompilerInfo {
bsc_path,
bsc_hash,
runtime_path,
})
}
pub fn initialize_build(
default_timing: Option<Duration>,
filter: &Option<regex::Regex>,
show_progress: bool,
path: &Path,
plain_output: bool,
warn_error: Option<String>,
prod: bool,
) -> Result<BuildCommandState> {
let project_context = ProjectContext::new(path)?;
let compiler = get_compiler_info(&project_context)?;
let timing_clean_start = Instant::now();
let packages = packages::make(filter, &project_context, show_progress, prod)?;
let compiler_check = verify_compiler_info(&packages, &compiler);
if !packages::validate_packages_dependencies(&packages) {
return Err(anyhow!("Failed to validate package dependencies"));
}
let mut build_state = BuildCommandState::new(
path.to_path_buf(),
project_context,
packages,
compiler,
warn_error,
);
packages::parse_packages(&mut build_state)?;
let compile_assets_state = read_compile_state::read(&mut build_state)?;
let (diff_cleanup, total_cleanup) = clean::cleanup_previous_build(&mut build_state, compile_assets_state);
let timing_clean_total = timing_clean_start.elapsed();
if show_progress {
if plain_output {
if let CompilerCheckResult::CleanedPackagesDueToCompiler = compiler_check {
// Snapshot-friendly output (no progress prefixes or emojis)
println!("Cleaned previous build due to compiler update");
}
println!("Cleaned {diff_cleanup}/{total_cleanup}")
} else {
if let CompilerCheckResult::CleanedPackagesDueToCompiler = compiler_check {
println!(
"{}{} {}Cleaned previous build due to compiler update",
LINE_CLEAR,
style("[1/3]").bold().dim(),
SWEEP
);
}
println!(
"{}{} {}Cleaned {}/{} in {:.2}s",
LINE_CLEAR,
style("[1/3]").bold().dim(),
SWEEP,
diff_cleanup,
total_cleanup,
default_timing.unwrap_or(timing_clean_total).as_secs_f64()
);
}
}
Ok(build_state)
}
fn format_step(current: usize, total: usize) -> console::StyledObject<String> {
style(format!("[{current}/{total}]")).bold().dim()
}
#[derive(Debug, Clone)]
pub enum IncrementalBuildErrorKind {
SourceFileParseError,
CompileError(Option<String>),
}
#[derive(Debug, Clone)]
pub struct IncrementalBuildError {
pub plain_output: bool,
pub kind: IncrementalBuildErrorKind,
}
impl fmt::Display for IncrementalBuildError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.kind {
IncrementalBuildErrorKind::SourceFileParseError => {
if self.plain_output {
write!(f, "{LINE_CLEAR} Could not parse Source Files",)
} else {
write!(f, "{LINE_CLEAR} {CROSS}Could not parse Source Files",)
}
}
IncrementalBuildErrorKind::CompileError(Some(e)) => {
if self.plain_output {
write!(f, "{LINE_CLEAR} Failed to Compile. Error: {e}",)
} else {
write!(f, "{LINE_CLEAR} {CROSS}Failed to Compile. Error: {e}",)
}
}
IncrementalBuildErrorKind::CompileError(None) => {
if self.plain_output {
write!(f, "{LINE_CLEAR} Failed to Compile. See Errors Above",)
} else {
write!(f, "{LINE_CLEAR} {CROSS}Failed to Compile. See Errors Above",)
}
}
}
}
}
pub fn incremental_build(
build_state: &mut BuildCommandState,
default_timing: Option<Duration>,
initial_build: bool,
show_progress: bool,
only_incremental: bool,
create_sourcedirs: bool,
plain_output: bool,
) -> Result<CompilationOutcome, IncrementalBuildError> {
let build_folder = build_state.root_folder.to_string_lossy().to_string();
let _lock = get_lock_or_exit(LockKind::Build, &build_folder);
logs::initialize(&build_state.packages);
let num_dirty_modules = build_state.modules.values().filter(|m| is_dirty(m)).count() as u64;
let pb = if !plain_output && show_progress {
ProgressBar::new(num_dirty_modules)
} else {
ProgressBar::hidden()
};
let mut current_step = if only_incremental { 1 } else { 2 };
let total_steps = if only_incremental { 2 } else { 3 };
pb.set_style(
ProgressStyle::with_template(&format!(
"{} {}Parsing... {{spinner}} {{pos}}/{{len}} {{msg}}",
format_step(current_step, total_steps),
PARSE
))
.unwrap(),
);
let timing_parse_start = Instant::now();
let timing_ast = Instant::now();
let result_asts = parse::generate_asts(build_state, || pb.inc(1));
let timing_ast_elapsed = timing_ast.elapsed();
let parse_warnings = match result_asts {
Ok(warnings) => {
pb.finish();
warnings
}
Err(err) => {
logs::finalize(&build_state.packages);
if !plain_output && show_progress {
eprintln!(
"{}{} {}Error parsing source files in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
CROSS,
default_timing.unwrap_or(timing_ast_elapsed).as_secs_f64()
);
pb.finish();
}
eprintln!("{}", &err);
let _lock = drop_lock(LockKind::Build, &build_folder);
return Err(IncrementalBuildError {
kind: IncrementalBuildErrorKind::SourceFileParseError,
plain_output,
});
}
};
let deleted_modules = build_state.deleted_modules.clone();
deps::get_deps(build_state, &deleted_modules);
let timing_parse_total = timing_parse_start.elapsed();
if show_progress {
if plain_output {
println!("Parsed {num_dirty_modules} source files")
} else {
println!(
"{}{} {}Parsed {} source files in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
PARSE,
num_dirty_modules,
default_timing.unwrap_or(timing_parse_total).as_secs_f64()
);
}
}
let has_parse_warnings = has_output(&parse_warnings);
if has_parse_warnings {
eprintln!("{}", &parse_warnings);
}
mark_modules_with_expired_deps_dirty(build_state);
mark_modules_with_deleted_deps_dirty(&mut build_state.build_state);
current_step += 1;
//print all the compile_dirty modules
if log_enabled!(log::Level::Trace) {
for (module_name, module) in build_state.modules.iter() {
if module.compile_dirty {
println!("compile dirty: {module_name}");
}
}
};
let start_compiling = Instant::now();
let pb = if !plain_output && show_progress {
ProgressBar::new(build_state.modules.len().try_into().unwrap())
} else {
ProgressBar::hidden()
};
pb.set_style(
ProgressStyle::with_template(&format!(
"{} {}Compiling... {{spinner}} {{pos}}/{{len}} {{msg}}",
format_step(current_step, total_steps),
SWORDS
))
.unwrap(),
);
let (compile_errors, compile_warnings, num_compiled_modules) = compile::compile(
build_state,
show_progress,
|| pb.inc(1),
|size| pb.set_length(size),
)
.map_err(|e| {
let _lock = drop_lock(LockKind::Build, &build_folder);
IncrementalBuildError {
kind: IncrementalBuildErrorKind::CompileError(Some(e.to_string())),
plain_output,
}
})?;
let compile_duration = start_compiling.elapsed();
logs::finalize(&build_state.packages);
if create_sourcedirs {
sourcedirs::print(build_state);
}
pb.finish();
if !compile_errors.is_empty() {
if show_progress {
if plain_output {
eprintln!("Compiled {num_compiled_modules} modules")
} else {
eprintln!(
"{}{} {}Compiled {} modules in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
CROSS,
num_compiled_modules,
default_timing.unwrap_or(compile_duration).as_secs_f64()
);
}
}
if has_output(&compile_warnings) {
eprintln!("{}", &compile_warnings);
}
if initial_build {
log_config_warnings(build_state);
}
if has_output(&compile_errors) {
eprintln!("{}", &compile_errors);
}
let _lock = drop_lock(LockKind::Build, &build_folder);
Err(IncrementalBuildError {
kind: IncrementalBuildErrorKind::CompileError(None),
plain_output,
})
} else {
let has_compile_warnings = has_output(&compile_warnings);
let has_config_warning_output = initial_build && has_config_warnings(build_state);
let outcome = if has_parse_warnings || has_compile_warnings || has_config_warning_output {
CompilationOutcome::Warnings
} else {
CompilationOutcome::Clean
};
if show_progress {
if plain_output {
println!("Compiled {num_compiled_modules} modules")
} else {
println!(
"{}{} {}Compiled {} modules in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
SWORDS,
num_compiled_modules,
default_timing.unwrap_or(compile_duration).as_secs_f64()
);
}
}
if has_compile_warnings {
eprintln!("{}", &compile_warnings);
}
if initial_build {
log_config_warnings(build_state);
}
// Write per-package compiler metadata to `lib/bs/compiler-info.json` (idempotent)
write_compiler_info(build_state);
let _lock = drop_lock(LockKind::Build, &build_folder);
Ok(outcome)
}
}
fn log_config_warnings(build_state: &BuildCommandState) {
build_state.packages.iter().for_each(|(_, package)| {
// Only warn for local dependencies, not external packages
if package.is_local_dep {
package
.config
.get_unsupported_fields()
.iter()
.for_each(|field| log_unsupported_config_field(&package.name, field));
package
.config
.get_unknown_fields()
.iter()
.for_each(|field| log_unknown_config_field(&package.name, field));
}
});
}
fn log_unsupported_config_field(package_name: &str, field_name: &str) {
let warning = format!(
"The field '{field_name}' found in the package config of '{package_name}' is not supported by ReScript 12's new build system."
);
eprintln!("\n{}", style(warning).yellow());
}
fn log_unknown_config_field(package_name: &str, field_name: &str) {
let warning = format!(
"Unknown field '{field_name}' found in the package config of '{package_name}'. This option will be ignored."
);
eprintln!("\n{}", style(warning).yellow());
}
// write build.ninja files in the packages after a non-incremental build
// this is necessary to bust the editor tooling cache. The editor tooling
// is watching this file.
// we don't need to do this in an incremental build because there are no file
// changes (deletes / additions)
pub fn write_build_ninja(build_state: &BuildCommandState) {
for package in build_state.packages.values() {
// write empty file:
let mut f = File::create(package.get_build_path().join("build.ninja")).expect("Unable to write file");
f.write_all(b"").expect("unable to write to ninja file");
}
}
#[allow(clippy::too_many_arguments)]
pub fn build(
filter: &Option<regex::Regex>,
path: &Path,
show_progress: bool,
no_timing: bool,
create_sourcedirs: bool,
plain_output: bool,
warn_error: Option<String>,
prod: bool,
) -> Result<BuildCommandState> {
let default_timing: Option<std::time::Duration> = if no_timing {
Some(std::time::Duration::new(0.0 as u64, 0.0 as u32))
} else {
None
};
let timing_total = Instant::now();
let mut build_state = initialize_build(
default_timing,
filter,
show_progress,
path,
plain_output,
warn_error,
prod,
)
.with_context(|| "Could not initialize build")?;
match incremental_build(
&mut build_state,
default_timing,
true,
show_progress,
false,
create_sourcedirs,
plain_output,
) {
Ok(result) => {
if !plain_output && show_progress {
let timing_total_elapsed = timing_total.elapsed();
println!(
"\n{}",
format_finished_compilation_message(
None,
result,
default_timing.unwrap_or(timing_total_elapsed),
)
);
}
clean::cleanup_after_build(&build_state);
write_build_ninja(&build_state);
Ok(build_state)
}
Err(e) => {
clean::cleanup_after_build(&build_state);
write_build_ninja(&build_state);
Err(anyhow!("Incremental build failed. Error: {e}"))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_successful_completion_message() {
assert_eq!(
format_finished_compilation_message(None, CompilationOutcome::Clean, Duration::from_millis(1500),),
format!("{LINE_CLEAR}{}Finished compilation in 1.50s", CHECKMARK)
);
}
#[test]
fn formats_warning_completion_message() {
assert_eq!(
format_finished_compilation_message(
Some("incremental"),
CompilationOutcome::Warnings,
Duration::from_millis(1500),
),
format!(
"{LINE_CLEAR}{}Finished incremental compilation with warnings in 1.50s",
WARNING
)
);
}
}