Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for GitHub issue/prs to markdown #5

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ dependencies = [
"youtube-transcript-api",
"SpeechRecognition",
"pathvalidate",
"pygithub"
]

[project.urls]
Expand Down
83 changes: 83 additions & 0 deletions src/markitdown/_markitdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@
except ModuleNotFoundError:
pass

# Optional GitHub issue support
try:
from github import Github

IS_GITHUB_ISSUE_CAPABLE = True
except ModuleNotFoundError:
IS_GITHUB_ISSUE_CAPABLE = False


class _CustomMarkdownify(markdownify.MarkdownConverter):
"""
Expand Down Expand Up @@ -837,6 +845,75 @@
return response.choices[0].message.content


class GitHubIssueConverter(DocumentConverter):
"""Converts GitHub issues to Markdown."""

def convert(self, issue_url, github_token) -> Union[None, DocumentConverterResult]:

# Bail if not a valid GitHub issue URL
if issue_url:
parsed_url = urlparse(issue_url)
path_parts = parsed_url.path.strip("/").split("/")
if len(path_parts) < 4 or path_parts[2] != "issues":
return None

if not github_token:
raise ValueError("GitHub token is not set. Cannot convert GitHub issue.")

return self._convert_github_issue(issue_url, github_token)

return None

def _convert_github_issue(
self, issue_url: str, github_token: str
) -> DocumentConverterResult:
"""
Convert a GitHub issue to a markdown document.
Args:
issue_url (str): The URL of the GitHub issue to convert.
github_token (str): A GitHub token with access to the repository.
Returns:
DocumentConverterResult: The result containing the issue title and markdown content.
Raises:
ImportError: If the PyGithub library is not installed.
ValueError: If the provided URL is not a valid GitHub issue URL.
"""
if not IS_GITHUB_ISSUE_CAPABLE:
raise ImportError(
"PyGithub is not installed. Please install it to use this feature."
)

# Parse the issue URL
parsed_url = urlparse(issue_url)
path_parts = parsed_url.path.strip("/").split("/")
if len(path_parts) < 4 or path_parts[2] != "issues":
raise ValueError("Invalid GitHub issue URL")

owner, repo, _, issue_number = path_parts[:4]

# Authenticate with GitHub
g = Github(github_token)
repo = g.get_repo(f"{owner}/{repo}")
issue = repo.get_issue(int(issue_number))

# Convert issue details to markdown
markdown_content = f"# {issue.title}\n\n{issue.body}\n\n"
markdown_content += f"**State:** {issue.state}\n"
markdown_content += f"**Created at:** {issue.created_at}\n"
markdown_content += f"**Updated at:** {issue.updated_at}\n"
markdown_content += f"**Comments:**\n"

for comment in issue.get_comments():
markdown_content += (
f"- {comment.user.login} ({comment.created_at}): {comment.body}\n"
)

return DocumentConverterResult(
title=issue.title,
text_content=markdown_content,
)


class FileConversionException(BaseException):
pass

Expand Down Expand Up @@ -889,6 +966,12 @@
- source: can be a string representing a path or url, or a requests.response object
- extension: specifies the file extension to use when interpreting the file. If None, infer from source (path, uri, content-type, etc.)
"""
# Handle GitHub issue URLs directly
if isinstance(source, str) and "github.com" in source and "/issues/" in source:
Fixed Show fixed Hide fixed
github_token = kwargs.get("github_token", os.getenv("GITHUB_TOKEN"))
if not github_token:
raise ValueError("GitHub token is required for GitHub issue conversion.")
return GitHubIssueConverter().convert(issue_url=source, github_token=github_token)

# Local path or url
if isinstance(source, str):
Expand Down
17 changes: 17 additions & 0 deletions tests/test_markitdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@
"data:image/svg+xml,%3Csvg%20width%3D",
]

GITHUB_ISSUE_URL = "https://github.com/microsoft/autogen/issues/1421"
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "")


@pytest.mark.skipif(
skip_remote,
Expand Down Expand Up @@ -179,8 +182,22 @@ def test_markitdown_exiftool() -> None:
assert target in result.text_content


@pytest.mark.skipif(
not GITHUB_TOKEN,
reason="GitHub token not provided",
)
def test_markitdown_github_issue() -> None:
markitdown = MarkItDown()
result = markitdown.convert(GITHUB_ISSUE_URL, github_token=GITHUB_TOKEN)
print(result.text_content)
assert "User-Defined Functions" in result.text_content
assert "closed" in result.text_content
assert "Comments:" in result.text_content


if __name__ == "__main__":
"""Runs this file's tests from the command line."""
test_markitdown_remote()
test_markitdown_local()
test_markitdown_exiftool()
test_markitdown_github_issue()
Loading