python-dbsync 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dbsync/gitops.py ADDED
@@ -0,0 +1,170 @@
1
+ """Git helpers. `main` = working branch (local folder), `dropbox` = mirror of remote,
2
+ kept in a separate worktree so the user's working tree is only changed by merges."""
3
+ import os
4
+ import subprocess
5
+
6
+ # core.autocrlf=false: git must store and check out bytes exactly as they are. Git for
7
+ # Windows ships core.autocrlf=true system-wide, which rewrote \n to \r\n on checkout and made
8
+ # every synced file look locally changed.
9
+ IDENT = ["-c", "user.name=dbsync", "-c", "user.email=dbsync@localhost", "-c", "core.autocrlf=false"]
10
+
11
+
12
+ class GitError(Exception):
13
+ pass
14
+
15
+
16
+ def git(repo, *args, check=True, input=None):
17
+ r = subprocess.run(["git", "--literal-pathspecs", "-C", str(repo), *IDENT, *args], capture_output=True, text=True,
18
+ input=input)
19
+ if check and r.returncode != 0:
20
+ raise GitError(f"git {' '.join(args)} failed: {r.stderr.strip() or r.stdout.strip()}")
21
+ return r
22
+
23
+
24
+ def git_bytes(repo, *args):
25
+ """Like git(), but stdout as raw bytes: no newline translation, no decoding (file contents)."""
26
+ r = subprocess.run(["git", "--literal-pathspecs", "-C", str(repo), *IDENT, *args], capture_output=True)
27
+ return r
28
+
29
+
30
+ def is_repo(path):
31
+ return os.path.isdir(os.path.join(path, ".git"))
32
+
33
+
34
+ def branch_exists(repo, name):
35
+ return git(repo, "rev-parse", "-q", "--verify", f"refs/heads/{name}", check=False).returncode == 0
36
+
37
+
38
+ def setup_repo(repo, worktree, exclude_text, main="main", mirror="dropbox"):
39
+ """Idempotent: repo with `main` + `mirror` branches and a worktree for `mirror`."""
40
+ os.makedirs(repo, exist_ok=True)
41
+ if not is_repo(repo):
42
+ git(repo, "init", "-q", "-b", main)
43
+ # In the repo's own config too, so a person resolving a conflict with plain git gets
44
+ # byte-exact files as well (Git for Windows defaults autocrlf=true).
45
+ git(repo, "config", "core.autocrlf", "false")
46
+ # git keeps a full compressed copy of a file for every commit until it packs them; a chat file that grows all
47
+ # day would pile up. A low gc.auto makes the automatic `git gc --auto` after commits pack (delta) them soon.
48
+ git(repo, "config", "gc.auto", "100")
49
+ if not git(repo, "rev-parse", "-q", "--verify", "HEAD", check=False).returncode == 0:
50
+ git(repo, "commit", "-q", "--allow-empty", "-m", "dbsync: initial empty commit")
51
+ if not branch_exists(repo, main):
52
+ raise GitError(f"repo {repo} has no '{main}' branch")
53
+ if not branch_exists(repo, mirror):
54
+ git(repo, "branch", mirror, main)
55
+ # Our ignore rules for convenience (git status); dbsync stages files explicitly with -f,
56
+ # so .env is tracked even though the global gitignore excludes it.
57
+ info = os.path.join(repo, ".git", "info")
58
+ os.makedirs(info, exist_ok=True)
59
+ with open(os.path.join(info, "exclude"), "w") as f:
60
+ f.write("# managed by dbsync\n" + exclude_text + "!.env\n")
61
+ git(repo, "worktree", "prune")
62
+ if not os.path.isdir(worktree):
63
+ git(repo, "worktree", "add", "-q", worktree, mirror)
64
+
65
+
66
+ def current_branch(repo):
67
+ return git(repo, "rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
68
+
69
+
70
+ def merge_in_progress(repo):
71
+ return git(repo, "rev-parse", "-q", "--verify", "MERGE_HEAD", check=False).returncode == 0
72
+
73
+
74
+ def unmerged_files(repo):
75
+ out = git(repo, "diff", "--name-only", "--diff-filter=U").stdout
76
+ return [l for l in out.splitlines() if l]
77
+
78
+
79
+ def stage_and_commit(path, files, message):
80
+ """Stage exactly `files` (forced, so .env is included) plus tracked changes/deletions.
81
+ Returns True if a commit was made."""
82
+ if files:
83
+ git(path, "add", "-f", "--pathspec-from-file=-", "--pathspec-file-nul",
84
+ input="\0".join(files))
85
+ git(path, "add", "-u")
86
+ if git(path, "diff", "--cached", "--quiet", check=False).returncode == 0:
87
+ return False
88
+ git(path, "commit", "-q", "--no-verify", "-m", message)
89
+ return True
90
+
91
+
92
+ def matches_any(rel, patterns):
93
+ """True if repo-relative path `rel` matches one of the glob `patterns`
94
+ ("logs/**" = everything under logs/, "*.csv" = csv files at any depth)."""
95
+ from fnmatch import fnmatchcase
96
+ for p in patterns or ():
97
+ if p.endswith("/**") and (rel == p[:-3] or rel.startswith(p[:-2])):
98
+ return True
99
+ if fnmatchcase(rel, p) or ("/" not in p and fnmatchcase(rel.rsplit("/", 1)[-1], p)):
100
+ return True
101
+ return False
102
+
103
+
104
+ def _resolve_ours(repo, rel):
105
+ """Resolve one conflicted file, keeping our side for conflicting hunks (as -X ours
106
+ would) and the other side's non-conflicting hunks."""
107
+ stages = {}
108
+ for line in git(repo, "ls-files", "-u", "-z", "--", rel).stdout.split("\0"):
109
+ if line:
110
+ meta, _ = line.split("\t", 1)
111
+ stages[int(meta.split()[2])] = meta.split()[1]
112
+ if 2 not in stages: # we deleted it: stay deleted
113
+ git(repo, "rm", "-q", "--cached", "--", rel)
114
+ p = os.path.join(repo, rel)
115
+ if os.path.exists(p):
116
+ os.remove(p)
117
+ return
118
+ if 1 in stages and 3 in stages:
119
+ # Bytes end to end (was text mode: on Windows it wrote \r\n, and text=True dropped \r
120
+ # from CRLF files everywhere and failed on non-UTF-8 content).
121
+ blobs = []
122
+ for n in (2, 1, 3):
123
+ r = git_bytes(repo, "cat-file", "blob", stages[n])
124
+ if r.returncode != 0:
125
+ raise GitError(f"git cat-file {stages[n]} failed: {r.stderr.decode(errors='replace').strip()}")
126
+ blobs.append(r.stdout)
127
+ import tempfile
128
+ with tempfile.TemporaryDirectory() as td:
129
+ paths = []
130
+ for name, data in zip(("ours", "base", "theirs"), blobs):
131
+ fp = os.path.join(td, name)
132
+ with open(fp, "wb") as f:
133
+ f.write(data)
134
+ paths.append(fp)
135
+ merged = git_bytes(repo, "merge-file", "-p", "--ours", *paths).stdout
136
+ with open(os.path.join(repo, rel), "wb") as f:
137
+ f.write(merged)
138
+ else: # added on both sides, etc.: take ours
139
+ git(repo, "checkout", "--ours", "--", rel)
140
+ git(repo, "add", "-f", "--", rel)
141
+
142
+
143
+ def merge(repo, branch, local_wins=None):
144
+ """Merge `branch` into the checked-out branch with a normal merge.
145
+ Returns (ok, conflicted_files). Conflicted files matching a `local_wins` glob
146
+ (e.g. ["logs/**"]) are resolved with the checked-out side winning conflicting hunks;
147
+ any other conflict stops the merge (left in progress) as usual."""
148
+ r = git(repo, "merge", "--no-edit", "-m", f"dbsync: merge {branch}", branch, check=False)
149
+ if r.returncode == 0:
150
+ return True, []
151
+ conflicts = unmerged_files(repo)
152
+ if not conflicts:
153
+ raise GitError(f"merge failed: {r.stderr.strip() or r.stdout.strip()}")
154
+ if local_wins:
155
+ for rel in conflicts:
156
+ if matches_any(rel, local_wins):
157
+ _resolve_ours(repo, rel)
158
+ conflicts = unmerged_files(repo)
159
+ if not conflicts:
160
+ git(repo, "commit", "-q", "--no-verify", "--no-edit")
161
+ return True, []
162
+ return False, conflicts
163
+
164
+
165
+ def is_ancestor(repo, a, b):
166
+ return git(repo, "merge-base", "--is-ancestor", a, b, check=False).returncode == 0
167
+
168
+
169
+ def head(repo, ref="HEAD"):
170
+ return git(repo, "rev-parse", ref).stdout.strip()
dbsync/hashing.py ADDED
@@ -0,0 +1,22 @@
1
+ """Dropbox content hash: SHA-256 of the concatenated SHA-256 digests of 4 MiB blocks."""
2
+ import hashlib
3
+
4
+ BLOCK = 4 * 1024 * 1024
5
+
6
+
7
+ def content_hash_bytes(data: bytes) -> str:
8
+ outer = hashlib.sha256()
9
+ for i in range(0, len(data), BLOCK):
10
+ outer.update(hashlib.sha256(data[i:i + BLOCK]).digest())
11
+ return outer.hexdigest()
12
+
13
+
14
+ def content_hash_file(path) -> str:
15
+ outer = hashlib.sha256()
16
+ with open(path, "rb") as f:
17
+ while True:
18
+ block = f.read(BLOCK)
19
+ if not block:
20
+ break
21
+ outer.update(hashlib.sha256(block).digest())
22
+ return outer.hexdigest()
dbsync/ignore.py ADDED
@@ -0,0 +1,50 @@
1
+ """Ignore rules. `.env` files are ALWAYS synced (Dropbox is the owner's backup)."""
2
+ from fnmatch import fnmatch
3
+
4
+ DEFAULT_IGNORE = [".git/", "env_*/", ".venv/", "venv/", "node_modules/",
5
+ "__pycache__/", "*.pyc", ".dbsync/"]
6
+
7
+ NEVER_IGNORE_FILES = (".env",)
8
+
9
+
10
+ class IgnoreRules:
11
+ def __init__(self, patterns=None):
12
+ pats = list(DEFAULT_IGNORE) + [p for p in (patterns or []) if p not in DEFAULT_IGNORE]
13
+ # A pattern with a "/" inside it (e.g. "tools/cache/") is a path anchored at the synced
14
+ # root; one without (e.g. "build/", "*.pyc") matches a single name at any depth.
15
+ # path patterns were matched one segment at a time and never hit.
16
+ self.path_pats = [p.strip("/") for p in pats if "/" in p.strip("/")]
17
+ rest = [p for p in pats if "/" not in p.strip("/")]
18
+ self.dir_pats = [p.rstrip("/") for p in rest if p.endswith("/")]
19
+ self.file_pats = [p for p in rest if not p.endswith("/")]
20
+
21
+ def dir_ignored(self, name):
22
+ return any(fnmatch(name, p) for p in self.dir_pats)
23
+
24
+ def path_ignored(self, rel):
25
+ """True if rel (POSIX, relative) is, or is inside, an anchored path pattern."""
26
+ return any(rel == p or rel.startswith(p + "/") or fnmatch(rel, p) for p in self.path_pats)
27
+
28
+ def is_ignored(self, rel_path):
29
+ """rel_path: POSIX path relative to the synced root, e.g. 'a/b/c.txt'."""
30
+ parts = [p for p in rel_path.strip("/").split("/") if p]
31
+ if not parts:
32
+ return False
33
+ if parts[-1] not in NEVER_IGNORE_FILES and self.path_ignored("/".join(parts)):
34
+ return True
35
+ if any(self.dir_ignored(d) for d in parts[:-1]):
36
+ return True
37
+ name = parts[-1]
38
+ if name == ".git": # .git file (worktrees/submodules) or dir
39
+ return True
40
+ if name in NEVER_IGNORE_FILES:
41
+ return False
42
+ return any(fnmatch(name, p) for p in self.file_pats)
43
+
44
+ def is_ignored_dir(self, rel_dir):
45
+ parts = [p for p in rel_dir.strip("/").split("/") if p]
46
+ return self.path_ignored("/".join(parts)) or any(self.dir_ignored(d) for d in parts)
47
+
48
+ def as_gitignore(self):
49
+ return "\n".join(["/" + p + "/" for p in self.path_pats] + [p + "/" for p in self.dir_pats]
50
+ + self.file_pats) + "\n"
@@ -0,0 +1,41 @@
1
+ """Platform-specific bits live here, behind one small interface:
2
+
3
+ CONFIG_DIR config folder (posix: ~/.config/dbsync; Windows: %APPDATA%/dbsync)
4
+ DATA_DIR state/log/status folder (posix: ~/.local/share/dbsync;
5
+ Windows: %LOCALAPPDATA%/dbsync)
6
+ file_lock(path) exclusive inter-process lock (context manager)
7
+ ControlServer(path, handler) local command channel (daemon side)
8
+ send_command(path, cmd) local command channel (client side)
9
+ control_address() default address for the channel
10
+ open_path(path) open a folder/file in the desktop
11
+ notify(title, body, urgent) desktop notification
12
+ pid_alive(pid)
13
+ single_instance(lockpath) process-lifetime lock (None if already running)
14
+ service_hint() "is it running?" text for messages (posix: systemctl --user status dbsync)
15
+ run_tray(status_path, control_addr, local_folder, log_path)
16
+ tray icon main loop (posix: linux_tray.py; win32: windows_tray.py)
17
+
18
+ Linux/macOS: posix.py. Windows: windows.py with the same names.
19
+ The tray module is imported only when run_tray() is called, so the daemon never needs GUI libs.
20
+
21
+ win32 imports .windows
22
+ instead of raising; CONFIG_DIR, DATA_DIR, service_hint and run_tray added to the interface.
23
+ """
24
+ import sys
25
+
26
+ if sys.platform.startswith("win"):
27
+ from .windows import (CONFIG_DIR, DATA_DIR, ControlServer, control_address, # noqa: F401
28
+ file_lock, notify, open_path, pid_alive, send_command, service_hint,
29
+ single_instance)
30
+
31
+ def run_tray(status_path, control_addr, local_folder, log_path):
32
+ from .windows_tray import run_tray as _run
33
+ return _run(status_path, control_addr, local_folder, log_path)
34
+ else:
35
+ from .posix import (CONFIG_DIR, DATA_DIR, ControlServer, control_address, # noqa: F401
36
+ file_lock, notify, open_path, pid_alive, send_command, service_hint,
37
+ single_instance)
38
+
39
+ def run_tray(status_path, control_addr, local_folder, log_path):
40
+ from .linux_tray import run_tray as _run
41
+ return _run(status_path, control_addr, local_folder, log_path)
@@ -0,0 +1,123 @@
1
+ """Linux tray icon (AyatanaAppIndicator3 via PyGObject). Needs system python3-gi and
2
+ gir1.2-ayatanaappindicator3-0.1; `dbsync tray` re-runs itself with /usr/bin/python3 if the
3
+ venv has no gi. Talks to the daemon only through the status file and the control channel.
4
+ texts via plat.service_hint()."""
5
+ import logging
6
+ import os
7
+ import threading
8
+
9
+ import gi
10
+
11
+ gi.require_version("Gtk", "3.0")
12
+ gi.require_version("AyatanaAppIndicator3", "0.1")
13
+ from gi.repository import AyatanaAppIndicator3 as AI # noqa: E402
14
+ from gi.repository import GLib, Gtk # noqa: E402
15
+
16
+ from ..status import PROBLEM_STATES, effective_state, read_status # noqa: E402
17
+ from . import notify, open_path, pid_alive, send_command, service_hint # noqa: E402
18
+
19
+ log = logging.getLogger("dbsync.tray")
20
+
21
+ # an installed package keeps its icons in dbsync/assets; a source
22
+ # checkout keeps them in assets/ at the top.
23
+ _PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24
+ ASSETS = next((d for d in (os.path.join(_PKG, "assets"), os.path.join(os.path.dirname(_PKG), "assets"))
25
+ if os.path.isdir(d)), os.path.join(os.path.dirname(_PKG), "assets"))
26
+ ICON = {"synced": "dbsync-synced", "syncing": "dbsync-syncing", "paused": "dbsync-paused",
27
+ "conflict": "dbsync-conflict", "error": "dbsync-error", "offline": "dbsync-offline",
28
+ "stopped": "dbsync-error"}
29
+ LABEL = {"synced": "Synced", "syncing": "Syncing…", "paused": "Paused", "conflict": "Conflict",
30
+ "error": "Error", "offline": "Offline", "stopped": "Daemon not running"}
31
+
32
+
33
+ class Tray:
34
+ def __init__(self, status_path, control_addr, local_folder, log_path, poll=1):
35
+ self.status_path, self.control_addr = status_path, control_addr
36
+ self.local_folder, self.log_path = local_folder, log_path
37
+ self.notified = None # (state, message) last notified
38
+ self.state = None
39
+ self.ind = AI.Indicator.new("dbsync", ICON["syncing"],
40
+ AI.IndicatorCategory.APPLICATION_STATUS)
41
+ self.ind.set_icon_theme_path(ASSETS)
42
+ self.ind.set_status(AI.IndicatorStatus.ACTIVE)
43
+ self.ind.set_title("dbsync")
44
+ menu = Gtk.Menu()
45
+ self.status_item = Gtk.MenuItem(label="dbsync: …")
46
+ self.status_item.set_sensitive(False)
47
+ self.detail_item = Gtk.MenuItem(label="")
48
+ self.detail_item.set_sensitive(False)
49
+ menu.append(self.status_item)
50
+ menu.append(self.detail_item)
51
+ menu.append(Gtk.SeparatorMenuItem())
52
+ self.sync_item = self._item(menu, "Sync now", lambda *_: self._cmd("sync-now"))
53
+ self.pause_item = self._item(menu, "Pause", self._toggle_pause)
54
+ menu.append(Gtk.SeparatorMenuItem())
55
+ self._item(menu, "Open folder", lambda *_: open_path(self.local_folder))
56
+ self._item(menu, "Open log", lambda *_: open_path(self.log_path))
57
+ menu.append(Gtk.SeparatorMenuItem())
58
+ self._item(menu, "Quit tray", lambda *_: Gtk.main_quit())
59
+ menu.show_all()
60
+ self.ind.set_menu(menu)
61
+ self.refresh()
62
+ GLib.timeout_add_seconds(poll, self.refresh)
63
+
64
+ @staticmethod
65
+ def _item(menu, label, cb):
66
+ it = Gtk.MenuItem(label=label)
67
+ it.connect("activate", cb)
68
+ menu.append(it)
69
+ return it
70
+
71
+ def _cmd(self, cmd):
72
+ def run():
73
+ try:
74
+ r = send_command(self.control_addr, cmd)
75
+ if not r.get("ok"):
76
+ log.warning("command %s failed: %s", cmd, r.get("error"))
77
+ except OSError as e:
78
+ log.warning("command %s: daemon unreachable (%s)", cmd, type(e).__name__)
79
+ GLib.idle_add(notify, "dbsync", f"Daemon is not running ({service_hint('start')})", True)
80
+ GLib.timeout_add(300, self.refresh_once)
81
+ threading.Thread(target=run, daemon=True).start()
82
+
83
+ def _toggle_pause(self, *_):
84
+ self._cmd("resume" if self.state == "paused" else "pause")
85
+
86
+ def refresh_once(self):
87
+ self.refresh()
88
+ return False
89
+
90
+ def refresh(self):
91
+ st = read_status(self.status_path)
92
+ state = effective_state(st, pid_alive)
93
+ msg = (st or {}).get("message", "") if state != "stopped" else service_hint("start")
94
+ if state != self.state:
95
+ self.ind.set_icon_full(ICON.get(state, ICON["error"]), f"dbsync: {LABEL.get(state, state)}")
96
+ self.state = state
97
+ last = (st or {}).get("last_sync")
98
+ line = f"dbsync: {LABEL.get(state, state)}"
99
+ if last and state in ("synced", "paused"):
100
+ line += f" · {last[11:16]}"
101
+ self.status_item.set_label(line)
102
+ self.detail_item.set_label((msg or "")[:70])
103
+ self.detail_item.set_visible(bool(msg))
104
+ self.pause_item.set_label("Resume" if state == "paused" else "Pause")
105
+ busy = state in ("syncing", "stopped")
106
+ self.sync_item.set_sensitive(not busy)
107
+ self.pause_item.set_sensitive(state != "stopped")
108
+ if state in PROBLEM_STATES:
109
+ key = (state, msg)
110
+ if key != self.notified:
111
+ self.notified = key
112
+ files = ", ".join((st or {}).get("conflicts", [])[:5])
113
+ notify(f"dbsync: {LABEL[state]}", (msg or "") + (f"\n{files}" if files else ""),
114
+ urgent=state == "error")
115
+ elif state == "synced":
116
+ self.notified = None
117
+ return True
118
+
119
+
120
+ def run_tray(status_path, control_addr, local_folder, log_path):
121
+ Tray(status_path, control_addr, local_folder, log_path)
122
+ Gtk.main()
123
+ return 0
dbsync/plat/posix.py ADDED
@@ -0,0 +1,160 @@
1
+ """POSIX implementation: fcntl lock, unix-socket control channel, xdg-open, notify-send."""
2
+ import fcntl
3
+ import json
4
+ import logging
5
+ import os
6
+ import shutil
7
+ import socket
8
+ import subprocess
9
+ import sys
10
+ import threading
11
+ from contextlib import contextmanager
12
+
13
+ log = logging.getLogger("dbsync")
14
+
15
+ # paths + service hint
16
+ # moved behind the plat interface.
17
+ CONFIG_DIR = os.path.expanduser("~/.config/dbsync")
18
+ # DBSYNC_DATA_DIR gives one running copy its own data folder (state, log, status, control socket), so
19
+ # more than one folder can be synced by one user, one service per folder. Unset: exactly as before.
20
+ DATA_DIR_DEFAULT = os.path.expanduser("~/.local/share/dbsync")
21
+ DATA_DIR = os.path.expanduser(os.environ.get("DBSYNC_DATA_DIR") or DATA_DIR_DEFAULT)
22
+
23
+
24
+ def service_hint(action="status"):
25
+ """Text telling the user how to check/start the background service."""
26
+ return f"systemctl --user {action} dbsync"
27
+
28
+
29
+ @contextmanager
30
+ def file_lock(path, on_wait=None):
31
+ os.makedirs(os.path.dirname(path), exist_ok=True)
32
+ with open(path, "w") as fh:
33
+ try:
34
+ fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
35
+ except BlockingIOError:
36
+ if on_wait:
37
+ on_wait()
38
+ fcntl.flock(fh, fcntl.LOCK_EX)
39
+ try:
40
+ yield
41
+ finally:
42
+ fcntl.flock(fh, fcntl.LOCK_UN)
43
+
44
+
45
+ def single_instance(path):
46
+ """Non-blocking exclusive lock held for the process lifetime. Returns handle or None."""
47
+ os.makedirs(os.path.dirname(path), exist_ok=True)
48
+ fh = open(path, "w")
49
+ try:
50
+ fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
51
+ except BlockingIOError:
52
+ fh.close()
53
+ return None
54
+ return fh
55
+
56
+
57
+ def control_address(data_dir):
58
+ # a copy with its own data folder (DBSYNC_DATA_DIR) keeps its socket there, so two copies never share one.
59
+ if os.path.abspath(data_dir) != os.path.abspath(DATA_DIR_DEFAULT):
60
+ return os.path.join(data_dir, "dbsync.sock")
61
+ run = os.environ.get("XDG_RUNTIME_DIR")
62
+ base = run if run and os.path.isdir(run) else data_dir
63
+ return os.path.join(base, "dbsync.sock")
64
+
65
+
66
+ class ControlServer:
67
+ """One JSON line in ({"cmd": ...}), one JSON line out. Socket mode 0600 (owner only)."""
68
+
69
+ def __init__(self, path, handler):
70
+ self.path = path
71
+ self.handler = handler
72
+ self._sock = None
73
+
74
+ def start(self):
75
+ if os.path.exists(self.path):
76
+ try: # another daemon alive?
77
+ send_command(self.path, "status", timeout=1)
78
+ raise RuntimeError(f"another dbsync daemon is listening on {self.path}")
79
+ except (ConnectionError, OSError):
80
+ os.unlink(self.path)
81
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
82
+ old = os.umask(0o177)
83
+ try:
84
+ s.bind(self.path)
85
+ finally:
86
+ os.umask(old)
87
+ s.listen(4)
88
+ self._sock = s
89
+ threading.Thread(target=self._serve, name="control", daemon=True).start()
90
+
91
+ def _serve(self):
92
+ while True:
93
+ try:
94
+ conn, _ = self._sock.accept()
95
+ except OSError:
96
+ return
97
+ with conn:
98
+ try:
99
+ conn.settimeout(5)
100
+ data = b""
101
+ while not data.endswith(b"\n") and len(data) < 4096:
102
+ chunk = conn.recv(1024)
103
+ if not chunk:
104
+ break
105
+ data += chunk
106
+ cmd = json.loads(data.decode() or "{}").get("cmd", "")
107
+ reply = self.handler(cmd)
108
+ except Exception as e: # never kill the server thread
109
+ reply = {"ok": False, "error": type(e).__name__}
110
+ try:
111
+ conn.sendall((json.dumps(reply) + "\n").encode())
112
+ except OSError:
113
+ pass
114
+
115
+ def close(self):
116
+ if self._sock:
117
+ self._sock.close()
118
+ try:
119
+ os.unlink(self.path)
120
+ except FileNotFoundError:
121
+ pass
122
+
123
+
124
+ def send_command(path, cmd, timeout=5):
125
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
126
+ s.settimeout(timeout)
127
+ try:
128
+ s.connect(path)
129
+ s.sendall((json.dumps({"cmd": cmd}) + "\n").encode())
130
+ data = b""
131
+ while not data.endswith(b"\n"):
132
+ chunk = s.recv(65536)
133
+ if not chunk:
134
+ break
135
+ data += chunk
136
+ return json.loads(data.decode() or "{}")
137
+ finally:
138
+ s.close()
139
+
140
+
141
+ def open_path(path):
142
+ opener = "open" if sys.platform == "darwin" else "xdg-open"
143
+ subprocess.Popen([opener, path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
144
+ start_new_session=True)
145
+
146
+
147
+ def notify(title, body, urgent=False):
148
+ if not shutil.which("notify-send"):
149
+ log.info("notify (no notify-send): %s: %s", title, body)
150
+ return
151
+ subprocess.Popen(["notify-send", "-a", "dbsync", "-u", "critical" if urgent else "normal",
152
+ title, body], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
153
+
154
+
155
+ def pid_alive(pid):
156
+ try:
157
+ os.kill(int(pid), 0)
158
+ return True
159
+ except (OSError, ValueError, TypeError):
160
+ return False