Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a warning when there is no matching start tag for an end tag #326

Merged
merged 1 commit into from
Apr 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/main/java/com/hubspot/jinjava/tree/TreeParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,13 @@ private void endTag(Tag tag, TagToken tagToken) {
parent.getMaster().setRightTrimAfterEnd(tagToken.isRightTrim());
}

boolean hasMatchingStartTag = false;
while (!(parent instanceof RootNode)) {
TagNode parentTag = (TagNode) parent;
parent = parent.getParent();

if (parentTag.getEndName().equals(tag.getEndTagName())) {
hasMatchingStartTag = true;
break;
} else {
interpreter.addError(TemplateError.fromException(
Expand All @@ -212,5 +214,17 @@ private void endTag(Tag tag, TagToken tagToken) {
tagToken.getLineNumber(), tagToken.getStartPosition())));
}
}
if (!hasMatchingStartTag) {
interpreter.addError(new TemplateError(
ErrorType.WARNING,
ErrorReason.SYNTAX_ERROR,
ErrorItem.TAG,
"Missing start tag",
tag.getName(),
tagToken.getLineNumber(),
tagToken.getStartPosition(),
null
));
}
}
}
11 changes: 11 additions & 0 deletions src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.hubspot.jinjava.Jinjava;
import com.hubspot.jinjava.JinjavaConfig;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import com.hubspot.jinjava.interpret.TemplateError.ErrorType;

public class TreeParserTest {

Expand Down Expand Up @@ -86,6 +87,16 @@ public void trimAndLstripBlocks() {
+ "</div>\n");
}

@Test
public void itWarnsAgainstMissingStartTags() {
String expression = "{% if true %} foo {% endif %} {% endif %}";
final Node tree = new TreeParser(interpreter, expression).buildTree();
assertThat(interpreter.getErrors()).hasSize(1);
assertThat(interpreter.getErrors().get(0).getSeverity()).isEqualTo(ErrorType.WARNING);
assertThat(interpreter.getErrors().get(0).getMessage()).isEqualTo("Missing start tag");
assertThat(interpreter.getErrors().get(0).getFieldName()).isEqualTo("endif");
}

Node parse(String fixture) {
try {
return new TreeParser(interpreter, Resources.toString(
Expand Down