Skip to content

Commit 2aa56ab

Browse files
authored
✨ Add a command to keep the backup up-to-date with the API (#12)
1 parent dba9ad9 commit 2aa56ab

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/gitmojis/cli/commands.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import json
2+
from dataclasses import asdict
3+
4+
import click
5+
6+
from gitmojis import defaults
7+
8+
9+
@click.command()
10+
@click.pass_context
11+
def sync(context: click.Context) -> None:
12+
"""Synchronize the backup file with the current state of the API."""
13+
# Get the `Guide` object from the command's context
14+
guide = context.obj["guide"]
15+
16+
# Covert the `Guide` instance from context to a format defined by the API schema
17+
gitmojis_json = list(map(asdict, guide))
18+
19+
with defaults.GITMOJI_API_PATH.open("w", encoding="UTF-8") as f:
20+
# Dump the Gitmoji data to the backup file
21+
json.dump(gitmojis_json, f, ensure_ascii=False, indent=2)
22+
23+
# Append a newline to avoid the `end-of-file-fixer` Pre-commit hook error
24+
f.write("\n")

tests/test_cli.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import sys
33

44
import click
5+
import requests
56

67
from gitmojis.cli import commands as commands_module
78
from gitmojis.cli import get_commands, gitmojis_cli
@@ -45,3 +46,19 @@ def command(context):
4546
result = cli_runner.invoke(gitmojis_cli, "command")
4647

4748
assert result.exit_code == 0
49+
50+
51+
def test_sync_command_dumps_api_data_to_backup_file(tmp_path, mocker, cli_runner):
52+
# Mock the backup file as empty file
53+
gitmoji_api_path = tmp_path / "gitmojis.json"
54+
mocker.patch("gitmojis.defaults.GITMOJI_API_PATH", gitmoji_api_path)
55+
56+
# Mock response
57+
response = mocker.Mock(spec_set=requests.Response)
58+
response.json.return_value = {"gitmojis": []}
59+
mocker.patch("requests.get", return_value=response)
60+
61+
# Run command
62+
cli_runner.invoke(gitmojis_cli, ["sync"])
63+
64+
assert gitmoji_api_path.read_text(encoding="UTF-8") == "[]\n"

0 commit comments

Comments
 (0)