Skip to content

Commit

Permalink
chore: add regex capture to label application rule (#214)
Browse files Browse the repository at this point in the history
  • Loading branch information
saxenakshitiz authored Jun 6, 2024
1 parent c0dd217 commit 31fc31e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ message LabelApplicationRuleData {
string key = 1;
optional string json_path = 2;
optional string alias = 3;
optional string regex_capture = 4;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,10 @@ public void validateLabelExpression(Action.DynamicLabel dynamicLabel) {
.getTokenExtractionRulesList()
.forEach(
tokenExtractionRule -> {
validKeys.add(tokenExtractionRule.getKey());
if (tokenExtractionRule.hasAlias()) {
validKeys.add(tokenExtractionRule.getAlias());
} else {
validKeys.add(tokenExtractionRule.getKey());
}
});
Pattern pattern = Pattern.compile("\\{(\\\\}|[^}])*}");
Expand All @@ -264,6 +265,9 @@ public void validateLabelExpression(Action.DynamicLabel dynamicLabel) {
private void validateTokenExtractionRule(
Action.DynamicLabel.TokenExtractionRule tokenExtractionRule) {
validateNonDefaultPresenceOrThrow(tokenExtractionRule, tokenExtractionRule.KEY_FIELD_NUMBER);
if (tokenExtractionRule.hasRegexCapture()) {
RegexValidator.validateCaptureGroupCount(tokenExtractionRule.getRegexCapture(), 1);
}
}

private void throwInvalidArgumentException(String description) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,20 @@ public static Status validate(String regexPattern) {
}
return Status.OK;
}

public static Status validateCaptureGroupCount(String regexPattern, int expectedCount) {
// compiling an invalid regex throws PatternSyntaxException
try {
Pattern pattern = Pattern.compile(regexPattern);
if (pattern.groupCount() != expectedCount) {
return Status.INVALID_ARGUMENT.withDescription(
"Regex group count should be: " + expectedCount);
}
} catch (PatternSyntaxException e) {
return Status.INVALID_ARGUMENT
.withCause(e)
.withDescription("Invalid Regex pattern: " + regexPattern);
}
return Status.OK;
}
}

0 comments on commit 31fc31e

Please sign in to comment.