Skip to content

Commit

Permalink
Merge pull request #2219 from alixander/markdown-comment
Browse files Browse the repository at this point in the history
markdown: sanitize links
  • Loading branch information
alixander authored Nov 18, 2024
2 parents ad62935 + b4382a6 commit fed65bc
Show file tree
Hide file tree
Showing 5 changed files with 153 additions and 1 deletion.
1 change: 1 addition & 0 deletions ci/release/changelogs/next.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
#### Bugfixes ⛑️

- Imports: fixes using substitutions in `icon` values [#2207](https://github.com/terrastruct/d2/pull/2207)
- Markdown: fixes ampersands in URLs in markdown [#2219](https://github.com/terrastruct/d2/pull/2219)
7 changes: 7 additions & 0 deletions d2compiler/compile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -935,6 +935,13 @@ b.(x -> y)[0]: two
}
},
},
{
name: "markdown_ampersand",
text: `memo: |md
<a href="https://www.google.com/search?q=d2&newwindow=1&amp;bar">d2</a>
|
`,
},
{
name: "unsemantic_markdown",

Expand Down
26 changes: 26 additions & 0 deletions lib/textmeasure/links.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package textmeasure

import (
"fmt"
"regexp"
"strings"
)

func sanitizeLinks(input string) (string, error) {
re := regexp.MustCompile(`href="([^"]*)"`)

return re.ReplaceAllStringFunc(input, func(href string) string {
matches := re.FindStringSubmatch(href)
if len(matches) < 2 {
return href
}

value := matches[1]

value = strings.ReplaceAll(value, "&amp;", "TEMP_AMP")
value = strings.ReplaceAll(value, "&", "&amp;")
value = strings.ReplaceAll(value, "TEMP_AMP", "&amp;")

return fmt.Sprintf(`href="%s"`, value)
}), nil
}
6 changes: 5 additions & 1 deletion lib/textmeasure/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ func RenderMarkdown(m string) (string, error) {
if err := markdownRenderer.Convert([]byte(m), &output); err != nil {
return "", err
}
return output.String(), nil
sanitized, err := sanitizeLinks(output.String())
if err != nil {
return "", err
}
return sanitized, nil
}

func init() {
Expand Down
114 changes: 114 additions & 0 deletions testdata/d2compiler/TestCompile/markdown_ampersand.exp.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit fed65bc

Please sign in to comment.