From 869802dddd985ccfe5a10c1d0019c8acf35fb809 Mon Sep 17 00:00:00 2001 From: David Karlsson <35727626+dvdksn@users.noreply.github.com> Date: Sun, 11 Feb 2024 21:51:55 +0100 Subject: [PATCH] yaml: add processing for internal links, and tests Signed-off-by: David Karlsson <35727626+dvdksn@users.noreply.github.com> --- markdown.go | 13 +++++++++++++ markdown_test.go | 15 +++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/markdown.go b/markdown.go index 3284923..bd85487 100644 --- a/markdown.go +++ b/markdown.go @@ -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(`\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) @@ -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") diff --git a/markdown_test.go b/markdown_test.go index e801b22..97c9e20 100644 --- a/markdown_test.go +++ b/markdown_test.go @@ -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