Skip to content

Commit

Permalink
yaml: add processing for internal links, and tests
Browse files Browse the repository at this point in the history
Signed-off-by: David Karlsson <[email protected]>
  • Loading branch information
dvdksn committed Feb 13, 2024
1 parent f588677 commit 869802d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
13 changes: 13 additions & 0 deletions markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ var (
// for our use-case; DO NOT consider using this as a generic regex, or at least
// not before reading https://stackoverflow.com/a/1732454/1811501.
htmlAnchor = regexp.MustCompile(`<a\s+(?:name|id)="?([^"]+)"?\s*></a>\s*`)
// relativeLink matches parts of internal links between .md documents
// e.g. "](buildx_build.md)"
relativeLink = regexp.MustCompile(`\]\((\.\/)?[a-z-_]+\.md(#.*)?\)`)
)

// getSections returns all H2 sections by title (lowercase)
Expand Down Expand Up @@ -58,6 +61,16 @@ func cleanupMarkDown(mdString string) (md string, anchors []string) {
mdString = strings.ReplaceAll(mdString, "\t", " ")
mdString = strings.ReplaceAll(mdString, "https://docs.docker.com", "")

// Rewrite internal links, replacing relative paths with absolute path
// e.g. from [docker buildx build](buildx_build.md#build-arg)
// to [docker buildx build](/reference/cli/docker/buildx/build/#build-arg)
mdString = relativeLink.ReplaceAllStringFunc(mdString, func(link string) string {
link = strings.TrimLeft(link, "](./")
link = strings.ReplaceAll(link, "_", "/")
link = strings.ReplaceAll(link, ".md", "/")
return "](/reference/cli/docker/" + link
})

var id string
// replace trailing whitespace per line, and handle custom anchors
lines := strings.Split(mdString, "\n")
Expand Down
15 changes: 15 additions & 0 deletions markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,21 @@ This is a line.
Last line.`,
},
{
doc: "Link preprocessing",
in: `[link1](https://example.com/)
[link2](https://docs.docker.com/foo/bar/)
[link3](buildx_build.md)
[link4](buildx_imagetools_create.md)
[link5](buildx_build.md#build-arg)
[link6](./swarm_join-token.md)`,
expected: `[link1](https://example.com/)
[link2](/foo/bar/)
[link3](/reference/cli/docker/buildx/build/)
[link4](/reference/cli/docker/buildx/imagetools/create/)
[link5](/reference/cli/docker/buildx/build/#build-arg)
[link6](/reference/cli/docker/swarm/join-token/)`,
},
}
for _, tc := range tests {
tc := tc
Expand Down

0 comments on commit 869802d

Please sign in to comment.