Skip to content

Commit

Permalink
fix linking commit URL doesn't work when it is a child of some other …
Browse files Browse the repository at this point in the history
…node
  • Loading branch information
rhysd committed Oct 1, 2024
1 parent 744fe10 commit 36548a1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
26 changes: 18 additions & 8 deletions reflink.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,24 +216,34 @@ var reGitHubCommitURL = regexp.MustCompile(`^https://github\.com/([^/]+/[^/]+)/c

func (l *Reflinker) linkGitHubURL(n *ast.AutoLink, src []byte) {
start := 0
p := n.PreviousSibling()
if p != nil {
if p := n.PreviousSibling(); p != nil {
t := p.(*ast.Text)
if t == nil {
return
}
start = t.Segment.Stop
}
label := n.Label(src)
stop := start + len(label)

url := n.URL(src)

// Search the offset of the start of the URL. When the text is a child of some other node, URL
// may not appear just after the previous node. The example is **https://...** where URL appers
// after the first **.
offset := bytes.Index(src[start:], url)
if offset < 0 {
return
}
start += offset

stop := start + len(url)
if start >= len(src) || stop > len(src) {
return
}
if src[start] == '<' && stop+1 < len(src) && src[stop+1] == '>' {
return
}

m := reGitHubCommitURL.FindSubmatch(label)
m := reGitHubCommitURL.FindSubmatch(url)
if m == nil {
return
}
Expand All @@ -244,10 +254,10 @@ func (l *Reflinker) linkGitHubURL(n *ast.AutoLink, src []byte) {
}

var replaced string
if bytes.HasPrefix(label, []byte(l.repo)) {
replaced = fmt.Sprintf("[`%s`](%s)", hash, label)
if bytes.HasPrefix(url, []byte(l.repo)) {
replaced = fmt.Sprintf("[`%s`](%s)", hash, url)
} else {
replaced = fmt.Sprintf("[`%s@%s`](%s)", slug, hash, label)
replaced = fmt.Sprintf("[`%s@%s`](%s)", slug, hash, url)
}

l.links = append(l.links, refLink{
Expand Down
10 changes: 10 additions & 0 deletions reflink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,16 @@ func TestLinkRefs(t *testing.T) {
input: "[this commit](https://github.com/foo/bar/commit/1d457ba853aa10f9a6c925a1b73d5aed38066ffe)",
want: "[this commit](https://github.com/foo/bar/commit/1d457ba853aa10f9a6c925a1b73d5aed38066ffe)",
},
{
what: "commit URL in code snippet",
input: "`https://github.com/foo/bar/commit/1d457ba853aa10f9a6c925a1b73d5aed38066ffe`",
want: "`https://github.com/foo/bar/commit/1d457ba853aa10f9a6c925a1b73d5aed38066ffe`",
},
{
what: "commit URL in bold text",
input: "**https://github.com/foo/bar/commit/1d457ba853aa10f9a6c925a1b73d5aed38066ffe**",
want: "**[`foo/bar@1d457ba853`](https://github.com/foo/bar/commit/1d457ba853aa10f9a6c925a1b73d5aed38066ffe)**",
},
}

for _, tc := range tests {
Expand Down

0 comments on commit 36548a1

Please sign in to comment.