Skip to content

Commit 300110c

Browse files
Recover from invalid JSX and preserve dependency error behavior
Reject unsupported JSX versions while reading configuration, and release the build lock through a Drop guard on every return or unwind. Retain dependency failures as typed error context so the CLI preserves exit code 2, package and root-path diagnostics, and the package-tree progress message. Review: Both recovery tests use temporary projects. The invalid-config test records every emitted output across invalid JSON and JSX configurations and recovery, with the same assertions for Rust and OCaml. Disabling Rust's source retry makes it detect stale output without depending on debug-log wording. Validation: Native compiler/CLI and Rust builds, 150 Rust unit tests, all 42 build fixtures, 297 configuration parity cases, 28 focused dependency-error checks, Clippy with warnings denied, formatting, changelog, and shell syntax checks pass. Both recovery scripts pass for both CLIs using isolated polling builds; native filesystem events are unavailable locally and remain for CI. Area: rewatch tests docs Output: unchanged; no generated JavaScript changes Tests: ~rewatch/src/build.rs ~rewatch/src/config.rs ~rewatch/tests/watch/09-watch-recovers-from-invalid-config.sh ~rewatch/tests/watch/10-watch-recovers-new-dependency-config.sh ~rewatch-ocaml/tests/check_command_validation.sh ~rewatch-ocaml/tests/config_acceptance_cases.tsv ~tests/build_tests/weird_deps/input.js ~tests/build_tests/weird_devdeps/input.js PR: #8641 Signed-off-by: Florian Hammerschmidt <florianh89@gmail.com>
1 parent 6d7bb7a commit 300110c

15 files changed

Lines changed: 253 additions & 247 deletions

File tree

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
- Keep watch mode running after full rebuild initialization fails, retry initialization on source edits, and watch newly added dependencies for configuration fixes. https://github.com/rescript-lang/rescript/pull/8641
2-
- Dependency resolution and configuration errors now return exit code `1` instead of `2` from `rescript build`, `clean`, and `format`. https://github.com/rescript-lang/rescript/pull/8641

‎rewatch-ocaml/README.md‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,6 @@ These are intentional:
105105
own process group.
106106
- `format -v` and `compiler-args -v` write their logs to stderr, so stdout
107107
remains formatted source or JSON. Rust writes them to stdout.
108-
- Dependency resolution failures and invalid dependency configurations from
109-
`build`, `clean`, and `format` return exit code `2` here and `1` in Rust.
110108
- While the root configuration is invalid, only configuration changes trigger
111109
recovery attempts here. Rust also retries initialization on watched source edits.
112110
- Watch mode also notices a missing dependency being installed into an

