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/sync.py ADDED
@@ -0,0 +1,627 @@
1
+ """Pull / push / status / watch for one configured folder.
2
+
3
+ Deletes and renames (phase 2):
4
+ - local delete -> remote files/delete_v2 with parent_rev = last-known rev (mismatch = conflict).
5
+ - remote delete -> removed on the `dropbox` branch, then merged into `main`; git deletes the
6
+ local file only if it is unchanged since the last sync, otherwise a modify/delete conflict
7
+ keeps the local file.
8
+ - local rename (delete A + new B, same content_hash) -> files/move_v2 (A's rev checked first).
9
+ - remote rename (deleted A + new B, same content_hash, same batch) -> git mv on `dropbox`,
10
+ merged into `main`.
11
+ """
12
+ import logging
13
+ import os
14
+ import shutil
15
+ import signal
16
+ import time
17
+ from dataclasses import dataclass, field
18
+
19
+ from . import gitops
20
+ from .api import CursorReset, NotFound, RevConflict, assert_within_configured_roots
21
+ from .hashing import content_hash_file
22
+ from .ignore import IgnoreRules
23
+ from .plat import file_lock
24
+ from .state import State
25
+
26
+ log = logging.getLogger("dbsync")
27
+
28
+ MAIN, MIRROR = "main", "dropbox"
29
+
30
+
31
+ @dataclass
32
+ class Report:
33
+ downloaded: list = field(default_factory=list)
34
+ uploaded: list = field(default_factory=list)
35
+ remote_deleted: list = field(default_factory=list) # remote deletes applied locally
36
+ delete_conflicts: list = field(default_factory=list) # remote deleted, local changed: kept
37
+ moved_local: list = field(default_factory=list) # remote renames applied locally (a, b)
38
+ deleted_remote: list = field(default_factory=list) # local deletes pushed to Dropbox
39
+ moved_remote: list = field(default_factory=list) # local renames pushed as moves (a, b)
40
+ local_deleted: list = field(default_factory=list) # local deletes NOT pushed (disabled/guard)
41
+ conflicts: list = field(default_factory=list) # git merge conflicts (files)
42
+ rev_conflicts: list = field(default_factory=list) # writes/deletes refused by Dropbox
43
+ skipped: list = field(default_factory=list)
44
+ pending: list = field(default_factory=list) # dry-run / status
45
+ messages: list = field(default_factory=list)
46
+ kept_remote: list = field(default_factory=list) # protected: Dropbox change kept aside (rel, copy)
47
+ error: str = ""
48
+
49
+ @property
50
+ def has_conflict(self):
51
+ return bool(self.conflicts or self.rev_conflicts or self.delete_conflicts)
52
+
53
+ @property
54
+ def changed_anything(self):
55
+ return bool(self.downloaded or self.uploaded or self.remote_deleted or self.moved_local
56
+ or self.deleted_remote or self.moved_remote)
57
+
58
+
59
+ def walk_local(root, rules):
60
+ """Return {rel: abspath} for syncable regular files under root."""
61
+ out = {}
62
+ for dirpath, dirnames, filenames in os.walk(root):
63
+ rel_dir = os.path.relpath(dirpath, root).replace(os.sep, "/")
64
+ rel_dir = "" if rel_dir == "." else rel_dir
65
+ dirnames[:] = [d for d in dirnames
66
+ if not rules.is_ignored_dir(f"{rel_dir}/{d}" if rel_dir else d)
67
+ and d != ".git" and not os.path.islink(os.path.join(dirpath, d))]
68
+ for fn in filenames:
69
+ rel = f"{rel_dir}/{fn}" if rel_dir else fn
70
+ ap = os.path.join(dirpath, fn)
71
+ if rules.is_ignored(rel) or os.path.islink(ap) or not os.path.isfile(ap):
72
+ continue
73
+ if fn.endswith(".dbsync-tmp"):
74
+ continue
75
+ out[rel] = ap
76
+ return out
77
+
78
+
79
+ def _pair_renames(gone, new, hash_of_gone, hash_of_new):
80
+ """Pair deleted paths with new paths of identical content_hash (prefer same basename).
81
+ -> [(old, new)]"""
82
+ pairs, used = [], set()
83
+ for b in new:
84
+ hb = hash_of_new(b)
85
+ cands = [a for a in gone if a not in used and hash_of_gone(a) == hb]
86
+ if not cands:
87
+ continue
88
+ same = [a for a in cands if a.rsplit("/", 1)[-1] == b.rsplit("/", 1)[-1]]
89
+ a = (same or cands)[0]
90
+ used.add(a)
91
+ pairs.append((a, b))
92
+ return pairs
93
+
94
+
95
+ class FolderSync:
96
+ def __init__(self, folder, api, roots, extra_ignore=None, out=print,
97
+ propagate_local_deletes=True, max_deletes=20,
98
+ settle_seconds=0, hot_upload_interval=0, local_wins=("logs/**",), push_only=False):
99
+ self.f = folder
100
+ self.api = api
101
+ self.roots = roots
102
+ self.rules = IgnoreRules(extra_ignore)
103
+ self.out = out
104
+ self.state = State(folder.state_path)
105
+ self.propagate_local_deletes = propagate_local_deletes
106
+ self.max_deletes = max_deletes
107
+ # Debounce for files that are still being written (e.g. a log appended every 2 s):
108
+ # a file modified < settle_seconds ago is "hot"; a hot file is uploaded at most once
109
+ # per hot_upload_interval (per process). Settled files upload right away.
110
+ self.settle_seconds = settle_seconds
111
+ self.hot_upload_interval = hot_upload_interval
112
+ self._last_upload = {}
113
+ # After a push, conflicts in files matching these globs keep the local side
114
+ # (a log that grew while its snapshot uploaded). Everything else stops on conflict.
115
+ self.local_wins = list(local_wins or ())
116
+ # push_only: one way, local -> Dropbox (files only
117
+ # this machine writes, e.g. live chat transcripts). Remote changes are still fetched into the
118
+ # `dropbox` mirror branch (kept aside there) but never merged into `main`, so a Dropbox-side edit or
119
+ # delete never replaces or removes a local file; the local file is then uploaded over it (the state
120
+ # holds the remote rev, so the rev-checked upload succeeds), and a remotely deleted file is uploaded
121
+ # again as new.
122
+ self.push_only = push_only
123
+
124
+ # ---------- helpers ----------
125
+ def remote_path(self, rel):
126
+ p = self.f.remote + "/" + rel
127
+ assert_within_configured_roots(p, self.roots)
128
+ return p
129
+
130
+ def rel_of(self, remote_display):
131
+ root = self.f.remote
132
+ if remote_display.lower() == root.lower():
133
+ return ""
134
+ if not remote_display.lower().startswith(root.lower() + "/"):
135
+ raise ValueError(f"entry outside root: {remote_display}")
136
+ rel = remote_display[len(root) + 1:]
137
+ if any(p in ("", ".", "..") for p in rel.split("/")):
138
+ raise ValueError(f"bad entry path: {remote_display}")
139
+ return rel
140
+
141
+ def _safe_join(self, base, rel):
142
+ p = os.path.realpath(os.path.join(base, *rel.split("/")))
143
+ if not p.startswith(os.path.realpath(base) + os.sep):
144
+ raise ValueError(f"path escapes folder: {rel}")
145
+ return p
146
+
147
+ def _wt_remove(self, rel):
148
+ """Remove a file from the mirror worktree (+ now-empty parent dirs)."""
149
+ p = self._safe_join(self.f.worktree, rel)
150
+ if os.path.isfile(p):
151
+ os.remove(p)
152
+ d = os.path.dirname(p)
153
+ root = os.path.realpath(self.f.worktree)
154
+ while d.startswith(root + os.sep) and os.path.isdir(d) and not os.listdir(d):
155
+ os.rmdir(d)
156
+ d = os.path.dirname(d)
157
+
158
+ def lock(self):
159
+ return file_lock(self.f.lock_path,
160
+ on_wait=lambda: self.out("waiting for another dbsync run to finish..."))
161
+
162
+ def setup(self):
163
+ gitops.setup_repo(self.f.local, self.f.worktree, self.rules.as_gitignore(), MAIN, MIRROR)
164
+
165
+ # ---------- remote change detection ----------
166
+ def _fetch_changes(self, cursor):
167
+ """-> (entries, new_cursor, full_listing)"""
168
+ if cursor:
169
+ try:
170
+ entries, cur = self.api.list_continue(cursor)
171
+ return entries, cur, False
172
+ except CursorReset:
173
+ log.warning("cursor reset; doing full listing")
174
+ entries, cur = self.api.list_folder(self.f.remote)
175
+ return entries, cur, True
176
+
177
+ def _plan(self, entries, full_listing=False):
178
+ """-> (downloads [(rel, e)], meta_only [(rel, e)], remote_deleted [rel], renames [(a, b, e)])
179
+
180
+ A deleted entry for a folder covers everything below it. Order matters inside a batch:
181
+ an entry only counts if no later entry for the same path (or an ancestor) supersedes it.
182
+ With a full listing, tracked files missing from the listing are deleted remotely.
183
+ """
184
+ files_final = {} # path_lower -> (idx, e)
185
+ dels = [] # (idx, path_lower)
186
+ for i, e in enumerate(entries):
187
+ if e["tag"] == "file":
188
+ files_final[e["path_lower"]] = (i, e)
189
+ elif e["tag"] == "deleted":
190
+ dels.append((i, e["path_lower"]))
191
+
192
+ def last_del(pl):
193
+ return max((i for i, d in dels if pl == d or pl.startswith(d + "/")), default=-1)
194
+
195
+ live = {} # rel -> e for files that exist remotely at the end of the batch
196
+ for pl, (i, e) in files_final.items():
197
+ if last_del(pl) > i:
198
+ continue
199
+ rel = self.rel_of(e["path"])
200
+ if not rel or self.rules.is_ignored(rel) or self.rules.is_ignored_dir(rel):
201
+ continue
202
+ live[rel] = e
203
+
204
+ tracked = self.state.all()
205
+ live_lower = {r.lower() for r in live}
206
+ deleted = []
207
+ for rel in tracked:
208
+ if rel.lower() in live_lower or self.rules.is_ignored(rel):
209
+ continue
210
+ if full_listing or last_del(self.remote_path(rel).lower()) >= 0:
211
+ deleted.append(rel)
212
+
213
+ downloads, meta_only = [], []
214
+ for rel, e in live.items():
215
+ st = self.state.get(rel)
216
+ if st and st["content_hash"] == e["content_hash"]:
217
+ if st["rev"] != e["rev"]:
218
+ meta_only.append((rel, e))
219
+ continue
220
+ wt = os.path.join(self.f.worktree, *rel.split("/"))
221
+ if os.path.isfile(wt) and content_hash_file(wt) == e["content_hash"]:
222
+ meta_only.append((rel, e))
223
+ continue
224
+ downloads.append((rel, e))
225
+
226
+ new_rels = [rel for rel, _ in downloads if self.state.get(rel) is None]
227
+ pairs = _pair_renames(deleted, new_rels, lambda a: tracked[a]["content_hash"],
228
+ lambda b: live[b]["content_hash"])
229
+ renames = [(a, b, live[b]) for a, b in pairs]
230
+ moved_to = {b for _, b in pairs}
231
+ moved_from = {a for a, _ in pairs}
232
+ downloads = [(r, e) for r, e in downloads if r not in moved_to]
233
+ deleted = sorted(r for r in deleted if r not in moved_from)
234
+ return downloads, meta_only, deleted, renames
235
+
236
+ def advance_if_quiet(self):
237
+ """Longpoll can report 'changes' that list_continue shows as an empty batch (activity
238
+ elsewhere in the account). If the batch is empty, just advance the cursor and return
239
+ True; otherwise leave state alone and return False (caller then does a real sync)."""
240
+ with self.lock():
241
+ cursor = self.state.cursor
242
+ if not cursor:
243
+ return False
244
+ try:
245
+ entries, new_cursor = self.api.list_continue(cursor)
246
+ except CursorReset:
247
+ return False
248
+ if entries:
249
+ return False
250
+ self.state.set_cursor(new_cursor)
251
+ return True
252
+
253
+ # ---------- pull ----------
254
+ def pull(self, dry_run=False):
255
+ with self.lock():
256
+ return self._pull(dry_run)
257
+
258
+ def _local_unchanged(self, rel, st):
259
+ p = os.path.join(self.f.local, *rel.split("/"))
260
+ if not os.path.isfile(p):
261
+ return True
262
+ return content_hash_file(p) == st["content_hash"]
263
+
264
+ def _pull(self, dry_run=False, rep=None):
265
+ rep = rep or Report()
266
+ entries, new_cursor, full = self._fetch_changes(self.state.cursor)
267
+ downloads, meta_only, deleted, renames = self._plan(entries, full_listing=full)
268
+ if dry_run:
269
+ rep.pending += [f"download {rel}" for rel, _ in downloads]
270
+ rep.pending += [f"delete locally {rel}" for rel in deleted]
271
+ rep.pending += [f"rename locally {a} -> {b}" for a, b, _ in renames]
272
+ return rep
273
+ touched = []
274
+ for rel, e in downloads:
275
+ dest = self._safe_join(self.f.worktree, rel)
276
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
277
+ tmp = dest + ".dbsync-tmp"
278
+ md = self.api.download(self.remote_path(rel), tmp)
279
+ got = content_hash_file(tmp)
280
+ if got != md["content_hash"]:
281
+ os.remove(tmp)
282
+ raise RuntimeError(f"hash mismatch downloading {rel}")
283
+ os.replace(tmp, dest)
284
+ log.info("downloaded %s rev=%s", rel, md["rev"])
285
+ rep.downloaded.append((rel, md))
286
+ touched.append(rel)
287
+ for a, b, e in renames:
288
+ src = self._safe_join(self.f.worktree, a)
289
+ dst = self._safe_join(self.f.worktree, b)
290
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
291
+ if os.path.isfile(src) and content_hash_file(src) == e["content_hash"]:
292
+ os.replace(src, dst)
293
+ else: # mirror out of step: fetch B instead
294
+ tmp = dst + ".dbsync-tmp"
295
+ self.api.download(self.remote_path(b), tmp)
296
+ os.replace(tmp, dst)
297
+ self._wt_remove(a)
298
+ st = self.state.get(a)
299
+ log.info("remote rename %s (rev=%s) -> %s rev=%s", a, st and st["rev"], b, e["rev"])
300
+ rep.moved_local.append((a, b))
301
+ touched.append(b)
302
+ for rel in deleted:
303
+ st = self.state.get(rel)
304
+ if self._local_unchanged(rel, st):
305
+ rep.remote_deleted.append(rel)
306
+ log.info("remote delete %s (last rev=%s): deleting local copy", rel, st["rev"])
307
+ else:
308
+ rep.delete_conflicts.append(rel)
309
+ log.warning("remote delete %s (last rev=%s) but local file changed: kept, conflict",
310
+ rel, st["rev"])
311
+ self._wt_remove(rel)
312
+ if touched or deleted:
313
+ n = len(downloads) + len(renames) + len(deleted)
314
+ gitops.stage_and_commit(self.f.worktree, touched,
315
+ f"dbsync: pull {n} change(s) from Dropbox")
316
+ for rel, md in rep.downloaded:
317
+ if self._push_only_skip(rel):
318
+ continue
319
+ self.state.put(rel, md["rev"], md["content_hash"], md["size"], None)
320
+ rep.downloaded = [r for r, _ in rep.downloaded]
321
+ for a, b, e in renames:
322
+ self.state.delete(a)
323
+ if not self._push_only_skip(b):
324
+ self.state.put(b, e["rev"], e["content_hash"], e["size"], None)
325
+ for rel in deleted:
326
+ self.state.delete(rel)
327
+ for rel, e in meta_only:
328
+ st = self.state.get(rel) or {}
329
+ self.state.put(rel, e["rev"], e["content_hash"], e["size"], st.get("mtime"))
330
+ self.state.set_cursor(new_cursor)
331
+ self.state.mark_synced()
332
+ hits = [rel for rel, _ in downloads] + list(deleted) + [a for a, _, _ in renames]
333
+ self._merge_into_main(rep, protected=[r for r in hits if self._is_protected(r)])
334
+ return rep
335
+
336
+ def _push_only_skip(self, rel):
337
+ # a file that came down only into the
338
+ # mirror, with no copy in the local folder, must not go into state. Otherwise local_changes()
339
+ # reads it as a local delete and the next push deletes it from Dropbox.
340
+ return self.push_only and not os.path.isfile(os.path.join(self.f.local, *rel.split("/")))
341
+
342
+ def _is_protected(self, rel):
343
+ return bool(self.f.protect) and gitops.matches_any(rel, self.f.protect)
344
+
345
+ def _merge_into_main(self, rep, prefer_local=False, protected=()):
346
+ repo = self.f.local
347
+ # a protected file keeps its local bytes;
348
+ # what came from Dropbox is kept beside it as <name>.remote-<time> and reported, and the
349
+ # next push puts the local file back up (state holds the remote rev, so the upload is allowed).
350
+ saved = {}
351
+ for rel in protected:
352
+ p = os.path.join(repo, *rel.split("/"))
353
+ if os.path.isfile(p):
354
+ with open(p, "rb") as fh:
355
+ saved[rel] = fh.read()
356
+ if self.push_only: # push_only: never bring the mirror into the local folder
357
+ return
358
+ if gitops.merge_in_progress(repo):
359
+ rep.conflicts += gitops.unmerged_files(repo) or ["(merge in progress)"]
360
+ rep.messages.append("main has an unfinished merge; resolve it, then commit")
361
+ return
362
+ if gitops.current_branch(repo) != MAIN:
363
+ rep.error = f"local repo is not on '{MAIN}'; not merging"
364
+ return
365
+ files = list(walk_local(repo, self.rules))
366
+ if gitops.stage_and_commit(repo, files, "dbsync: auto-commit local changes"):
367
+ rep.messages.append("auto-committed local changes on main")
368
+ if gitops.is_ancestor(repo, MIRROR, MAIN):
369
+ return
370
+ wins = (list(self.local_wins) if prefer_local else []) + list(self.f.protect)
371
+ ok, conflicts = gitops.merge(repo, MIRROR, local_wins=wins or None)
372
+ if ok:
373
+ log.info("merged %s into %s", MIRROR, MAIN)
374
+ self._restore_protected(rep, saved)
375
+ else:
376
+ rep.conflicts += conflicts
377
+ log.warning("merge conflict: %s", conflicts)
378
+
379
+ def _restore_protected(self, rep, saved):
380
+ repo = self.f.local
381
+ stamp = time.strftime("%Y%m%d-%H%M%S")
382
+ touched = []
383
+ for rel, data in saved.items():
384
+ p = os.path.join(repo, *rel.split("/"))
385
+ remote = None
386
+ if os.path.isfile(p):
387
+ with open(p, "rb") as fh:
388
+ remote = fh.read()
389
+ if remote == data:
390
+ continue
391
+ copy = None
392
+ if remote is not None:
393
+ copy = f"{rel}.remote-{stamp}"
394
+ with open(os.path.join(repo, *copy.split("/")), "wb") as fh:
395
+ fh.write(remote)
396
+ touched.append(copy)
397
+ os.makedirs(os.path.dirname(p), exist_ok=True)
398
+ with open(p, "wb") as fh:
399
+ fh.write(data)
400
+ touched.append(rel)
401
+ what = f"kept beside it as {copy}" if copy else "it was deleted in Dropbox"
402
+ rep.kept_remote.append((rel, copy))
403
+ rep.messages.append(f"protected {rel}: Dropbox change not applied ({what}); local copy goes back up")
404
+ log.warning("protected %s: remote change not applied (%s)", rel, what)
405
+ if touched:
406
+ gitops.stage_and_commit(repo, touched, "dbsync: protected files kept local")
407
+
408
+ def is_hot(self, ap, now=None):
409
+ try:
410
+ return (now or time.time()) - os.stat(ap).st_mtime < self.settle_seconds
411
+ except OSError:
412
+ return False
413
+
414
+ def is_deferred(self, rel, ap, now=None):
415
+ """Hot and uploaded less than hot_upload_interval ago -> wait."""
416
+ now = now or time.time()
417
+ return self.is_hot(ap, now) and \
418
+ now - self._last_upload.get(rel, float("-inf")) < self.hot_upload_interval
419
+
420
+ # ---------- local change detection ----------
421
+ def local_changes(self):
422
+ """-> (changed [(rel, abspath, hash, prev_state)], local_deleted [rel])"""
423
+ local = walk_local(self.f.local, self.rules)
424
+ changed = []
425
+ for rel, ap in sorted(local.items()):
426
+ st = self.state.get(rel)
427
+ stt = os.stat(ap)
428
+ if st and st["size"] == stt.st_size and st["mtime"] == stt.st_mtime:
429
+ continue
430
+ h = content_hash_file(ap)
431
+ if st and st["content_hash"] == h:
432
+ self.state.put(st["rel"], st["rev"], h, stt.st_size, stt.st_mtime)
433
+ continue
434
+ changed.append((rel, ap, h, st))
435
+ local_lower = {r.lower() for r in local}
436
+ deleted = [r for r in self.state.all() if r.lower() not in local_lower
437
+ and not self.rules.is_ignored(r)]
438
+ return changed, sorted(deleted)
439
+
440
+ # ---------- push ----------
441
+ def push(self, dry_run=False, allow_mass_delete=False):
442
+ with self.lock():
443
+ return self._push(dry_run, allow_mass_delete)
444
+
445
+ def _push(self, dry_run, allow_mass_delete=False):
446
+ repo = self.f.local
447
+ rep = Report()
448
+ if not os.path.isdir(repo) or not gitops.is_repo(repo):
449
+ rep.error = f"local folder {repo} is missing or not a git repo; refusing to push"
450
+ return rep
451
+ if gitops.merge_in_progress(repo):
452
+ rep.conflicts = gitops.unmerged_files(repo) or ["(merge in progress)"]
453
+ rep.error = "unfinished merge on main; resolve and commit before pushing"
454
+ return rep
455
+ self._pull(dry_run, rep)
456
+ if rep.has_conflict or rep.error:
457
+ rep.error = rep.error or "pull produced conflicts; nothing pushed"
458
+ return rep
459
+ if not dry_run and not self.push_only and not gitops.is_ancestor(repo, MIRROR, MAIN):
460
+ rep.error = f"'{MIRROR}' is not merged into '{MAIN}'; merge it before pushing"
461
+ return rep
462
+ changed, deleted = self.local_changes()
463
+ renames = []
464
+ if self.propagate_local_deletes:
465
+ new = {c[0]: c for c in changed if c[3] is None}
466
+ tracked = self.state.all()
467
+ pairs = _pair_renames(deleted, list(new), lambda a: tracked[a]["content_hash"],
468
+ lambda b: new[b][2])
469
+ renames = [(a, new[b]) for a, b in pairs]
470
+ moved_to = {b for _, b in pairs}
471
+ moved_from = {a for a, _ in pairs}
472
+ changed = [c for c in changed if c[0] not in moved_to]
473
+ deleted = [d for d in deleted if d not in moved_from]
474
+ if len(deleted) > self.max_deletes and not allow_mass_delete:
475
+ rep.error = (f"{len(deleted)} local deletions exceed max_deletes={self.max_deletes}; "
476
+ "not deleting remotely (run `dbsync push --allow-mass-delete`)")
477
+ rep.local_deleted = deleted
478
+ deleted = []
479
+ else:
480
+ rep.local_deleted = deleted
481
+ deleted = []
482
+ if dry_run:
483
+ rep.pending += [f"upload {c[0]}" for c in changed]
484
+ rep.pending += [f"move remote {a} -> {c[0]}" for a, c in renames]
485
+ rep.pending += [f"delete remote {rel}" for rel in deleted]
486
+ return rep
487
+
488
+ deferred = [c for c in changed if self.is_deferred(c[0], c[1])]
489
+ if deferred:
490
+ rep.skipped += [c[0] for c in deferred]
491
+ changed = [c for c in changed if c not in deferred]
492
+ log.info("deferred %d hot file(s) (upload at most every %ss): %s", len(deferred),
493
+ self.hot_upload_interval, ", ".join(c[0] for c in deferred[:5]))
494
+ pushed = []
495
+ for a, (b, ap, h, _) in renames:
496
+ st = self.state.get(a)
497
+ try:
498
+ md = self.api.move(self.remote_path(a), self.remote_path(b), expect_rev=st["rev"])
499
+ except RevConflict:
500
+ log.warning("rename %s -> %s: remote changed or move refused; "
501
+ "falling back to upload + rev-checked delete", a, b)
502
+ changed.append((b, ap, h, None))
503
+ deleted.append(a)
504
+ continue
505
+ wt_a = self._safe_join(self.f.worktree, a)
506
+ wt_b = self._safe_join(self.f.worktree, b)
507
+ os.makedirs(os.path.dirname(wt_b), exist_ok=True)
508
+ if os.path.isfile(wt_a):
509
+ os.replace(wt_a, wt_b)
510
+ else:
511
+ shutil.copy2(ap, wt_b)
512
+ self._wt_remove(a)
513
+ stt = os.stat(ap)
514
+ mtime = stt.st_mtime if content_hash_file(ap) == md["content_hash"] else None
515
+ self.state.delete(a)
516
+ self.state.put(b, md["rev"], md["content_hash"], md["size"], mtime)
517
+ log.info("moved remote %s (rev=%s) -> %s rev=%s", a, st["rev"], b, md["rev"])
518
+ rep.moved_remote.append((a, b))
519
+ pushed.append(b)
520
+
521
+ for rel, ap, h, st in changed:
522
+ dest = self._safe_join(self.f.worktree, rel)
523
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
524
+ tmp = dest + ".dbsync-tmp"
525
+ shutil.copy2(ap, tmp) # snapshot = exactly what gets uploaded
526
+ snap_hash = content_hash_file(tmp)
527
+ rev = st["rev"] if st else None
528
+ try:
529
+ md = self.api.upload(self.remote_path(rel), tmp, rev=rev)
530
+ except RevConflict:
531
+ os.remove(tmp)
532
+ rep.rev_conflicts.append(rel)
533
+ log.warning("rev conflict on %s (remote changed); not overwritten", rel)
534
+ continue
535
+ except Exception:
536
+ os.remove(tmp)
537
+ raise
538
+ if md["content_hash"] != snap_hash:
539
+ log.warning("uploaded hash differs for %s", rel)
540
+ os.replace(tmp, dest)
541
+ stt = os.stat(ap)
542
+ mtime = stt.st_mtime if content_hash_file(ap) == snap_hash else None
543
+ self.state.put(rel, md["rev"], md["content_hash"], md["size"], mtime)
544
+ log.info("uploaded %s rev=%s (mode=%s)", rel, md["rev"], "update" if rev else "add")
545
+ rep.uploaded.append(rel)
546
+ pushed.append(rel)
547
+ self._last_upload[rel] = time.time()
548
+
549
+ for rel in deleted:
550
+ st = self.state.get(rel)
551
+ if not st or not st.get("rev"): # hard rule: only paths tracked in state
552
+ log.warning("not deleting %s: not tracked in state", rel)
553
+ continue
554
+ try:
555
+ self.api.delete(self.remote_path(rel), parent_rev=st["rev"])
556
+ log.info("deleted remote %s rev=%s (recoverable in Dropbox)", rel, st["rev"])
557
+ except NotFound:
558
+ log.info("remote %s already gone (last rev=%s)", rel, st["rev"])
559
+ except RevConflict:
560
+ rep.rev_conflicts.append(rel)
561
+ log.warning("delete of %s refused: remote rev != %s (changed elsewhere); kept",
562
+ rel, st["rev"])
563
+ continue
564
+ self._wt_remove(rel)
565
+ self.state.delete(rel)
566
+ rep.deleted_remote.append(rel)
567
+
568
+ if pushed or rep.deleted_remote:
569
+ n = len(pushed) + len(rep.deleted_remote)
570
+ gitops.stage_and_commit(self.f.worktree, pushed, f"dbsync: push {n} change(s)")
571
+ self.state.mark_synced()
572
+ # `dropbox` now only adds our own uploads (remote changes were merged by the pull
573
+ # above). A file that kept growing locally after its snapshot was taken must not
574
+ # conflict with that older snapshot: keep main's (newer) side, but only for
575
+ # paths in local_wins (default logs/**); other conflicts stop as usual.
576
+ self._merge_into_main(rep, prefer_local=True)
577
+ if rep.rev_conflicts:
578
+ rep.messages.append("remote changed during push; pulling + merging. Re-run push after.")
579
+ self._pull(False, rep)
580
+ return rep
581
+
582
+ # ---------- status ----------
583
+ def status(self):
584
+ rep = Report()
585
+ changed, deleted = self.local_changes()
586
+ rep.pending = [f"local change: {r}" for r, *_ in changed]
587
+ rep.pending += [f"local delete: {r}" for r in deleted]
588
+ if self.state.cursor:
589
+ entries, _, full = self._fetch_changes(self.state.cursor)
590
+ downloads, _, rdel, ren = self._plan(entries, full_listing=full)
591
+ rep.pending += [f"remote change: {r}" for r, _ in downloads]
592
+ rep.pending += [f"remote delete: {r}" for r in rdel]
593
+ rep.pending += [f"remote rename: {a} -> {b}" for a, b, _ in ren]
594
+ else:
595
+ rep.messages.append("never synced (run dbsync init)")
596
+ if gitops.is_repo(self.f.local) and gitops.merge_in_progress(self.f.local):
597
+ rep.conflicts = gitops.unmerged_files(self.f.local) or ["(merge in progress)"]
598
+ return rep
599
+
600
+ # ---------- watch (phase 1 foreground loop; the daemon lives in daemon.py) ----------
601
+ def watch(self, timeout, fallback, on_report):
602
+ def _term(*_):
603
+ raise KeyboardInterrupt
604
+ signal.signal(signal.SIGTERM, _term)
605
+ try:
606
+ on_report(self.pull())
607
+ while True:
608
+ try:
609
+ changes, backoff = self.api.longpoll(self.state.cursor, timeout)
610
+ if changes:
611
+ log.info("longpoll: changes")
612
+ on_report(self.pull())
613
+ if backoff:
614
+ time.sleep(backoff)
615
+ except KeyboardInterrupt:
616
+ raise
617
+ except Exception as e: # network drop etc.: fall back to polling
618
+ log.warning("longpoll failed (%s); fallback poll in %ss", type(e).__name__, fallback)
619
+ time.sleep(fallback)
620
+ try:
621
+ on_report(self.pull())
622
+ except KeyboardInterrupt:
623
+ raise
624
+ except Exception as e2:
625
+ log.warning("fallback pull failed: %s", type(e2).__name__)
626
+ except KeyboardInterrupt:
627
+ self.out("watch stopped")