Skip to content

Commit 7f204b8

Browse files
committed
Fix --incremental-by-files skipping updated items east of UTC
The modification time of a saved issue, pull request or discussion was formatted in local time but labelled UTC, then compared with GitHub's UTC updated_at. East of UTC, items updated within the offset after they were saved were skipped and their changes missed; west of UTC, unchanged items were fetched again. The checkpoint time used when a repository has no updated_at or pushed_at had the same local-time mistake.
1 parent 839aa35 commit 7f204b8

2 files changed

Lines changed: 141 additions & 5 deletions

File tree

‎github_backup/github_backup.py‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import time
2121
import traceback
2222
from collections.abc import Generator
23-
from datetime import datetime
23+
from datetime import datetime, timezone
2424
from http.client import IncompleteRead
2525
from urllib.error import HTTPError, URLError
2626
from urllib.parse import urlencode, urlparse
@@ -2004,7 +2004,7 @@ def get_repository_checkpoint_time(repository):
20042004
if timestamps:
20052005
return max(timestamps)
20062006

2007-
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.localtime())
2007+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
20082008

20092009

20102010
def resource_backup_exists(resource_cwd):
@@ -2525,7 +2525,9 @@ def backup_discussions(args, repo_cwd, repository):
25252525

25262526
if args.incremental_by_files and os.path.isfile(discussion_file):
25272527
modified = os.path.getmtime(discussion_file)
2528-
modified = datetime.fromtimestamp(modified).strftime("%Y-%m-%dT%H:%M:%SZ")
2528+
modified = datetime.fromtimestamp(modified, timezone.utc).strftime(
2529+
"%Y-%m-%dT%H:%M:%SZ"
2530+
)
25292531
if modified > summary["updatedAt"]:
25302532
logger.info(
25312533
"Skipping discussion {0} because it wasn't modified since last backup".format(
@@ -2805,7 +2807,9 @@ def backup_issues(args, repo_cwd, repository, repos_template):
28052807
and number not in stale_timelines
28062808
):
28072809
modified = os.path.getmtime(issue_file)
2808-
modified = datetime.fromtimestamp(modified).strftime("%Y-%m-%dT%H:%M:%SZ")
2810+
modified = datetime.fromtimestamp(modified, timezone.utc).strftime(
2811+
"%Y-%m-%dT%H:%M:%SZ"
2812+
)
28092813
if modified > issue["updated_at"]:
28102814
logger.info(
28112815
"Skipping issue {0} because it wasn't modified since last backup".format(
@@ -3006,7 +3010,9 @@ def pull_is_due_for_repository_checkpoint(pull):
30063010

30073011
if args.incremental_by_files and os.path.isfile(pull_file):
30083012
modified = os.path.getmtime(pull_file)
3009-
modified = datetime.fromtimestamp(modified).strftime("%Y-%m-%dT%H:%M:%SZ")
3013+
modified = datetime.fromtimestamp(modified, timezone.utc).strftime(
3014+
"%Y-%m-%dT%H:%M:%SZ"
3015+
)
30103016
if modified > pull["updated_at"] and not needs_review_backfill:
30113017
logger.info(
30123018
"Skipping pull request {0} because it wasn't modified since last backup".format(

‎tests/test_incremental_by_files.py‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
"""Tests for --incremental-by-files timestamp comparison.
2+
3+
A saved file is skipped when its modification time is newer than the item's
4+
``updated_at``. GitHub's timestamps are UTC, so the file's modification time
5+
must be compared in UTC too, whatever the local time zone is.
6+
"""
7+
8+
import calendar
9+
import json
10+
import os
11+
import time
12+
13+
import pytest
14+
15+
from github_backup import github_backup
16+
17+
UPDATED_AT = "2026-07-01T12:00:00Z"
18+
19+
20+
@pytest.fixture
21+
def east_of_utc(monkeypatch):
22+
"""Run the test with the local time zone at UTC+10 (no daylight saving)."""
23+
monkeypatch.setenv("TZ", "Etc/GMT-10")
24+
time.tzset()
25+
yield
26+
monkeypatch.undo()
27+
time.tzset()
28+
29+
30+
def _stored(path, number, written_at):
31+
"""Save an item file whose modification time is ``written_at`` (UTC)."""
32+
path.mkdir(parents=True, exist_ok=True)
33+
item_file = path / "{0}.json".format(number)
34+
item_file.write_text(json.dumps({"number": number, "title": "stored"}))
35+
mtime = calendar.timegm(time.strptime(written_at, "%Y-%m-%dT%H:%M:%SZ"))
36+
os.utime(item_file, (mtime, mtime))
37+
return item_file
38+
39+
40+
def _fake_retrieve(items):
41+
def _retrieve(args, template, query_args=None, **kwargs):
42+
return items if template.endswith(("/issues", "/pulls")) else []
43+
44+
return _retrieve
45+
46+
47+
@pytest.mark.parametrize(
48+
"written_at, refetched",
49+
[
50+
("2026-07-01T10:00:00Z", True), # updated 2 hours after it was saved
51+
("2026-07-01T14:00:00Z", False), # saved 2 hours after the update
52+
],
53+
)
54+
def test_issue_skip_compares_in_utc(
55+
create_args, tmp_path, monkeypatch, east_of_utc, written_at, refetched
56+
):
57+
issue_file = _stored(tmp_path / "issues", 1, written_at)
58+
issue = {"number": 1, "title": "updated", "updated_at": UPDATED_AT}
59+
monkeypatch.setattr(github_backup, "retrieve_data", _fake_retrieve([issue]))
60+
args = create_args(include_issues=True, incremental_by_files=True, since=None)
61+
62+
github_backup.backup_issues(
63+
args, str(tmp_path), {"full_name": "owner/repo"}, "https://api.github.com/repos"
64+
)
65+
66+
title = json.loads(issue_file.read_text())["title"]
67+
assert title == ("updated" if refetched else "stored")
68+
69+
70+
@pytest.mark.parametrize(
71+
"written_at, refetched",
72+
[
73+
("2026-07-01T10:00:00Z", True),
74+
("2026-07-01T14:00:00Z", False),
75+
],
76+
)
77+
def test_pull_skip_compares_in_utc(
78+
create_args, tmp_path, monkeypatch, east_of_utc, written_at, refetched
79+
):
80+
pull_file = _stored(tmp_path / "pulls", 1, written_at)
81+
pull = {"number": 1, "title": "updated", "updated_at": UPDATED_AT}
82+
monkeypatch.setattr(github_backup, "retrieve_data", _fake_retrieve([pull]))
83+
args = create_args(include_pulls=True, incremental_by_files=True, since=None)
84+
85+
github_backup.backup_pulls(
86+
args, str(tmp_path), {"full_name": "owner/repo"}, "https://api.github.com/repos"
87+
)
88+
89+
title = json.loads(pull_file.read_text())["title"]
90+
assert title == ("updated" if refetched else "stored")
91+
92+
93+
@pytest.mark.parametrize(
94+
"written_at, refetched",
95+
[
96+
("2026-07-01T10:00:00Z", True),
97+
("2026-07-01T14:00:00Z", False),
98+
],
99+
)
100+
def test_discussion_skip_compares_in_utc(
101+
create_args, tmp_path, monkeypatch, east_of_utc, written_at, refetched
102+
):
103+
discussion_file = _stored(tmp_path / "discussions", 1, written_at)
104+
summary = {"number": 1, "updatedAt": UPDATED_AT}
105+
monkeypatch.setattr(
106+
github_backup,
107+
"retrieve_discussion_summaries",
108+
lambda args, repository, since=None: ([summary], UPDATED_AT, True, 1),
109+
)
110+
monkeypatch.setattr(
111+
github_backup,
112+
"retrieve_discussion",
113+
lambda args, repository, number: {"number": number, "title": "updated"},
114+
)
115+
args = create_args(
116+
include_discussions=True, incremental_by_files=True, token_classic="ghp_test"
117+
)
118+
119+
github_backup.backup_discussions(args, str(tmp_path), {"full_name": "owner/repo"})
120+
121+
title = json.loads(discussion_file.read_text())["title"]
122+
assert title == ("updated" if refetched else "stored")
123+
124+
125+
def test_checkpoint_fallback_time_is_utc(east_of_utc):
126+
before = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
127+
checkpoint = github_backup.get_repository_checkpoint_time({})
128+
after = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
129+
130+
assert before <= checkpoint <= after

0 commit comments

Comments
 (0)