Skip to content

Commit e14faf0

Browse files
committed
fix(core): add fail-fast validation to SiftBuilder.shake()
- Validate the generated regex string using Pattern.compile(). - Throw a descriptive IllegalStateException if the pattern is malformed. - Add testShakeFailFastValidation to verify exception handling.
1 parent 30b498d commit e14faf0

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

sift-core/src/main/java/com/mirkoddd/sift/core/SiftBuilder.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,13 @@ public SiftPattern andNothingElse() {
326326
public String shake() {
327327
if (cachedRegex == null) {
328328
cachedRegex = assembler.build();
329+
330+
try {
331+
java.util.regex.Pattern.compile(cachedRegex);
332+
} catch (java.util.regex.PatternSyntaxException e) {
333+
throw new IllegalStateException("Sift generated an invalid regex pattern: " + cachedRegex +
334+
". Please report this bug to the library maintainers.", e);
335+
}
329336
}
330337
return cachedRegex;
331338
}

sift-core/src/test/java/com/mirkoddd/sift/core/SiftTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,7 @@ void testBuilderIdentity() {
437437

438438
assertNotEquals(builderA, "^[a-zA-Z]??", "A builder should not be equal to an object of a different class");
439439
}
440+
440441
@Test
441442
@DisplayName("toString() should return the generated pattern string")
442443
void testBuilderToString() {
@@ -448,6 +449,23 @@ void testBuilderToString() {
448449
assertEquals(builder.shake(), builder.toString(),
449450
"toString() must rely on the cached shake() output");
450451
}
452+
453+
@Test
454+
@DisplayName("shake() should perform fail-fast validation and throw IllegalStateException on invalid regex")
455+
void testShakeFailFastValidation() {
456+
SiftPattern malformedPattern = () -> "(?unclosedGroup";
457+
458+
com.mirkoddd.sift.core.SiftBuilder builder =
459+
(com.mirkoddd.sift.core.SiftBuilder) Sift.fromStart().pattern(malformedPattern);
460+
461+
IllegalStateException exception = assertThrows(IllegalStateException.class, builder::shake,
462+
"shake() should throw an IllegalStateException if the generated regex is physically invalid");
463+
464+
assertTrue(exception.getMessage().contains("Sift generated an invalid regex pattern"),
465+
"The exception message should clearly indicate a Sift compilation error");
466+
assertInstanceOf(java.util.regex.PatternSyntaxException.class, exception.getCause(),
467+
"The root cause must be the original PatternSyntaxException from java.util.regex");
468+
}
451469
}
452470

453471
@Nested

0 commit comments

Comments
 (0)