Skip to content

Commit d99bd24

Browse files
Copilotalexr00
andcommitted
Add commit SHA linking to file view comments
Co-authored-by: alexr00 <38270282+alexr00@users.noreply.github.com>
1 parent 2c12a46 commit d99bd24

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/github/prComment.ts

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,38 @@ ${lineContents}
421421
return replaceImages(body, html, this.githubRepository?.remote.host);
422422
}
423423

424+
private replaceCommitShas(body: string): string {
425+
const githubRepository = this.githubRepository;
426+
if (!githubRepository) {
427+
return body;
428+
}
429+
430+
// Match commit SHAs that are:
431+
// - Either 7 or 40 hex characters
432+
// - Not already part of a URL or markdown link
433+
// - Not inside code blocks (backticks)
434+
const commitShaRegex = /(?<![`\/\w])([0-9a-f]{7})([0-9a-f]{33})?(?![`\/\w])/g;
435+
436+
return body.replace(commitShaRegex, (match, shortSha, remaining, offset) => {
437+
// Don't replace if inside code blocks
438+
const beforeMatch = body.substring(0, offset);
439+
const backtickCount = (beforeMatch.match(/`/g)?.length ?? 0);
440+
if (backtickCount % 2 === 1) {
441+
return match;
442+
}
443+
444+
// Don't replace if already part of a markdown link
445+
if (beforeMatch.endsWith('[') || body.substring(offset + match.length).startsWith(']')) {
446+
return match;
447+
}
448+
449+
const owner = githubRepository.remote.owner;
450+
const repo = githubRepository.remote.repositoryName;
451+
const commitUrl = `https://${githubRepository.remote.host}/${owner}/${repo}/commit/${match}`;
452+
return `[${shortSha}](${commitUrl})`;
453+
});
454+
}
455+
424456
private replaceNewlines(body: string) {
425457
return body.replace(/(?<!\s)(\r\n|\n)/g, ' \n');
426458
}
@@ -463,7 +495,8 @@ ${lineContents}
463495
return `${substring.startsWith('@') ? '' : substring.charAt(0)}[@${username}](${url})`;
464496
});
465497

466-
const permalinkReplaced = await this.replacePermalink(linkified);
498+
const commitShasReplaced = this.replaceCommitShas(linkified);
499+
const permalinkReplaced = await this.replacePermalink(commitShasReplaced);
467500
await emojiPromise;
468501
return this.postpendSpecialAuthorComment(emojify(this.replaceImg(this.replaceSuggestion(permalinkReplaced))));
469502
}

0 commit comments

Comments
 (0)