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

yaml: add processing for internal links, and tests #49

Merged
merged 1 commit into from
Feb 19, 2024
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
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 {
dvdksn marked this conversation as resolved.
Show resolved Hide resolved
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