Skip to content

Commit

Permalink
fix: escape attribute values
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h committed Nov 8, 2023
1 parent c3d4a33 commit 5bd994f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
5 changes: 3 additions & 2 deletions format.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func printPre(w io.Writer, n *html.Node) (err error) {
return
}
for _, a := range n.Attr {
val := a.Val
val := html.EscapeString(a.Val)
if _, err = fmt.Fprintf(w, ` %s="%s"`, a.Key, val); err != nil {
return
}
Expand Down Expand Up @@ -130,7 +130,8 @@ func printNode(w io.Writer, n *html.Node, level int) (err error) {
return
}
for _, a := range n.Attr {
if _, err = fmt.Fprintf(w, ` %s="%s"`, a.Key, a.Val); err != nil {
val := html.EscapeString(a.Val)
if _, err = fmt.Fprintf(w, ` %s="%s"`, a.Key, val); err != nil {
return
}
}
Expand Down
37 changes: 35 additions & 2 deletions format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,43 @@ func TestFormat(t *testing.T) {
expected string
}{
{
name: "html elements are indented",
name: "missing closing tags are inserted",
input: `<li>`,
expected: `<li>
</li>
`,
},
{
name: "html attribute escaping is normalized",
input: `<ol> <li style="&amp;&#38;"> A </li> <li> B </li> </ol> `,
expected: `<ol>
<li style="&amp;&amp;">
A
</li>
<li>
B
</li>
</ol>
`,
},
{
name: "bare ampersands are escaped",
input: `<ol> <li style="&"> A </li> <li> B </li> </ol> `,
expected: `<ol>
<li style="&">
<li style="&amp;">
A
</li>
<li>
B
</li>
</ol>
`,
},
{
name: "html elements are indented",
input: `<ol> <li class="name"> A </li> <li> B </li> </ol> `,
expected: `<ol>
<li class="name">
A
</li>
<li>
Expand Down

0 comments on commit 5bd994f

Please sign in to comment.