‎rewatch-ocaml/tests/check_command_validation.sh‎

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -518,19 +518,19 @@ require_same_output() {
518518

519519
require_both_errors_contain() {
520520
local name=$1
521-
local implementation fragment native_fragment native_short_fragment
522-
for implementation in rust ocaml; do
523-
if [ "$implementation" = rust ]; then fragment=$2; else fragment=${3:-$2}; fi
524-
native_fragment=${fragment/"$work"/"$native_work"}
525-
native_short_fragment=${fragment/"$work"/"$native_short_work"}
526-
if ! { grep -F "$fragment" "$work/$implementation.err" >/dev/null || \
527-
tr '\\' '/' <"$work/$implementation.err" | grep -F "$native_fragment" >/dev/null || \
528-
tr '\\' '/' <"$work/$implementation.err" | grep -F "$native_short_fragment" >/dev/null; }; then
529-
printf '%s: expected %s error to contain %s\n' "$name" "$implementation" "$fragment" >&2
530-
dump_both
531-
exit 1
532-
fi
533-
done
521+
local fragment=$2
522+
local native_fragment=${fragment/"$work"/"$native_work"}
523+
local native_short_fragment=${fragment/"$work"/"$native_short_work"}
524+
if ! { grep -F "$fragment" "$work/rust.err" >/dev/null || \
525+
tr '\\' '/' <"$work/rust.err" | grep -F "$native_fragment" >/dev/null || \
526+
tr '\\' '/' <"$work/rust.err" | grep -F "$native_short_fragment" >/dev/null; } || \
527+
! { grep -F "$fragment" "$work/ocaml.err" >/dev/null || \
528+
tr '\\' '/' <"$work/ocaml.err" | grep -F "$native_fragment" >/dev/null || \
529+
tr '\\' '/' <"$work/ocaml.err" | grep -F "$native_short_fragment" >/dev/null; }; then
530+
printf '%s: expected both errors to contain %s\n' "$name" "$fragment" >&2
531+
dump_both
532+
exit 1
533+
fi
534534
}
535535

536536
# Rust needs RESCRIPT_BSC_EXE to exist; OCaml builds and formats with the
@@ -1190,16 +1190,19 @@ if ! grep -F \
11901190
cat "$work/ocaml.out" "$work/ocaml.err" >&2
11911191
exit 1
11921192
fi
1193-
run_case build-missing-dependency reject exit2 build "$work/missing-dependency"
1193+
run_case build-missing-dependency exit2 exit2 build "$work/missing-dependency"
11941194
require_both_errors_contain build-missing-dependency \
1195-
"Could not build package tree reading dependency 'absent'"
1196-
run_case build-configless-dependency reject exit2 build "$work/configless-dependency"
1195+
"Could not build package tree reading dependency 'absent' at path '$work/missing-dependency'. Error:"
1196+
if ! grep -F 'Error building package tree.' "$work/rust.out" >/dev/null; then
1197+
echo "Missing dependency did not report package-tree progress" >&2
1198+
dump_both
1199+
exit 1
1200+
fi
1201+
run_case build-configless-dependency exit2 exit2 build "$work/configless-dependency"
11971202
require_both_errors_contain build-configless-dependency \
1198-
"Could not read dependency config at $work/configless-dependency/node_modules/no-config" \
11991203
"Could not build package tree for 'no-config' at path '$work/configless-dependency'. Error:"
1200-
run_case build-malformed-dependency reject exit2 build "$work/malformed-dependency"
1204+
run_case build-malformed-dependency exit2 exit2 build "$work/malformed-dependency"
12011205
require_both_errors_contain build-malformed-dependency \
1202-
"Could not read dependency config at $work/malformed-dependency/node_modules/bad-config" \
12031206
"Could not build package tree for 'bad-config' at path '$work/malformed-dependency'. Error:"
12041207
run_case build-duplicate-dependency accept accept build "$work/duplicate-dependency"
12051208
duplicate_warning='Duplicated package: shared ./node_modules/shared (chosen) vs ./node_modules/a/node_modules/shared in ./node_modules/a'
@@ -1522,9 +1525,9 @@ if ! cmp -s "$work/quiet-watch-rust.err.norm" \
15221525
fi
15231526
checked=$((checked + 1))
15241527

1525-
run_case clean-missing-dependency reject exit2 clean "$work/missing-dependency"
1526-
run_case clean-configless-dependency reject exit2 clean "$work/configless-dependency"
1527-
run_case clean-malformed-dependency reject exit2 clean "$work/malformed-dependency"
1528+
run_case clean-missing-dependency exit2 exit2 clean "$work/missing-dependency"
1529+
run_case clean-configless-dependency exit2 exit2 clean "$work/configless-dependency"
1530+
run_case clean-malformed-dependency exit2 exit2 clean "$work/malformed-dependency"
15281531
run_both clean "$work/clean-duplicate-{impl}"
15291532
if [ "$(classify "$rust_status")" != reject ] || [ "$ocaml_status" -ne 0 ] || \
15301533
[ ! -e "$work/clean-duplicate-rust/src/one/A.js" ] || \
@@ -1542,8 +1545,8 @@ set +e
15421545
"$rust" watch "$work/missing-dependency" >"$work/rust.out" 2>"$work/rust.err"
15431546
rust_status=$?
15441547
set -e
1545-
if [ "$rust_status" -ne 1 ]; then
1546-
echo "watch-missing-dependency: expected Rust exit 1, got $rust_status" >&2
1548+
if [ "$rust_status" -ne 2 ]; then
1549+
echo "watch-missing-dependency: expected Rust exit 2, got $rust_status" >&2
15471550
cat "$work/rust.out" "$work/rust.err" >&2
15481551
exit 1
15491552
fi
@@ -1574,11 +1577,11 @@ printf '{"name":"missing-dependency","sources":["src"],"dependencies":["absent"]
15741577
>"$work/missing-dependency/rescript.json"
15751578
checked=$((checked + 1))
15761579
run_case --cwd "$work/missing-dependency" \
1577-
format-missing-dependency reject exit2 format
1580+
format-missing-dependency exit2 exit2 format
15781581
run_case --cwd "$work/configless-dependency" \
1579-
format-configless-dependency reject exit2 format
1582+
format-configless-dependency exit2 exit2 format
15801583
run_case --cwd "$work/malformed-dependency" \
1581-
format-malformed-dependency reject exit2 format
1584+
format-malformed-dependency exit2 exit2 format
15821585
if [ -e "$work/missing-dependency/lib/build.lock" ] || \
15831586
[ -e "$work/missing-dependency/lib/watch.lock" ]; then
15841587
echo "OCaml dependency failures left a build or watch lock behind" >&2

‎rewatch-ocaml/tests/config_acceptance_cases.tsv‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ jsx preserve-false accept {"name":"config-shape","jsx":{"preserve":false}}
124124
jsx preserve-true accept {"name":"config-shape","jsx":{"preserve":true}}
125125
jsx unknown-field accept {"name":"config-shape","jsx":{"future":true}}
126126
jsx boolean-outer reject {"name":"config-shape","jsx":true}
127-
jsx version-three panic/reject {"name":"config-shape","jsx":{"version":3}}
127+
jsx version-three reject {"name":"config-shape","jsx":{"version":3}}
128128
jsx string-version reject {"name":"config-shape","jsx":{"version":"4"}}
129129
jsx boolean-module reject {"name":"config-shape","jsx":{"module":true}}
130130
jsx unknown-mode accept {"name":"config-shape","jsx":{"mode":"modern"}}

‎rewatch/src/build.rs‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ pub fn initialize_build(
189189
let compiler = get_compiler_info(&project_context)?;
190190

191191
let timing_clean_start = Instant::now();
192-
let packages = packages::make(filter, &project_context, prod, features.as_ref())?;
192+
let packages = packages::make(filter, &project_context, show_progress, prod, features.as_ref())?;
193193

194194
let source_map_args = project_context
195195
.get_root_config()
@@ -292,11 +292,17 @@ impl fmt::Display for IncrementalBuildError {
292292
}
293293

294294
pub fn with_build_lock<T>(path: &Path, f: impl FnOnce() -> T) -> T {
295+
struct BuildLock<'a>(&'a str);
296+
impl Drop for BuildLock<'_> {
297+
fn drop(&mut self) {
298+
let _ = drop_lock(LockKind::Build, self.0);
299+
}
300+
}
301+
295302
let build_folder = path.to_string_lossy().to_string();
296-
let _lock = get_lock_or_exit(LockKind::Build, &build_folder);
297-
let result = f();
298-
let _lock = drop_lock(LockKind::Build, &build_folder);
299-
result
303+
get_lock_or_exit(LockKind::Build, &build_folder);
304+
let _lock = BuildLock(&build_folder);
305+
f()
300306
}
301307

