Skip to content

Commit 2139c15

Browse files
jonasfranztechknowlogick
authored andcommitted
Fix relative markdown links with anchors (#4058)
* Replace '%28' with '#' Add test case Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use ResolveReference instead of strings.Replace Signed-off-by: Jonas Franz <info@jonasfranz.software>
1 parent f86f56e commit 2139c15

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

modules/util/util.go

+16-6
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package util
77
import (
88
"net/url"
99
"path"
10+
"strings"
1011

1112
"code.gitea.io/gitea/modules/log"
1213
)
@@ -56,16 +57,25 @@ func Max(a, b int) int {
5657

5758
// URLJoin joins url components, like path.Join, but preserving contents
5859
func URLJoin(base string, elems ...string) string {
59-
u, err := url.Parse(base)
60+
if !strings.HasSuffix(base, "/") {
61+
base += "/"
62+
}
63+
baseURL, err := url.Parse(base)
6064
if err != nil {
6165
log.Error(4, "URLJoin: Invalid base URL %s", base)
6266
return ""
6367
}
64-
joinArgs := make([]string, 0, len(elems)+1)
65-
joinArgs = append(joinArgs, u.Path)
66-
joinArgs = append(joinArgs, elems...)
67-
u.Path = path.Join(joinArgs...)
68-
return u.String()
68+
joinedPath := path.Join(elems...)
69+
argURL, err := url.Parse(joinedPath)
70+
if err != nil {
71+
log.Error(4, "URLJoin: Invalid arg %s", joinedPath)
72+
return ""
73+
}
74+
joinedURL := baseURL.ResolveReference(argURL).String()
75+
if !baseURL.IsAbs() {
76+
return joinedURL[1:] // Removing leading '/'
77+
}
78+
return joinedURL
6979
}
7080

7181
// Min min of two ints

modules/util/util_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ func TestURLJoin(t *testing.T) {
3030
"a", "b/c/"),
3131
newTest("a/b/d",
3232
"a/", "b/c/", "/../d/"),
33+
newTest("https://try.gitea.io/a/b/c#d",
34+
"https://try.gitea.io", "a/b", "c#d"),
3335
} {
3436
assert.Equal(t, test.Expected, URLJoin(test.Base, test.Elements...))
3537
}

0 commit comments

Comments
 (0)