From f8c9ff55b98adfbfbcc24efd178c114006f28336 Mon Sep 17 00:00:00 2001
From: Gusted <postmaster@gusted.xyz>
Date: Wed, 17 Jan 2024 17:45:55 +0100
Subject: [PATCH] [GITEA] Fix relative links rendering

- Backport of #2166
- Relative links were not properly being rendered, because the links
were being made absolute against the repository URL instead of
repository URL + /src/branch, which leads to incorrect links.
- Restore the 'old' behaviour. When there's branch information, that
should be used as base for links.
- Adjusts the test cases.
- Regression of 637451a45ecbc3d127ff2adf27437ce1357493ea
- Resolves https://codeberg.org/Codeberg/Community/issues/1411

(cherry picked from commit 0e9d52e2918004ac183910c712e9fe486e139e05)
---
 modules/markup/markdown/goldmark.go      | 2 ++
 modules/markup/markdown/markdown_test.go | 4 ++--
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/modules/markup/markdown/goldmark.go b/modules/markup/markdown/goldmark.go
index b92b90561b..1db3cbad7e 100644
--- a/modules/markup/markdown/goldmark.go
+++ b/modules/markup/markdown/goldmark.go
@@ -137,6 +137,8 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa
 				var base string
 				if ctx.IsWiki {
 					base = ctx.Links.WikiLink()
+				} else if ctx.Links.HasBranchInfo() {
+					base = ctx.Links.SrcLink()
 				} else {
 					base = ctx.Links.Base
 				}
diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go
index 6f2bbae6e0..5216d1973c 100644
--- a/modules/markup/markdown/markdown_test.go
+++ b/modules/markup/markdown/markdown_test.go
@@ -765,7 +765,7 @@ space</p>
 			Expected: `<p>space @mention-user<br/>
 /just/a/path.bin<br/>
 <a href="https://example.com/file.bin" rel="nofollow">https://example.com/file.bin</a><br/>
-<a href="/user/repo/file.bin" rel="nofollow">local link</a><br/>
+<a href="/user/repo/src/branch/main/file.bin" rel="nofollow">local link</a><br/>
 <a href="https://example.com" rel="nofollow">remote link</a><br/>
 <a href="/user/repo/src/branch/main/file.bin" rel="nofollow">local link</a><br/>
 <a href="https://example.com" rel="nofollow">remote link</a><br/>
@@ -878,7 +878,7 @@ space</p>
 			Expected: `<p>space @mention-user<br/>
 /just/a/path.bin<br/>
 <a href="https://example.com/file.bin" rel="nofollow">https://example.com/file.bin</a><br/>
-<a href="/user/repo/file.bin" rel="nofollow">local link</a><br/>
+<a href="/user/repo/src/branch/main/sub/folder/file.bin" rel="nofollow">local link</a><br/>
 <a href="https://example.com" rel="nofollow">remote link</a><br/>
 <a href="/user/repo/src/branch/main/sub/folder/file.bin" rel="nofollow">local link</a><br/>
 <a href="https://example.com" rel="nofollow">remote link</a><br/>