302308
#[instrument(name = "build.incremental", skip_all, fields(module_count = build_state.modules.len()))]
@@ -733,6 +739,18 @@ mod tests {
733739
);
734740
}
735741

742+
#[test]
743+
fn with_build_lock_drops_lock_after_panic() {
744+
let temp_dir = TempDir::new().unwrap();
745+
let project_folder = temp_dir.path();
746+
let result = std::panic::catch_unwind(|| {
747+
with_build_lock(project_folder, || panic!("failed"));
748+
});
749+
750+
assert!(result.is_err());
751+
assert!(!project_folder.join("lib/build.lock").exists());
752+
}
753+
736754
#[test]
737755
fn build_waits_for_lock_before_initializing() {
738756
let temp_dir = TempDir::new().expect("temp dir should be created");

‎rewatch/src/build/clean.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ pub fn clean(path: &Path, show_progress: bool, plain_output: bool, prod: bool) -
346346
// `clean` always acts on the full set of source directories regardless of which features are
347347
// active. We explicitly pass `None` so every tagged source folder is included and its
348348
// artifacts can be removed, even for features the user hasn't enabled for this build.
349-
let packages = packages::make(&None, &project_context, prod, None)?;
349+
let packages = packages::make(&None, &project_context, show_progress, prod, None)?;
350350

351351
let timing_clean_compiler_assets = Instant::now();
352352
if !plain_output && show_progress {

‎rewatch/src/build/packages.rs‎

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -282,30 +282,30 @@ pub fn read_dependency(
282282
Ok(canonical_path)
283283
}
284284

285-
/// Retain the resolved directory even when its config cannot be read, so watch mode can
286-
/// observe a correction to a dependency that was absent from the previous build state.
285+
/// Retain dependency context for CLI exit codes and recovery watches after config errors.
287286
#[derive(Debug)]
288-
pub struct DependencyConfigError {
289-
pub package_path: PathBuf,
290-
source: anyhow::Error,
287+
pub struct DependencyError {
288+
pub package_path: Option<PathBuf>,
289+
package_name: String,
290+
root_path: PathBuf,
291291
}
292292

293-
impl fmt::Display for DependencyConfigError {
293+
impl fmt::Display for DependencyError {
294294
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295295
write!(
296296
f,
297-
"Could not read dependency config at {}",
298-
self.package_path.display()
297+
"Could not build package tree {} '{}' at path '{}'. Error",
298+
if self.package_path.is_some() {
299+
"for"
300+
} else {
301+
"reading dependency"
302+
},
303+
self.package_name,
304+
self.root_path.display()
299305
)
300306
}
301307
}
302308

303-
impl error::Error for DependencyConfigError {
304-
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
305-
Some(self.source.as_ref())
306-
}
307-
}
308-
309309
/// Given a config, recursively finds all dependencies.
310310
/// 1. It starts with registering dependencies and
311311
/// prevents the operation for the ones which are already
@@ -369,14 +369,15 @@ fn read_dependencies(
369369
// Read all config files in parallel instead of blocking
370370
.par_iter()
371371
.map(|package_name| -> Result<Dependency> {
372+
let dependency_error = |package_path| DependencyError {
373+
package_path,
374+
package_name: package_name.clone(),
375+
root_path: project_context.get_root_path().to_path_buf(),
376+
};
372377
let canonical_path = read_dependency(package_name, package_config, project_context)
373-
.with_context(|| {
374-
format!("Could not build package tree reading dependency '{package_name}'")
375-
})?;
376-
let config = read_config(&canonical_path).map_err(|source| DependencyConfigError {
377-
package_path: canonical_path.clone(),
378-
source,
379-
})?;
378+
.with_context(|| dependency_error(None))?;
379+
let config = read_config(&canonical_path)
380+
.with_context(|| dependency_error(Some(canonical_path.clone())))?;
380381

381382
let is_local_dep = is_local_dependency(project_context, package_name, &canonical_path);
382383

@@ -834,10 +835,19 @@ fn compute_active_features(
834835
pub fn make(
835836
filter: &Option<regex::Regex>,
836837
project_context: &ProjectContext,
838+
show_progress: bool,
837839
prod: bool,
838840
cli_features: Option<&Vec<String>>,
839841
) -> Result<AHashMap<String, Package>> {
840-
let mut map = read_packages(project_context, prod)?;
842+
let mut map = read_packages(project_context, prod).inspect_err(|_| {
843+
if show_progress {
844+
println!(
845+
"{} {} Error building package tree.",
846+
console::style("[1/2]").bold().dim(),
847+
CROSS
848+
);
849+
}
850+
})?;
841851

842852
let active_features = compute_active_features(&map, cli_features, prod)?;
843853

‎rewatch/src/config.rs‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,14 @@ impl Config {
778778
config.handle_deprecations()?;
779779
config.unknown_fields = unknown_fields;
780780

781+
if let Some(version) = config.jsx.as_ref().and_then(|jsx| jsx.version)
782+
&& version != 4
783+
{
784+
return Err(anyhow!(
785+
"JSX version {version} is unsupported; jsx.version must be 4"
786+
));
787+
}
788+
781789
Ok(config)
782790
}
783791

@@ -828,10 +836,9 @@ impl Config {
828836
pub fn get_jsx_args(&self) -> Vec<String> {
829837
match self.jsx.to_owned() {
830838
Some(jsx) => match jsx.version {
831-
Some(version) if version == 4 => {
839+
Some(version) => {
832840
vec!["-bs-jsx".to_string(), version.to_string()]
833841
}
834-
Some(version) => panic!("JSX version {version} is unsupported"),
835842
None => vec![],
836843
},
837844
None => vec![],
@@ -1635,6 +1642,12 @@ pub mod tests {
16351642
assert!(config.get_gentype_args(&[], None, &[]).is_empty());
16361643
}
16371644

1645+
#[test]
1646+
fn test_unsupported_jsx_version_is_a_config_error() {
1647+
let error = Config::new_from_json_string(r#"{"name":"test","jsx":{"version":3}}"#).unwrap_err();
1648+
assert!(error.to_string().contains("JSX version 3 is unsupported"));
1649+
}
1650+
16381651
#[test]
16391652
fn test_other_jsx_module() {
16401653
let json = r#"

‎rewatch/src/format.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ fn get_files_in_scope() -> Result<Vec<String>> {
3939
let project_context = project_context::ProjectContext::new(&current_dir)?;
4040

4141
// Format walks all source files regardless of feature selection.
42-
let packages = packages::make(&None, &project_context, false, None)?;
42+
let packages = packages::make(&None, &project_context, false, false, None)?;
4343
let mut files: Vec<String> = Vec::new();
4444
let packages_to_format = project_context.get_scoped_local_packages();
4545

‎rewatch/src/main.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,11 @@ fn exit_code(result: Result<()>) -> i32 {
121121
Ok(()) => 0,
122122
Err(e) => {
123123
eprintln!("{:#}", e);
124-
1
124+
if e.is::<build::packages::DependencyError>() {
125+
2
126+
} else {
127+
1
128+
}
125129
}
126130
}
127131
}

0 commit comments

Comments
 (0)