feat: opt-in by sync.json + per-instance ULID + restic subpath
Reshapes the launcher integration around two ideas:
1. ONE global Prism PreLaunch/PostExit hook is enough for all
instances. Wire it once at Settings > Default > Custom commands:
python /opt/cloud-sync.pyz pull --pack-folder=$INST_MC_DIR
python /opt/cloud-sync.pyz push --pack-folder=$INST_MC_DIR
Instances WITHOUT .cloud-sync/sync.json are silent no-ops (rc=0,
no UI, no banner). The opt-in probe runs BEFORE the UI factory
so Prism's launch log stays clean for non-sync instances.
2. Per-instance opt-in via 'setup' / 'init' subcommands that mint a
fresh ULID-style instance_id + write sync.json (mode 644) and
token (mode 600). 'disable' removes sync.json; cloud data
untouched.
Restic URL gains an /<instance_id>/ subpath under the user's
namespace, so two Prism instances of the same Discord user no longer
share a snapshot timeline. --private-repos still gates on the first
path segment (the username); deeper segments are user-controlled,
so this works without server-side coordination. First-push-on-a-new-
instance probes via 'restic cat config' and 'init's the per-instance
repo if absent.
UI label resolution is runtime-only (NEVER stored in sync.json) so
the user renaming the Prism instance just propagates through on
next launch:
--instance-label > $INST_NAME > $INST_ID > instance_id[:8]
Schema bumps:
state.json schema: 1 -> 2, adds instance_id field. Schema-1 files
are treated as missing (existing test1 user re-pulls fresh).
sync.json schema: 1 (new file).
CLI rework:
pull / push no --url; load everything from sync.json
setup interactive: Qt login dialog for token; URL prompt
if --url omitted; falls back to stdin when headless
init non-interactive setup; for scripted callers
disable rm sync.json
Args dataclass: drops 'url', adds 'instance_label'. cli.parse() now
returns (cmd, Namespace); a separate args_from(ns) builds the Args
so each subcommand can pluck the bits it needs from the Namespace
without forcing a 'one Args fits all subcommands' shape.
73 tests green; pyz 75 KB.
Smoke-verified locally:
- pull/push on a folder without sync.json: silent rc=0, no banner
- init writes sync.json (644) + token (600) with correct contents
- disable removes sync.json, keeps token
- mint produces unique 26-char base32 instance_ids
- label resolution chain (flag > INST_NAME > INST_ID > prefix)
This commit is contained in:
+62
-28
@@ -1,63 +1,102 @@
|
||||
"""CLI parsing tests — argv → (subcommand, Args)."""
|
||||
"""CLI parsing tests — argv → (subcommand, Namespace) and → Args."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from cloud_sync.cli import Args, parse
|
||||
from cloud_sync.cli import Args, args_from, parse
|
||||
|
||||
|
||||
def test_parses_pull_with_required_url() -> None:
|
||||
cmd, args = parse(["pull", "--url=https://cloud.tm.center"])
|
||||
# ---- pull / push ----
|
||||
|
||||
|
||||
def test_parses_pull_without_url() -> None:
|
||||
"""url is sync.json's job now — pull/push don't take --url."""
|
||||
cmd, ns = parse(["pull"])
|
||||
assert cmd == "pull"
|
||||
args = args_from(ns)
|
||||
assert isinstance(args, Args)
|
||||
assert args.url == "https://cloud.tm.center"
|
||||
assert args.allow_download is True
|
||||
assert args.headless is False
|
||||
assert args.instance_label is None
|
||||
|
||||
|
||||
def test_default_token_file_under_pack_folder() -> None:
|
||||
_, args = parse(["pull", "--url=https://x", "--pack-folder=/tmp/inst"])
|
||||
_, ns = parse(["pull", "--pack-folder=/tmp/inst"])
|
||||
args = args_from(ns)
|
||||
assert args.token_file.as_posix().endswith(".cloud-sync/token")
|
||||
assert "/tmp/inst" in args.token_file.as_posix()
|
||||
|
||||
|
||||
def test_custom_token_file_overrides_default() -> None:
|
||||
_, args = parse(
|
||||
["pull", "--url=https://x", "--pack-folder=/tmp/inst",
|
||||
"--token-file=/etc/cloud-creds"]
|
||||
)
|
||||
_, ns = parse([
|
||||
"pull", "--pack-folder=/tmp/inst", "--token-file=/etc/cloud-creds",
|
||||
])
|
||||
args = args_from(ns)
|
||||
assert args.token_file.as_posix() == "/etc/cloud-creds"
|
||||
|
||||
|
||||
def test_inline_and_space_separated_both_work() -> None:
|
||||
_, a1 = parse(["pull", "--url=https://x", "--pack-folder=/srv"])
|
||||
_, a2 = parse(["pull", "--url", "https://x", "--pack-folder", "/srv"])
|
||||
assert a1.url == a2.url
|
||||
_, ns1 = parse(["pull", "--pack-folder=/srv"])
|
||||
_, ns2 = parse(["pull", "--pack-folder", "/srv"])
|
||||
a1, a2 = args_from(ns1), args_from(ns2)
|
||||
assert a1.pack_folder == a2.pack_folder
|
||||
|
||||
|
||||
def test_no_gui_flag() -> None:
|
||||
_, a = parse(["push", "--url=https://x", "-g"])
|
||||
assert a.headless is True
|
||||
_, b = parse(["push", "--url=https://x", "--no-gui"])
|
||||
assert b.headless is True
|
||||
_, a = parse(["push", "-g"])
|
||||
assert args_from(a).headless is True
|
||||
_, b = parse(["push", "--no-gui"])
|
||||
assert args_from(b).headless is True
|
||||
|
||||
|
||||
def test_no_download_flag() -> None:
|
||||
_, a = parse(["push", "--url=https://x", "--no-download"])
|
||||
assert a.allow_download is False
|
||||
_, ns = parse(["push", "--no-download"])
|
||||
assert args_from(ns).allow_download is False
|
||||
|
||||
|
||||
def test_restic_binary_override() -> None:
|
||||
_, a = parse(["push", "--url=https://x", "--restic-binary=/opt/restic"])
|
||||
_, ns = parse(["push", "--restic-binary=/opt/restic"])
|
||||
a = args_from(ns)
|
||||
assert a.restic_binary is not None
|
||||
assert a.restic_binary.as_posix() == "/opt/restic"
|
||||
|
||||
|
||||
def test_missing_url_exits() -> None:
|
||||
def test_instance_label_override() -> None:
|
||||
_, ns = parse(["pull", "--instance-label=Frazaserver 1.21.4"])
|
||||
assert args_from(ns).instance_label == "Frazaserver 1.21.4"
|
||||
|
||||
|
||||
def test_pack_folder_is_resolved_to_absolute() -> None:
|
||||
_, ns = parse(["pull", "--pack-folder=."])
|
||||
assert args_from(ns).pack_folder.is_absolute()
|
||||
|
||||
|
||||
# ---- setup / init / disable ----
|
||||
|
||||
|
||||
def test_setup_subcommand_accepts_optional_url() -> None:
|
||||
cmd, ns = parse(["setup", "--url=https://x"])
|
||||
assert cmd == "setup"
|
||||
assert ns.url == "https://x"
|
||||
|
||||
|
||||
def test_init_requires_url() -> None:
|
||||
with pytest.raises(SystemExit):
|
||||
parse(["pull"])
|
||||
parse(["init"])
|
||||
|
||||
|
||||
def test_init_accepts_url_and_token() -> None:
|
||||
cmd, ns = parse(["init", "--url=https://x", "--token=42:secret"])
|
||||
assert cmd == "init"
|
||||
assert ns.url == "https://x"
|
||||
assert ns.token == "42:secret"
|
||||
|
||||
|
||||
def test_disable_subcommand_parses() -> None:
|
||||
cmd, ns = parse(["disable", "--pack-folder=/tmp/x"])
|
||||
assert cmd == "disable"
|
||||
assert str(ns.pack_folder) == "/tmp/x"
|
||||
|
||||
|
||||
def test_missing_subcommand_exits() -> None:
|
||||
@@ -67,9 +106,4 @@ def test_missing_subcommand_exits() -> None:
|
||||
|
||||
def test_unknown_subcommand_exits() -> None:
|
||||
with pytest.raises(SystemExit):
|
||||
parse(["bogus", "--url=https://x"])
|
||||
|
||||
|
||||
def test_pack_folder_is_resolved_to_absolute() -> None:
|
||||
_, a = parse(["pull", "--url=https://x", "--pack-folder=."])
|
||||
assert a.pack_folder.is_absolute()
|
||||
parse(["bogus"])
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""sync.json read/write/mint + label resolution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cloud_sync import config as cfgmod
|
||||
|
||||
|
||||
# ---- mint / new_instance_id ----
|
||||
|
||||
|
||||
def test_new_instance_id_shape():
|
||||
iid = cfgmod.new_instance_id()
|
||||
assert len(iid) == 26
|
||||
# base32 alphabet (uppercase + 2-7), no padding
|
||||
assert re.fullmatch(r"[A-Z2-7]+", iid), iid
|
||||
|
||||
|
||||
def test_new_instance_id_uniqueness():
|
||||
ids = {cfgmod.new_instance_id() for _ in range(200)}
|
||||
assert len(ids) == 200 # collisions effectively impossible
|
||||
|
||||
|
||||
def test_mint_returns_filled_config():
|
||||
cfg = cfgmod.mint(url="https://x.test")
|
||||
assert cfg.url == "https://x.test"
|
||||
assert len(cfg.instance_id) == 26
|
||||
assert cfg.host_fingerprint # non-empty hex
|
||||
assert cfg.created_at.tzinfo is not None
|
||||
|
||||
|
||||
# ---- read / write / exists / delete ----
|
||||
|
||||
|
||||
def test_exists_false_when_missing(tmp_path: Path):
|
||||
assert cfgmod.exists(tmp_path) is False
|
||||
assert cfgmod.read(tmp_path) is None
|
||||
|
||||
|
||||
def test_write_then_read_roundtrip(tmp_path: Path):
|
||||
cfg = cfgmod.mint(url="https://x.test")
|
||||
cfgmod.write(tmp_path, cfg)
|
||||
assert cfgmod.exists(tmp_path) is True
|
||||
got = cfgmod.read(tmp_path)
|
||||
assert got is not None
|
||||
assert got.url == cfg.url
|
||||
assert got.instance_id == cfg.instance_id
|
||||
assert got.host_fingerprint == cfg.host_fingerprint
|
||||
|
||||
|
||||
def test_write_sets_mode_644(tmp_path: Path):
|
||||
"""sync.json is NOT a secret — it's the opt-in marker + (instance_id, url)
|
||||
pair. token is the secret (mode 600)."""
|
||||
cfg = cfgmod.mint(url="https://x.test")
|
||||
cfgmod.write(tmp_path, cfg)
|
||||
mode = cfgmod.config_path(tmp_path).stat().st_mode & 0o777
|
||||
assert mode == 0o644
|
||||
|
||||
|
||||
def test_delete_returns_true_when_existed(tmp_path: Path):
|
||||
cfgmod.write(tmp_path, cfgmod.mint("https://x"))
|
||||
assert cfgmod.delete(tmp_path) is True
|
||||
assert cfgmod.exists(tmp_path) is False
|
||||
|
||||
|
||||
def test_delete_returns_false_when_missing(tmp_path: Path):
|
||||
assert cfgmod.delete(tmp_path) is False
|
||||
|
||||
|
||||
def test_corrupt_json_returns_none(tmp_path: Path):
|
||||
cfg_path = cfgmod.config_path(tmp_path)
|
||||
cfg_path.parent.mkdir(parents=True)
|
||||
cfg_path.write_text("{not json")
|
||||
assert cfgmod.read(tmp_path) is None
|
||||
|
||||
|
||||
def test_wrong_schema_returns_none(tmp_path: Path):
|
||||
cfg_path = cfgmod.config_path(tmp_path)
|
||||
cfg_path.parent.mkdir(parents=True)
|
||||
cfg_path.write_text('{"schema": 999, "url": "x", "instance_id": "y", "created_at": "2026-01-01T00:00:00Z"}')
|
||||
assert cfgmod.read(tmp_path) is None
|
||||
|
||||
|
||||
# ---- resolve_label ----
|
||||
|
||||
|
||||
def test_label_flag_wins_over_env(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("INST_NAME", "from-env")
|
||||
assert cfgmod.resolve_label("from-flag", "ABCDEF") == "from-flag"
|
||||
|
||||
|
||||
def test_label_falls_back_to_inst_name(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("INST_NAME", "Frazaserver 1.21.4")
|
||||
monkeypatch.delenv("INST_ID", raising=False)
|
||||
assert cfgmod.resolve_label(None, "ABCDEF") == "Frazaserver 1.21.4"
|
||||
|
||||
|
||||
def test_label_falls_back_to_inst_id(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.delenv("INST_NAME", raising=False)
|
||||
monkeypatch.setenv("INST_ID", "26.1.2")
|
||||
assert cfgmod.resolve_label(None, "ABCDEF") == "26.1.2"
|
||||
|
||||
|
||||
def test_label_last_resort_uses_instance_id_prefix(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.delenv("INST_NAME", raising=False)
|
||||
monkeypatch.delenv("INST_ID", raising=False)
|
||||
assert cfgmod.resolve_label(None, "ABCDEFGHIJKLMN") == "ABCDEFGH"
|
||||
|
||||
|
||||
def test_label_blank_flag_does_not_override(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Empty string from --instance-label="" should not win over env."""
|
||||
monkeypatch.setenv("INST_NAME", "env-name")
|
||||
assert cfgmod.resolve_label("", "ABCDEF") == "env-name"
|
||||
+21
-14
@@ -7,45 +7,52 @@ import pytest
|
||||
from cloud_sync.sync import _restic_env, _restic_repo
|
||||
|
||||
|
||||
_IID = "01H7XJ4WB2KD5MNCYV8RQ6PTAZ"
|
||||
|
||||
|
||||
def test_basic_http_url():
|
||||
repo = _restic_repo("http://cloud.tm.center", "12345", "secretpw")
|
||||
assert repo == "rest:http://12345:secretpw@cloud.tm.center/12345/"
|
||||
repo = _restic_repo("http://cloud.tm.center", "12345", "secretpw", _IID)
|
||||
assert repo == f"rest:http://12345:secretpw@cloud.tm.center/12345/{_IID}/"
|
||||
|
||||
|
||||
def test_https_url():
|
||||
repo = _restic_repo("https://cloud.tm.center", "12345", "pw")
|
||||
assert repo == "rest:https://12345:pw@cloud.tm.center/12345/"
|
||||
repo = _restic_repo("https://cloud.tm.center", "12345", "pw", _IID)
|
||||
assert repo == f"rest:https://12345:pw@cloud.tm.center/12345/{_IID}/"
|
||||
|
||||
|
||||
def test_trailing_slash_stripped():
|
||||
repo = _restic_repo("https://cloud.tm.center/", "12345", "pw")
|
||||
assert repo == "rest:https://12345:pw@cloud.tm.center/12345/"
|
||||
repo = _restic_repo("https://cloud.tm.center/", "12345", "pw", _IID)
|
||||
assert repo == f"rest:https://12345:pw@cloud.tm.center/12345/{_IID}/"
|
||||
|
||||
|
||||
def test_url_with_port():
|
||||
repo = _restic_repo("http://127.0.0.1:8002", "alice", "pw")
|
||||
assert repo == "rest:http://alice:pw@127.0.0.1:8002/alice/"
|
||||
repo = _restic_repo("http://127.0.0.1:8002", "alice", "pw", _IID)
|
||||
assert repo == f"rest:http://alice:pw@127.0.0.1:8002/alice/{_IID}/"
|
||||
|
||||
|
||||
def test_rest_prefix_stripped_if_supplied():
|
||||
repo = _restic_repo("rest:http://x.test", "u", "p")
|
||||
assert repo == "rest:http://u:p@x.test/u/"
|
||||
repo = _restic_repo("rest:http://x.test", "u", "p", _IID)
|
||||
assert repo == f"rest:http://u:p@x.test/u/{_IID}/"
|
||||
|
||||
|
||||
def test_password_with_special_chars_encoded():
|
||||
repo = _restic_repo("http://x.test", "u", "p@ss/word?!&")
|
||||
# URL-encoded form of "p@ss/word?!&"
|
||||
repo = _restic_repo("http://x.test", "u", "p@ss/word?!&", _IID)
|
||||
assert "p%40ss%2Fword%3F%21%26@x.test" in repo
|
||||
|
||||
|
||||
def test_user_with_special_chars_encoded():
|
||||
repo = _restic_repo("http://x.test", "u/with@chars", "pw")
|
||||
repo = _restic_repo("http://x.test", "u/with@chars", "pw", _IID)
|
||||
assert "u%2Fwith%40chars" in repo
|
||||
|
||||
|
||||
def test_instance_id_in_url_path():
|
||||
repo = _restic_repo("http://x.test", "u", "p", _IID)
|
||||
assert repo.endswith(f"/u/{_IID}/")
|
||||
|
||||
|
||||
def test_missing_scheme_rejected():
|
||||
with pytest.raises(ValueError):
|
||||
_restic_repo("cloud.tm.center", "u", "p")
|
||||
_restic_repo("cloud.tm.center", "u", "p", _IID)
|
||||
|
||||
|
||||
def test_env_does_not_contain_password():
|
||||
|
||||
+29
-4
@@ -27,14 +27,22 @@ def test_read_missing_returns_none(tmp_path: Path):
|
||||
assert statemod.read(tmp_path) is None
|
||||
|
||||
|
||||
_IID = "01H7XJ4WB2KD5MNCYV8RQ6PTAZ"
|
||||
|
||||
|
||||
def test_write_then_read_roundtrip(tmp_path: Path):
|
||||
dt = datetime(2026, 6, 5, 12, 34, 56, tzinfo=timezone.utc)
|
||||
statemod.write(
|
||||
tmp_path,
|
||||
statemod.State(last_pulled_snapshot_id="abc123", last_pulled_at=dt),
|
||||
statemod.State(
|
||||
instance_id=_IID,
|
||||
last_pulled_snapshot_id="abc123",
|
||||
last_pulled_at=dt,
|
||||
),
|
||||
)
|
||||
got = statemod.read(tmp_path)
|
||||
assert got is not None
|
||||
assert got.instance_id == _IID
|
||||
assert got.last_pulled_snapshot_id == "abc123"
|
||||
assert got.last_pulled_at == dt
|
||||
|
||||
@@ -43,6 +51,7 @@ def test_write_sets_mode_600(tmp_path: Path):
|
||||
statemod.write(
|
||||
tmp_path,
|
||||
statemod.State(
|
||||
instance_id=_IID,
|
||||
last_pulled_snapshot_id="x",
|
||||
last_pulled_at=datetime.now(timezone.utc),
|
||||
),
|
||||
@@ -56,6 +65,7 @@ def test_clear_idempotent(tmp_path: Path):
|
||||
statemod.write(
|
||||
tmp_path,
|
||||
statemod.State(
|
||||
instance_id=_IID,
|
||||
last_pulled_snapshot_id="x",
|
||||
last_pulled_at=datetime.now(timezone.utc),
|
||||
),
|
||||
@@ -68,9 +78,24 @@ def test_clear_idempotent(tmp_path: Path):
|
||||
def test_wrong_schema_returns_none(tmp_path: Path):
|
||||
p = tmp_path / ".cloud-sync" / "state.json"
|
||||
p.parent.mkdir(parents=True)
|
||||
p.write_text(
|
||||
json.dumps({"schema": 999, "last_pulled_snapshot_id": "x", "last_pulled_at": "2026-01-01T00:00:00Z"})
|
||||
)
|
||||
p.write_text(json.dumps({
|
||||
"schema": 999, "instance_id": _IID,
|
||||
"last_pulled_snapshot_id": "x",
|
||||
"last_pulled_at": "2026-01-01T00:00:00Z",
|
||||
}))
|
||||
assert statemod.read(tmp_path) is None
|
||||
|
||||
|
||||
def test_schema_v1_returns_none(tmp_path: Path):
|
||||
"""Old schema-1 state.json (no instance_id) is treated as missing on
|
||||
read. Triggers a fresh sync flow after the schema bump migration."""
|
||||
p = tmp_path / ".cloud-sync" / "state.json"
|
||||
p.parent.mkdir(parents=True)
|
||||
p.write_text(json.dumps({
|
||||
"schema": 1,
|
||||
"last_pulled_snapshot_id": "x",
|
||||
"last_pulled_at": "2026-01-01T00:00:00Z",
|
||||
}))
|
||||
assert statemod.read(tmp_path) is None
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user