From d2e4c808e6897fafbf4ab0716d1ded2a1e872e4d Mon Sep 17 00:00:00 2001 From: Jakub Kuczys Date: Sat, 14 Nov 2026 17:31:09 +0100 Subject: [PATCH 1/7] Fix handling of temporary private forks --- github_backup/github_backup.py | 78 ++++++++++++++++++++++++++++---- github_backup/graphql_queries.py | 67 +++++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 9 deletions(-) diff --git a/github_backup/github_backup.py b/github_backup/github_backup.py index 64c08c3..f3d1e8a 100644 --- a/github_backup/github_backup.py +++ b/github_backup/github_backup.py @@ -42,7 +42,9 @@ DISCUSSION_PAGE_SIZE, DISCUSSION_REPLIES_QUERY, ISSUE_CROSS_REFERENCE_COUNT_QUERY, + PULL_COMMENTS_QUERY, PULL_CROSS_REFERENCE_COUNT_QUERY, + PULL_PAGE_SIZE, ) FILE_URI_PREFIX = "file://" @@ -2367,7 +2369,7 @@ def backup_repositories(args, output_directory, repositories): lfs_clone=args.lfs_clone, no_prune=args.no_prune, ) - if args.include_issues or args.include_everything: + if repository["has_issues"] and (args.include_issues or args.include_everything): incremental_resource_work_attempted = True issue_cwd = os.path.join(repo_cwd, "issues") args.since = read_resource_last_update( @@ -2376,7 +2378,7 @@ def backup_repositories(args, output_directory, repositories): backup_issues(args, repo_cwd, repository, repos_template) write_resource_last_update(args, issue_cwd, repository) - if args.include_pulls or args.include_everything: + if repository["has_pull_requests"] and (args.include_pulls or args.include_everything): incremental_resource_work_attempted = True pulls_cwd = os.path.join(repo_cwd, "pulls") args.since = read_resource_last_update( @@ -2385,7 +2387,7 @@ def backup_repositories(args, output_directory, repositories): backup_pulls(args, repo_cwd, repository, repos_template) write_resource_last_update(args, pulls_cwd, repository) - if args.include_discussions or args.include_everything: + if repository["has_discussions"] and (args.include_discussions or args.include_everything): backup_discussions(args, repo_cwd, repository) if args.include_milestones or args.include_everything: @@ -3144,7 +3146,6 @@ def pull_is_due_for_repository_checkpoint(pull): # regular comments need to be fetched via issue API. # For backwards compatibility with versions <= 0.41.0 # keep name "comment_data" for review comments - comments_regular_template = _issue_template + "/{0}/comments" comments_template = _pulls_template + "/{0}/comments" commits_template = _pulls_template + "/{0}/commits" reviews_template = _pulls_template + "/{0}/reviews" @@ -3175,8 +3176,49 @@ def pull_is_due_for_repository_checkpoint(pull): if ( args.include_pull_comments or args.include_everything ) and should_fetch_non_review_data: - template = comments_regular_template.format(number) - pulls[number]["comment_regular_data"] = retrieve_data(args, template) + after = None + comments_page = 1 + comments = [] + comment_total_count = 0 + owner, name = _repository_owner_name(repository) + while True: + data = retrieve_graphql_data( + args, + PULL_COMMENTS_QUERY, + { + "owner": owner, + "name": name, + "number": number, + "after": after, + "pageSize": PULL_PAGE_SIZE, + }, + log_context="pull request {0}#{1} comments page {2}".format( + repository["full_name"], number, comments_page + ), + ) + repository_data = data.get("repository") or {} + pr_data = repository_data.get("pullRequest") + if pr_data is None: + raise Exception( + "Pull request #{0} not found in {1}".format( + number, repository["full_name"] + ) + ) + + comments_connection = pr_data.get("comments") or {} + comment_total_count = comments_connection.get( + "totalCount", comment_total_count + ) + comments.extend(_connection_nodes(comments_connection)) + + page_info = comments_connection.get("pageInfo") or {} + if not page_info.get("hasNextPage"): + break + + after = page_info.get("endCursor") + comments_page += 1 + pulls[number]["comment_regular_data"] = comments + template = comments_template.format(number) pulls[number]["comment_data"] = retrieve_data(args, template) if include_pull_reviews: @@ -3230,7 +3272,13 @@ def backup_milestones(args, repo_cwd, repository, repos_template): query_args = {"state": "all"} - _milestones = retrieve_data(args, template, query_args=query_args) + try: + _milestones = retrieve_data(args, template, query_args=query_args) + except HTTPError as e: + if e.code == 404: + logger.info("Milestones are not available for this repository, skipping") + return + raise milestones = {} for milestone in _milestones: @@ -3303,7 +3351,13 @@ def backup_labels(args, repo_cwd, repository, repos_template): label_cwd = os.path.join(repo_cwd, "labels") output_file = "{0}/labels.json".format(label_cwd) template = "{0}/{1}/labels".format(repos_template, repository["full_name"]) - _backup_data(args, "labels", template, output_file, label_cwd) + try: + _backup_data(args, "labels", template, output_file, label_cwd) + except HTTPError as e: + if e.code == 404: + logger.info("Labels are not available for this repository, skipping") + return + raise def backup_hooks(args, repo_cwd, repository, repos_template): @@ -3348,7 +3402,13 @@ def backup_releases(args, repo_cwd, repository, repos_template, include_assets=F query_args = {} release_template = "{0}/{1}/releases".format(repos_template, repository_fullname) - releases = retrieve_data(args, release_template, query_args=query_args) + try: + releases = retrieve_data(args, release_template, query_args=query_args) + except HTTPError as e: + if e.code == 404: + logger.info("Releases are not available for this repository, skipping") + return + raise if args.skip_prerelease: releases = [r for r in releases if not r["prerelease"] and not r["draft"]] diff --git a/github_backup/graphql_queries.py b/github_backup/graphql_queries.py index a80d131..ed2ac4d 100644 --- a/github_backup/graphql_queries.py +++ b/github_backup/graphql_queries.py @@ -1,6 +1,7 @@ """GraphQL query templates used by github-backup.""" DISCUSSION_PAGE_SIZE = 100 +PULL_PAGE_SIZE = 100 CROSS_REFERENCE_PAGE_SIZE = 100 @@ -62,6 +63,72 @@ } """ +PULL_COMMENTS_QUERY = """ +query($owner: String!, $name: String!, $number: Int!, $after: String, $pageSize: Int!) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + comments(first: $pageSize, after: $after) { + totalCount + nodes { + ...IssueCommentFields + } + pageInfo { + hasNextPage + endCursor + } + } + } + } +} + +fragment ActorFields on Actor { + avatarUrl + login + resourcePath + url +} + +fragment ReactionGroupFields on ReactionGroup { + content + reactors { + totalCount + } +} + +fragment IssueCommentFields on IssueComment { + author { + ...ActorFields + } + authorAssociation + body + bodyHTML + bodyText + createdAt + createdViaEmail + databaseId + editor { + ...ActorFields + } + id + includesCreatedEdit + isMinimized + isPinned + lastEditedAt + minimizedReason + pinnedAt + pinnedBy { + ...ActorFields + } + publishedAt + reactionGroups { + ...ReactionGroupFields + } + resourcePath + updatedAt + url +} +""" + DISCUSSION_LIST_QUERY = """ query($owner: String!, $name: String!, $after: String, $pageSize: Int!) { repository(owner: $owner, name: $name) { From c7fb6c41d1df1924fe3695874ccaed9975476084 Mon Sep 17 00:00:00 2001 From: Jakub Kuczys Date: Sun, 15 Nov 2026 05:49:08 +0100 Subject: [PATCH 2/7] Add missing fields to test cases --- tests/test_all_starred.py | 12 ++++++++++++ tests/test_incremental_per_repository.py | 3 +++ tests/test_skip_assets_on.py | 3 +++ 3 files changed, 18 insertions(+) diff --git a/tests/test_all_starred.py b/tests/test_all_starred.py index 9776926..914e179 100644 --- a/tests/test_all_starred.py +++ b/tests/test_all_starred.py @@ -30,6 +30,9 @@ def test_all_starred_clones_without_repositories_flag(self, mock_get_url, mock_f "private": False, "fork": False, "has_wiki": False, + "has_issues": True, + "has_pull_requests": True, + "has_discussions": True, "is_starred": True, # This flag is set for starred repos } @@ -56,6 +59,9 @@ def test_starred_repo_not_cloned_without_all_starred_flag(self, mock_get_url, mo "private": False, "fork": False, "has_wiki": False, + "has_issues": True, + "has_pull_requests": True, + "has_discussions": True, "is_starred": True, } @@ -80,6 +86,9 @@ def test_non_starred_repo_not_cloned_with_only_all_starred(self, mock_get_url, m "private": False, "fork": False, "has_wiki": False, + "has_issues": True, + "has_pull_requests": True, + "has_discussions": True, # No is_starred flag } @@ -103,6 +112,9 @@ def test_repositories_flag_still_works(self, mock_get_url, mock_fetch, create_ar "private": False, "fork": False, "has_wiki": False, + "has_issues": True, + "has_pull_requests": True, + "has_discussions": True, } with patch('github_backup.github_backup.mkdir_p'): diff --git a/tests/test_incremental_per_repository.py b/tests/test_incremental_per_repository.py index f1fd67a..7ad5ddc 100644 --- a/tests/test_incremental_per_repository.py +++ b/tests/test_incremental_per_repository.py @@ -15,6 +15,9 @@ def _repo(name, updated_at, pushed_at=None): "private": False, "fork": False, "has_wiki": False, + "has_issues": True, + "has_pull_requests": True, + "has_discussions": True, "updated_at": updated_at, "pushed_at": pushed_at, } diff --git a/tests/test_skip_assets_on.py b/tests/test_skip_assets_on.py index 519750e..d3fd743 100644 --- a/tests/test_skip_assets_on.py +++ b/tests/test_skip_assets_on.py @@ -22,6 +22,9 @@ def _create_mock_repository(self, name="test-repo", owner="testuser"): "private": False, "fork": False, "has_wiki": False, + "has_issues": True, + "has_pull_requests": True, + "has_discussions": True, } def _create_mock_release(self, tag="v1.0.0"): From a10af4e0e8905106658bcc0f0846dd8b73f93294 Mon Sep 17 00:00:00 2001 From: Jakub Kuczys Date: Sun, 15 Nov 2026 05:56:47 +0100 Subject: [PATCH 3/7] Assume has_pull_requests may not be present per API docs --- github_backup/github_backup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github_backup/github_backup.py b/github_backup/github_backup.py index f3d1e8a..3126f47 100644 --- a/github_backup/github_backup.py +++ b/github_backup/github_backup.py @@ -2378,7 +2378,7 @@ def backup_repositories(args, output_directory, repositories): backup_issues(args, repo_cwd, repository, repos_template) write_resource_last_update(args, issue_cwd, repository) - if repository["has_pull_requests"] and (args.include_pulls or args.include_everything): + if repository.get("has_pull_requests", True) and (args.include_pulls or args.include_everything): incremental_resource_work_attempted = True pulls_cwd = os.path.join(repo_cwd, "pulls") args.since = read_resource_last_update( From 90c04b8a25b7bf645ab5b392fd1d9e3f58c97eb4 Mon Sep 17 00:00:00 2001 From: Jakub Kuczys Date: Wed, 25 Nov 2026 18:19:02 +0100 Subject: [PATCH 4/7] Try REST API for comments before GraphQL --- github_backup/github_backup.py | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/github_backup/github_backup.py b/github_backup/github_backup.py index 3126f47..adcbfd6 100644 --- a/github_backup/github_backup.py +++ b/github_backup/github_backup.py @@ -3052,6 +3052,51 @@ def get_pull_reviews_since(args, pulls_cwd): return args_since or reviews_since, reviews_since, reviews_last_update_path +def get_pull_comments_with_graphql(args, repository, number): + after = None + comments_page = 1 + comments = [] + comment_total_count = 0 + owner, name = _repository_owner_name(repository) + while True: + data = retrieve_graphql_data( + args, + PULL_COMMENTS_QUERY, + { + "owner": owner, + "name": name, + "number": number, + "after": after, + "pageSize": PULL_PAGE_SIZE, + }, + log_context="pull request {0}#{1} comments page {2}".format( + repository["full_name"], number, comments_page + ), + ) + repository_data = data.get("repository") or {} + pr_data = repository_data.get("pullRequest") + if pr_data is None: + raise Exception( + "Pull request #{0} not found in {1}".format( + number, repository["full_name"] + ) + ) + + comments_connection = pr_data.get("comments") or {} + comment_total_count = comments_connection.get( + "totalCount", comment_total_count + ) + comments.extend(_connection_nodes(comments_connection)) + + page_info = comments_connection.get("pageInfo") or {} + if not page_info.get("hasNextPage"): + break + + after = page_info.get("endCursor") + comments_page += 1 + return comments + + def backup_pulls(args, repo_cwd, repository, repos_template): has_pulls_dir = os.path.isdir("{0}/pulls/.git".format(repo_cwd)) if args.skip_existing and has_pulls_dir: @@ -3146,6 +3191,7 @@ def pull_is_due_for_repository_checkpoint(pull): # regular comments need to be fetched via issue API. # For backwards compatibility with versions <= 0.41.0 # keep name "comment_data" for review comments + comments_regular_template = _issue_template + "/{0}/comments" comments_template = _pulls_template + "/{0}/comments" commits_template = _pulls_template + "/{0}/commits" reviews_template = _pulls_template + "/{0}/reviews" @@ -3176,6 +3222,19 @@ def pull_is_due_for_repository_checkpoint(pull): if ( args.include_pull_comments or args.include_everything ) and should_fetch_non_review_data: + template = comments_regular_template.format(number) + try: + pulls[number]["comment_regular_data"] = retrieve_data(args, template) + except HTTPError as e: + # Issue #547: REST API endpoint for regular comments on temporary + # private forks returns 404. There's nothing in repo data that would + # indicate that repo is private temporary fork so best we can do is + # limit this special case a bit more by limiting it to private repos. + if not repository.get("private", False) or e.code != 404: + raise + pulls[number]["comment_regular_data"] = get_pull_comments_with_graphql( + args, repository, number + ) after = None comments_page = 1 comments = [] From 7ebbdc8b5a778200cddfd75c9a65d02564d0b18b Mon Sep 17 00:00:00 2001 From: Jakub Kuczys Date: Wed, 25 Nov 2026 21:08:35 +0100 Subject: [PATCH 5/7] Add end-to-end test --- tests/test_temporary_private_forks.py | 97 +++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 tests/test_temporary_private_forks.py diff --git a/tests/test_temporary_private_forks.py b/tests/test_temporary_private_forks.py new file mode 100644 index 0000000..010c9ee --- /dev/null +++ b/tests/test_temporary_private_forks.py @@ -0,0 +1,97 @@ +"""Tests for behavior of backups ran for temporary private forks.""" + +import json +from unittest.mock import patch +from urllib.error import HTTPError + +from github_backup import github_backup + + +def _repo(name, updated_at, pushed_at=None): + return { + "name": name, + "full_name": "owner/{0}".format(name), + "owner": {"login": "owner"}, + "clone_url": "https://github.com/owner/{0}.git".format(name), + "private": True, + "fork": False, + "has_issues": False, + "has_projects": False, + "has_downloads": False, + "has_wiki": False, + "has_pages": False, + "has_discussions": False, + "updated_at": updated_at, + "pushed_at": pushed_at, + } + + +# This is an end-to-end test of a full repository backup that's supposed to ensure that +# everything in the process can handle most of the REST API endpoints returning 404s +# without raising errors. +def test_temporary_private_fork_backup_handles_limited_api_endpoints_with_no_errors( + create_args, tmp_path, monkeypatch +): + args = create_args(include_everything=True, private=True) + repo_name = "repo-one-ghsa-01ab-34cd-56ef" + repositories = [_repo(repo_name, "2026-02-01T00:00:00Z")] + repo_cwd = tmp_path / "repositories" / repo_name + pull_file = repo_cwd / "pulls" / "1.json" + + expected_dirs = {"pulls"} + base_pr_data = {"number": 1, "updated_at": "2026-01-01T00:00:00Z"} + regular_comments = [{"id": 2, "body": "regular comment"}] + review_comments = [{"id": 3, "body": "review comment"}] + commits = [{"sha": "abc"}] + + def fake_retrieve_graphql_data(args, query, variables=None, log_context=None): + if query == github_backup.PULL_COMMENTS_QUERY: + return { + "repository": { + "pullRequest": { + "comments": { + "totalCount": 1, + "nodes": regular_comments, + "pageInfo": {"hasNextPage": False, "endCursor": None}, + }, + }, + }, + } + else: + raise AssertionError(f"request made with unknown query: {query}") + + def fake_retrieve_data( + passed_args, template, query_args=None, lazy=False, **kwargs + ): + def gen(): + if template.endswith("/pulls"): + yield base_pr_data + elif template.endswith("/pulls/1/comments"): + yield from review_comments + elif template.endswith("/pulls/1/commits"): + yield from commits + else: + # anything other than above should just be assumed to return 404 + raise HTTPError(template, 404, "Not Found", hdrs=None, fp=None) + + if lazy: + return gen() + return list(gen()) + + monkeypatch.setattr( + github_backup, "retrieve_graphql_data", fake_retrieve_graphql_data + ) + monkeypatch.setattr(github_backup, "retrieve_data", fake_retrieve_data) + + with patch("github_backup.github_backup.fetch_repository"): + github_backup.backup_repositories(args, tmp_path, repositories) + + actual_dirs = {p.name for p in repo_cwd.iterdir()} + assert expected_dirs == actual_dirs + + pr_data = json.loads(pull_file.read_text()) + for key in base_pr_data: + assert pr_data[key] == base_pr_data[key] + assert pr_data["comment_regular_data"] == regular_comments + assert pr_data["comment_data"] == review_comments + assert pr_data["commit_data"] == commits From 1d69f8baccc282544417661ec97728b8e0ce6c07 Mon Sep 17 00:00:00 2001 From: Jakub Kuczys Date: Wed, 25 Nov 2026 21:16:23 +0100 Subject: [PATCH 6/7] Avoid making empty dirs for labels, milestones, and releases --- github_backup/github_backup.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/github_backup/github_backup.py b/github_backup/github_backup.py index adcbfd6..e52de85 100644 --- a/github_backup/github_backup.py +++ b/github_backup/github_backup.py @@ -3325,7 +3325,6 @@ def backup_milestones(args, repo_cwd, repository, repos_template): return logger.info("Retrieving {0} milestones".format(repository["full_name"])) - mkdir_p(repo_cwd, milestone_cwd) template = "{0}/{1}/milestones".format(repos_template, repository["full_name"]) @@ -3339,6 +3338,8 @@ def backup_milestones(args, repo_cwd, repository, repos_template): return raise + mkdir_p(repo_cwd, milestone_cwd) + milestones = {} for milestone in _milestones: milestones[milestone["number"]] = milestone @@ -3453,10 +3454,8 @@ def backup_hooks(args, repo_cwd, repository, repos_template): def backup_releases(args, repo_cwd, repository, repos_template, include_assets=False): repository_fullname = repository["full_name"] - # give release files somewhere to live & log intent - release_cwd = os.path.join(repo_cwd, "releases") + # log intent logger.info("Retrieving {0} releases".format(repository_fullname)) - mkdir_p(repo_cwd, release_cwd) query_args = {} @@ -3469,6 +3468,10 @@ def backup_releases(args, repo_cwd, repository, repos_template, include_assets=F return raise + # give release files somewhere to live + release_cwd = os.path.join(repo_cwd, "releases") + mkdir_p(repo_cwd, release_cwd) + if args.skip_prerelease: releases = [r for r in releases if not r["prerelease"] and not r["draft"]] @@ -3686,9 +3689,9 @@ def _backup_data(args, name, template, output_file, output_directory): skip_existing = args.skip_existing if not skip_existing or not os.path.exists(output_file): logger.info("Retrieving {0} {1}".format(args.user, name)) - mkdir_p(output_directory) data = retrieve_data(args, template) + mkdir_p(output_directory) if json_dump_if_changed(data, output_file): logger.info("Saved {0} {1} to disk".format(len(data), name)) else: From 285c57c100736c3933f10f73587a0bcfcbc0aa10 Mon Sep 17 00:00:00 2001 From: Jakub Kuczys Date: Thu, 26 Nov 2026 19:57:48 +0100 Subject: [PATCH 7/7] Test GraphQL pagination in pull comments retrieval --- tests/test_temporary_private_forks.py | 61 ++++++++++++++++++++++----- 1 file changed, 50 insertions(+), 11 deletions(-) diff --git a/tests/test_temporary_private_forks.py b/tests/test_temporary_private_forks.py index 010c9ee..8c857af 100644 --- a/tests/test_temporary_private_forks.py +++ b/tests/test_temporary_private_forks.py @@ -26,6 +26,23 @@ def _repo(name, updated_at, pushed_at=None): } +def _pull_comments_page(comment_nodes, total_count, has_next=False): + return { + "repository": { + "pullRequest": { + "comments": { + "totalCount": total_count, + "nodes": comment_nodes, + "pageInfo": { + "hasNextPage": has_next, + "endCursor": "COMMENTS2" if has_next else None, + }, + }, + } + } + } + + # This is an end-to-end test of a full repository backup that's supposed to ensure that # everything in the process can handle most of the REST API endpoints returning 404s # without raising errors. @@ -46,17 +63,7 @@ def test_temporary_private_fork_backup_handles_limited_api_endpoints_with_no_err def fake_retrieve_graphql_data(args, query, variables=None, log_context=None): if query == github_backup.PULL_COMMENTS_QUERY: - return { - "repository": { - "pullRequest": { - "comments": { - "totalCount": 1, - "nodes": regular_comments, - "pageInfo": {"hasNextPage": False, "endCursor": None}, - }, - }, - }, - } + return _pull_comments_page(regular_comments, len(regular_comments)) else: raise AssertionError(f"request made with unknown query: {query}") @@ -95,3 +102,35 @@ def gen(): assert pr_data["comment_regular_data"] == regular_comments assert pr_data["comment_data"] == review_comments assert pr_data["commit_data"] == commits + + +def test_get_pull_comments_with_graphql_paginates(create_args): + args = create_args() + repository = {"full_name": "owner/repo"} + + comment_1 = {"id": "comment-1", "body": "first comment"} + comment_2 = {"id": "comment-2", "body": "second comment"} + comment_3 = {"id": "comment-3", "body": "third comment"} + total_count = 3 + + responses = [ + _pull_comments_page([comment_1, comment_2], total_count, has_next=True), + _pull_comments_page([comment_3], total_count, has_next=False), + ] + + with patch( + "github_backup.github_backup.retrieve_graphql_data", side_effect=responses + ) as mock_retrieve: + comment_data = github_backup.get_pull_comments_with_graphql( + args, repository, 42 + ) + + assert len(comment_data) == total_count + assert comment_data[0]["body"] == "first comment" + assert comment_data[1]["body"] == "second comment" + assert comment_data[2]["body"] == "third comment" + assert mock_retrieve.call_count == 2 + assert [call.kwargs["log_context"] for call in mock_retrieve.call_args_list] == [ + "pull request owner/repo#42 comments page 1", + "pull request owner/repo#42 comments page 2", + ]