mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 11:46:30 +01:00
GitHubClient: add canAccessRepo() + deleteFile() (v0.3.0)
Make the shared client a superset of what todo's and diet_guard-app's local GitHubClient copies provide, so every app can drop its copy and sync through one client. canAccessRepo() is a lightweight connection test (bare repo GET, never throws); deleteFile() resolves the file's own sha and no-ops when absent. Mirrored on the Dart and Python sides. 90 Dart + 78 Python tests, 100%. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019KwUCPESvE5CjCtmUFz8xQ
This commit is contained in:
parent
d69598880a
commit
5480e72335
@ -192,3 +192,41 @@ class GitHubSyncClient:
|
|||||||
for item in data
|
for item in data
|
||||||
if isinstance(item, dict) and isinstance(item.get("name"), str)
|
if isinstance(item, dict) and isinstance(item.get("name"), str)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def can_access_repo(self) -> bool:
|
||||||
|
"""Return whether the token can read this repo (a connection test).
|
||||||
|
|
||||||
|
Hits the bare repo endpoint, so it succeeds even before any file has
|
||||||
|
been pushed. Never raises -- a network failure or missing repo is
|
||||||
|
reported as ``False``.
|
||||||
|
"""
|
||||||
|
return self._repo_exists()
|
||||||
|
|
||||||
|
def delete_file(self, path: str, *, message: str = "crdt_sync: delete") -> None:
|
||||||
|
"""Delete the file at ``path``, resolving its current sha itself.
|
||||||
|
|
||||||
|
A no-op if ``path`` does not exist, so a repeated cleanup is safe.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: A repo-relative file path.
|
||||||
|
message: The commit message for the deletion.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
GitHubSyncError: On any non-2xx response or network error.
|
||||||
|
"""
|
||||||
|
sha = self._existing_sha(path)
|
||||||
|
if sha is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
response = requests.delete(
|
||||||
|
self._contents_url(path),
|
||||||
|
headers=self._headers,
|
||||||
|
json={"message": message, "sha": sha},
|
||||||
|
timeout=self._timeout_seconds,
|
||||||
|
)
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
msg = f"network error deleting {path}"
|
||||||
|
raise GitHubSyncError(msg) from exc
|
||||||
|
if not response.ok:
|
||||||
|
msg = f"DELETE {path} failed: {response.status_code}"
|
||||||
|
raise GitHubSyncError(msg)
|
||||||
|
|||||||
@ -168,3 +168,55 @@ class TestPutFileText:
|
|||||||
pytest.raises(GitHubSyncError),
|
pytest.raises(GitHubSyncError),
|
||||||
):
|
):
|
||||||
_client().put_file_text("devices/pc/log.json", "{}", message="m")
|
_client().put_file_text("devices/pc/log.json", "{}", message="m")
|
||||||
|
|
||||||
|
|
||||||
|
class TestCanAccessRepo:
|
||||||
|
def test_true_when_repo_endpoint_ok(self) -> None:
|
||||||
|
with _patch_get(_response(200)):
|
||||||
|
assert _client().can_access_repo() is True
|
||||||
|
|
||||||
|
def test_false_when_repo_is_missing(self) -> None:
|
||||||
|
with _patch_get(_response(404)):
|
||||||
|
assert _client().can_access_repo() is False
|
||||||
|
|
||||||
|
def test_false_on_a_network_error(self) -> None:
|
||||||
|
with _patch_get_raises():
|
||||||
|
assert _client().can_access_repo() is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestDeleteFile:
|
||||||
|
def test_deletes_an_existing_file_resolving_its_own_sha(self) -> None:
|
||||||
|
with (
|
||||||
|
_patch_get(_response(200, {"sha": "abc123"})),
|
||||||
|
patch.object(_github.requests, "delete", return_value=_response(200)),
|
||||||
|
):
|
||||||
|
_client().delete_file("devices/pc/log.json")
|
||||||
|
|
||||||
|
def test_is_a_no_op_when_the_file_is_absent(self) -> None:
|
||||||
|
# sha GET 404, repo-exists GET 200 -> None sha -> no DELETE sent.
|
||||||
|
with (
|
||||||
|
_patch_get(_response(404), _response(200)),
|
||||||
|
patch.object(_github.requests, "delete") as mock_delete,
|
||||||
|
):
|
||||||
|
_client().delete_file("devices/pc/gone.json")
|
||||||
|
mock_delete.assert_not_called()
|
||||||
|
|
||||||
|
def test_raises_on_a_delete_non_2xx_response(self) -> None:
|
||||||
|
with (
|
||||||
|
_patch_get(_response(200, {"sha": "abc123"})),
|
||||||
|
patch.object(_github.requests, "delete", return_value=_response(500)),
|
||||||
|
pytest.raises(GitHubSyncError),
|
||||||
|
):
|
||||||
|
_client().delete_file("devices/pc/log.json")
|
||||||
|
|
||||||
|
def test_raises_on_a_delete_network_error(self) -> None:
|
||||||
|
with (
|
||||||
|
_patch_get(_response(200, {"sha": "abc123"})),
|
||||||
|
patch.object(
|
||||||
|
_github.requests,
|
||||||
|
"delete",
|
||||||
|
side_effect=requests.ConnectionError("offline"),
|
||||||
|
),
|
||||||
|
pytest.raises(GitHubSyncError),
|
||||||
|
):
|
||||||
|
_client().delete_file("devices/pc/log.json")
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "crdt-sync"
|
name = "crdt-sync"
|
||||||
version = "0.2.0"
|
version = "0.3.0"
|
||||||
description = "Shared CRDT merge scheme + GitHub-Contents-API sync transport for cross-device apps"
|
description = "Shared CRDT merge scheme + GitHub-Contents-API sync transport for cross-device apps"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
dependencies = ["requests"]
|
dependencies = ["requests"]
|
||||||
|
|||||||
@ -167,5 +167,35 @@ class GitHubClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns whether the configured token can read this repo.
|
||||||
|
///
|
||||||
|
/// A lightweight connection test for a settings "Test connection" button: it
|
||||||
|
/// hits the bare repo endpoint, so it succeeds even before any file has been
|
||||||
|
/// pushed. Never throws -- a network failure or missing repo returns false.
|
||||||
|
Future<bool> canAccessRepo() => _repoExists();
|
||||||
|
|
||||||
|
/// Deletes the file at [path], resolving its current sha itself so callers
|
||||||
|
/// don't have to track it. A no-op if [path] does not exist.
|
||||||
|
Future<void> deleteFile(
|
||||||
|
String path, {
|
||||||
|
String message = 'crdt_sync: delete',
|
||||||
|
}) async {
|
||||||
|
final sha = await _existingSha(path);
|
||||||
|
if (sha == null) return;
|
||||||
|
late final http.Response res;
|
||||||
|
try {
|
||||||
|
res = await _http.delete(
|
||||||
|
_contentsUri(path),
|
||||||
|
headers: _headers,
|
||||||
|
body: jsonEncode({'message': message, 'sha': sha}),
|
||||||
|
);
|
||||||
|
} on http.ClientException catch (exc) {
|
||||||
|
throw GitHubSyncError('network error deleting $path: $exc');
|
||||||
|
}
|
||||||
|
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||||
|
throw GitHubSyncError('DELETE $path failed: ${res.statusCode}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void close() => _http.close();
|
void close() => _http.close();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,7 +2,7 @@ name: crdt_sync
|
|||||||
description: >-
|
description: >-
|
||||||
Shared CRDT merge scheme + GitHub-Contents-API sync transport for
|
Shared CRDT merge scheme + GitHub-Contents-API sync transport for
|
||||||
cross-device apps. Pure Dart, no Flutter dependency.
|
cross-device apps. Pure Dart, no Flutter dependency.
|
||||||
version: 0.2.0
|
version: 0.3.0
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
|
|||||||
@ -19,6 +19,8 @@ GitHubClient _client(
|
|||||||
List<Object> getResponses, {
|
List<Object> getResponses, {
|
||||||
http.Response? putResponse,
|
http.Response? putResponse,
|
||||||
Object? putError,
|
Object? putError,
|
||||||
|
http.Response? deleteResponse,
|
||||||
|
Object? deleteError,
|
||||||
}) {
|
}) {
|
||||||
var getIndex = 0;
|
var getIndex = 0;
|
||||||
final mock = http_testing.MockClient((request) async {
|
final mock = http_testing.MockClient((request) async {
|
||||||
@ -34,6 +36,10 @@ GitHubClient _client(
|
|||||||
if (putError != null) throw putError;
|
if (putError != null) throw putError;
|
||||||
return putResponse!;
|
return putResponse!;
|
||||||
}
|
}
|
||||||
|
if (request.method == 'DELETE') {
|
||||||
|
if (deleteError != null) throw deleteError;
|
||||||
|
return deleteResponse!;
|
||||||
|
}
|
||||||
throw UnsupportedError('unexpected method ${request.method}');
|
throw UnsupportedError('unexpected method ${request.method}');
|
||||||
});
|
});
|
||||||
return GitHubClient(
|
return GitHubClient(
|
||||||
@ -192,4 +198,59 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
group('canAccessRepo', () {
|
||||||
|
test('is true when the repo endpoint returns 2xx', () async {
|
||||||
|
expect(await _client([_response(200)]).canAccessRepo(), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false when the repo is missing (404)', () async {
|
||||||
|
expect(await _client([_response(404)]).canAccessRepo(), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false on a network error', () async {
|
||||||
|
expect(await _client([_networkError]).canAccessRepo(), isFalse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('deleteFile', () {
|
||||||
|
test('deletes an existing file (resolves its own sha)', () async {
|
||||||
|
final client = _client(
|
||||||
|
[_response(200, {'sha': 'abc123'})],
|
||||||
|
deleteResponse: _response(200),
|
||||||
|
);
|
||||||
|
await expectLater(client.deleteFile('devices/pc/log.json'), completes);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is a no-op when the file does not exist', () async {
|
||||||
|
// sha lookup 404s, repo-exists check 200s -> null sha -> no DELETE sent.
|
||||||
|
final client = _client([
|
||||||
|
_response(404),
|
||||||
|
_response(200),
|
||||||
|
], deleteError: StateError('DELETE must not be called'));
|
||||||
|
await expectLater(client.deleteFile('devices/pc/gone.json'), completes);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws GitHubSyncError on a delete non-2xx response', () async {
|
||||||
|
final client = _client(
|
||||||
|
[_response(200, {'sha': 'abc123'})],
|
||||||
|
deleteResponse: _response(500),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
() => client.deleteFile('devices/pc/log.json'),
|
||||||
|
throwsA(isA<GitHubSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws GitHubSyncError on a delete network exception', () async {
|
||||||
|
final client = _client(
|
||||||
|
[_response(200, {'sha': 'abc123'})],
|
||||||
|
deleteError: http.ClientException('offline'),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
() => client.deleteFile('devices/pc/log.json'),
|
||||||
|
throwsA(isA<GitHubSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user