This repository was archived by the owner on Nov 21, 2026. It is now read-only.
Repository navigation
Github line previews cog + tests #188
Open
Xarlos89
wants to merge
1
commit into
master
Choose a base branch
from
feature/github-line-preview
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| """ | ||
| When someone posts a GitHub link with line numbers (like #L3 or #L3-L9), | ||
| the bot replies with those lines in a code block. | ||
| """ | ||
|
|
||
| import logging | ||
| import re | ||
|
|
||
| import aiohttp | ||
| from discord.ext import commands | ||
|
|
||
| from src.bot.cogs import BaseCog | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # This monster matches links like https://github.com/owner/repo/blob/branch/file.py#L3-L9 | ||
| # Thx uncle | ||
| GITHUB_LINK_PATTERN = r"https://github\.com/([\w.-]+)/([\w.-]+)/blob/([^\s?#]+)(?:\?[^\s#]*)?#L(\d+)(?:-L(\d+))?" | ||
| MAX_LINKS = 3 | ||
| MAX_MESSAGE_LENGTH = 2000 | ||
| TRUNCATED_TEXT = "\n... (truncated)\n```" | ||
|
|
||
|
|
||
| def parse_links(content): | ||
| """ | ||
| Finds GitHub line links in a message. | ||
| Returns a list of (owner, repo, path, start, end). | ||
| """ | ||
| links = [] | ||
| dat_match = re.findall(GITHUB_LINK_PATTERN, content) | ||
|
|
||
| for bleh in dat_match: | ||
| owner = bleh[0] | ||
| repo = bleh[1] | ||
| path = bleh[2] | ||
| start = int(bleh[3]) | ||
|
|
||
| # A link like #L3 has no end line, so the end is the same as the start | ||
| if bleh[4] == "": | ||
| end = start | ||
| else: | ||
| end = int(bleh[4]) | ||
|
|
||
| # Someone might write #L9-L3, so swap them | ||
| if start > end: | ||
| temp = start | ||
| start = end | ||
| end = temp | ||
|
|
||
| links.append((owner, repo, path, start, end)) | ||
|
|
||
| if len(links) == MAX_LINKS: | ||
| break | ||
|
|
||
| return links | ||
|
|
||
|
|
||
| def format_snippet(header, text, start, end): | ||
| """Builds the message for one link.""" | ||
| all_lines = text.splitlines() | ||
|
|
||
| # The link might ask for more lines than the file has | ||
| if end > len(all_lines): | ||
| end = len(all_lines) | ||
|
|
||
| # The link starts after the last line of the file, so there is nothing to show | ||
| if start > end: | ||
| return None | ||
|
|
||
| # Line numbers dont index at 0 | ||
| wanted_lines = all_lines[start - 1 : end] | ||
| code = "\n".join(wanted_lines) | ||
|
|
||
| # Stop the file's own ``` from ending our code block early | ||
| code = code.replace("```", "```") | ||
|
|
||
| # Use the file extension for syntax highlighting | ||
| file_name = header.split("/")[-1] | ||
| language = "" | ||
| if "." in file_name: | ||
| language = file_name.split(".")[-1] | ||
|
|
||
| if start == end: | ||
| line_text = f"L{start}" | ||
| else: | ||
| line_text = f"L{start}-L{end}" | ||
|
|
||
| return f"**{header}** {line_text}\n```{language}\n{code}\n```" | ||
|
|
||
|
|
||
| def truncate(content): | ||
| """Discord messages can only be 2000 characters""" | ||
| if len(content) <= MAX_MESSAGE_LENGTH: | ||
| # lol so sry | ||
| return content | ||
|
|
||
| keep = MAX_MESSAGE_LENGTH - len(TRUNCATED_TEXT) | ||
| return content[:keep] + TRUNCATED_TEXT | ||
|
|
||
|
|
||
| class GithubLines(BaseCog): | ||
| """Shows the code from GitHub line links in chat.""" | ||
|
|
||
| def __init__(self, bot): | ||
| super().__init__(logger) | ||
|
|
||
| self.bot = bot | ||
|
|
||
| @commands.Cog.listener() | ||
| async def on_message(self, message): | ||
| # Ignore other bots and DMs | ||
| if message.author.bot: | ||
| return | ||
| if message.guild is None: | ||
| return | ||
|
|
||
| links = parse_links(message.content) | ||
| if len(links) == 0: | ||
| return | ||
|
|
||
| snippets = [] | ||
| timeout = aiohttp.ClientTimeout(total=10) | ||
|
|
||
| async with aiohttp.ClientSession(timeout=timeout) as session: | ||
| for owner, repo, path, start, end in links: | ||
| url = ( | ||
| "https://raw.githubusercontent.com/" | ||
| + owner | ||
| + "/" | ||
| + repo | ||
| + "/" | ||
| + path | ||
| ) | ||
|
|
||
| try: | ||
| async with session.get(url) as response: | ||
| # For anything that isn't 200, private repo or wrong link, just skip it | ||
| if response.status != 200: | ||
| continue | ||
| text = await response.text() | ||
| except (aiohttp.ClientError, TimeoutError): | ||
| logger.warning("Failed to fetch %s", url) | ||
| continue | ||
|
|
||
| # path is "branch/folder/file.py", so drop the branch for the header | ||
| path_parts = path.split("/", 1) | ||
| header = repo + "/" + path_parts[-1] | ||
|
|
||
| snippet = format_snippet(header, text, start, end) | ||
| if snippet is not None: | ||
| snippets.append(snippet) | ||
|
|
||
| if len(snippets) == 0: | ||
| return | ||
|
|
||
| logger.info( | ||
| "Previewing %d GitHub link(s) for %s", len(snippets), message.author.name | ||
| ) | ||
| reply_text = "\n".join(snippets) | ||
| await message.reply(truncate(reply_text), mention_author=False) | ||
|
|
||
|
|
||
| async def setup(bot): | ||
| """ | ||
| Required. | ||
| """ | ||
| await bot.add_cog(GithubLines(bot)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | ||
| if not hasattr(sys.modules.get("aiohttp"), "__file__"): | ||
| sys.modules.pop("aiohttp", None) | ||
|
|
||
| from src.bot.cogs.features.github_lines import ( # noqa: E402 | ||
| MAX_MESSAGE_LENGTH, | ||
| format_snippet, | ||
| parse_links, | ||
| truncate, | ||
| ) | ||
|
|
||
| BASE = "https://github.com/diogoscf/github-lines/blob/master/package.json" | ||
|
|
||
|
|
||
| def test_single_line(): | ||
| assert parse_links(f"look {BASE}#L3 here") == [ | ||
| ("diogoscf", "github-lines", "master/package.json", 3, 3) | ||
| ] | ||
|
|
||
|
|
||
| def test_3to9_and_9to3(): | ||
| assert parse_links(f"{BASE}#L3-L9")[0][3:] == (3, 9) | ||
| assert parse_links(f"{BASE}#L9-L3")[0][3:] == (3, 9) | ||
|
|
||
|
|
||
| def test_branch_with_slash(): | ||
| link = "https://github.com/a/b/blob/feature/x/src/main.py#L1" | ||
| assert parse_links(link)[0][2] == "feature/x/src/main.py" | ||
|
|
||
|
|
||
| def test_extra_parameter(): | ||
| link = "https://github.com/a/b/blob/master/README.md?plain=1#L11-L15" | ||
| assert parse_links(link) == [("a", "b", "master/README.md", 11, 15)] | ||
|
|
||
|
|
||
| def test_ignored_links(): | ||
| assert parse_links(BASE) == [] | ||
| assert parse_links("https://gitlab.com/a/b/blob/main/x.py#L1") == [] | ||
|
|
||
|
|
||
| def test_format_snippet(): | ||
| text = "a\nb\nc\nd" | ||
| assert ( | ||
| format_snippet("repo/x.py", text, 2, 3) | ||
| == "**repo/x.py** L2-L3\n```py\nb\nc\n```" | ||
| ) | ||
| assert format_snippet("repo/x.py", text, 4, 99).startswith("**repo/x.py** L4\n") | ||
| assert format_snippet("repo/x.py", text, 10, 12) is None | ||
| assert format_snippet("repo/Makefile", text, 1, 1).startswith( | ||
| "**repo/Makefile** L1\n```\n" | ||
| ) | ||
|
|
||
|
|
||
| def test_backticks_escaped(): | ||
| snippet = format_snippet("r/x.md", "```evil```", 1, 1) | ||
| assert snippet.count("```") == 2 | ||
|
|
||
|
|
||
| def test_truncate(): | ||
| out = truncate("```\n" + "x" * 5000) | ||
| assert len(out) == MAX_MESSAGE_LENGTH | ||
| assert out.endswith("```") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why?