suken-sync 0.1.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.
- suken_sync/GUIDE.md +46 -0
- suken_sync/SYNCED.md +8 -0
- suken_sync/__init__.py +1 -0
- suken_sync/__main__.py +3 -0
- suken_sync/cli.py +280 -0
- suken_sync/common.py +87 -0
- suken_sync/hook.py +79 -0
- suken_sync/profiles.py +57 -0
- suken_sync/service.py +128 -0
- suken_sync/stubs.py +84 -0
- suken_sync/unison.py +215 -0
- suken_sync/watch.py +135 -0
- suken_sync-0.1.0.dist-info/METADATA +89 -0
- suken_sync-0.1.0.dist-info/RECORD +19 -0
- suken_sync-0.1.0.dist-info/WHEEL +5 -0
- suken_sync-0.1.0.dist-info/entry_points.txt +2 -0
- suken_sync-0.1.0.dist-info/licenses/LICENSE +21 -0
- suken_sync-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +17 -0
- suken_sync-0.1.0.dist-info/top_level.txt +1 -0
suken_sync/GUIDE.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# suken-sync — đồng bộ hai chiều một thư mục từ máy Linux về máy này
|
|
2
|
+
|
|
3
|
+
**Việc của bạn:** user muốn đọc và sửa code ngay trên máy này, còn code nằm ở một máy Linux (nơi chạy docker, server, build). Bạn dựng bản sao hai chiều bằng lệnh `add`, mỗi thư mục chạy đúng một lần. Gói tự cài Unison, tự chạy nền, tự nối lại khi mất mạng hoặc VPN.
|
|
4
|
+
|
|
5
|
+
## Lệnh add — BẮT BUỘC đủ 3 tham số
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
suken-sync add --host <tên SSH> --remote <đường dẫn trên Linux> --local <thư mục trên máy này>
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Thiếu hoặc sai một tham số là lệnh bị chặn ngay và in lý do. Hỏi user giá trị nào chưa biết, ĐỪNG tự đoán.
|
|
12
|
+
|
|
13
|
+
| Tham số | Bắt buộc | Ý nghĩa |
|
|
14
|
+
| --- | --- | --- |
|
|
15
|
+
| `--host` | có | tên SSH của máy Linux: tên trong `~/.ssh/config` hoặc `user@host`. Phải vào được bằng key, không hỏi mật khẩu; bật VPN trước nếu máy ở mạng công ty |
|
|
16
|
+
| `--remote` | có | đường dẫn TUYỆT ĐỐI của thư mục trên máy Linux, vd `/home/dev/my_project` |
|
|
17
|
+
| `--local` (cũng viết `--remote-Mac`) | có | đường dẫn TUYỆT ĐỐI của thư mục sẽ chứa bản sao trên máy này, vd `/Users/me/Downloads_linux-box/my_project` |
|
|
18
|
+
| `--threshold` | không | file từ cỡ này trở lên KHÔNG đồng bộ, mặc định `10MB` (viết `500KB`, `10MB`, `2GB`) |
|
|
19
|
+
| `--name` | không | tên phiên, mặc định lấy tên thư mục cuối của `--remote` |
|
|
20
|
+
| `--ignore` | không | mẫu Unison bỏ thêm, lặp lại được, vd `--ignore "Name node_modules"` |
|
|
21
|
+
|
|
22
|
+
## Add làm gì
|
|
23
|
+
|
|
24
|
+
1. Nối ssh, kiểm máy là Linux x86_64 và thư mục có thật.
|
|
25
|
+
2. Cài đúng bản Unison bên Linux (thư mục riêng `~/.cache/suken-sync`, không đụng gì khác).
|
|
26
|
+
3. Đồng bộ lần đầu hai chiều; file từ ngưỡng trở lên bị bỏ.
|
|
27
|
+
4. Tạo file bóng `<tên file>.linux-only.txt` cho mỗi file nặng bên Linux (ghi cỡ và vị trí thật). Bóng không bao giờ đồng bộ ngược.
|
|
28
|
+
5. Cài dịch vụ nền (macOS launchd, Linux systemd user) chạy lại sau reboot, mất mạng, mất VPN.
|
|
29
|
+
6. Cài hook SessionStart vào `<local>/.claude/settings.local.json`; từ đó mỗi phiên Claude mở trong thư mục đó tự nhận hướng dẫn làm việc. Không đụng CLAUDE.md.
|
|
30
|
+
7. Kiểm cuối: đủ thì in "✅ Sync xong", thiếu thì liệt kê từng thứ và thoát mã lỗi.
|
|
31
|
+
|
|
32
|
+
## Sau khi add: cách làm việc
|
|
33
|
+
|
|
34
|
+
- Máy này CHỈ để đọc và sửa code, nội dung trong thư mục đã đồng bộ. Mọi lệnh chạy (build, test, docker, python, dotnet, pip/npm install...) chạy bên Linux: `ssh <host> 'cd <remote>/<thư mục con> && <lệnh>'`.
|
|
35
|
+
- Sửa ở máy này tự sang Linux sau khoảng 1 giây; đợi đủ rồi mới chạy lệnh bên Linux.
|
|
36
|
+
- File nặng chỉ có bóng `*.linux-only.txt`: nội dung thật ở Linux, đừng tải lại, đừng build lại, đừng coi là file lỗi.
|
|
37
|
+
|
|
38
|
+
## Các lệnh khác
|
|
39
|
+
|
|
40
|
+
| Lệnh | Làm gì |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `suken-sync list` | liệt kê các phiên đã thêm |
|
|
43
|
+
| `suken-sync status [tên]` | dịch vụ còn chạy, nối được Linux; thoát mã lỗi nếu có vấn đề |
|
|
44
|
+
| `suken-sync refresh [tên]` | quét file nặng mới bên Linux và cập nhật bóng (chạy sau khi lệnh bên Linux sinh file nặng) |
|
|
45
|
+
| `suken-sync remove <tên>` | tháo phiên: dịch vụ, hook, bóng; không xoá code ở cả hai máy |
|
|
46
|
+
| `suken-sync usage` | in lại hướng dẫn này |
|
suken_sync/SYNCED.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# suken-sync: thư mục này là bản đồng bộ từ máy Linux «{host}»
|
|
2
|
+
|
|
3
|
+
- Gốc trên Linux: `{host}:{remote}` ⇄ gốc ở máy này: `{local}`. Đồng bộ hai chiều, trễ khoảng 1 giây; sửa ở đây tự sang Linux.
|
|
4
|
+
- Máy này CHỈ để đọc và sửa code, nội dung. KHÔNG chạy ở đây: build, test, docker, python, dotnet, pip/npm install...
|
|
5
|
+
- Muốn chạy gì thì chạy bên Linux: `ssh {host} 'cd {remote}/<thư mục con> && <lệnh>'`. Sửa file ở đây xong, đợi khoảng 1 giây rồi mới chạy lệnh bên Linux.
|
|
6
|
+
- File từ {threshold} trở lên KHÔNG đồng bộ. Chỗ nào có `<tên file>.linux-only.txt` là bóng của file nặng: nội dung thật chỉ ở Linux; đừng tải lại, đừng build lại, đừng coi là file lỗi.
|
|
7
|
+
- Đừng tạo file nặng ở đây (sẽ không sang Linux). File nặng mới do lệnh bên Linux sinh ra chưa có bóng cho tới khi chạy `suken-sync refresh {name}`.
|
|
8
|
+
- Nghi đồng bộ hỏng: chạy `suken-sync status {name}`.
|
suken_sync/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
suken_sync/__main__.py
ADDED
suken_sync/cli.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import __version__, profiles, service, stubs
|
|
10
|
+
from .common import DEFAULT_THRESHOLD, HOST, NAME, PATH_CHARS, config_dir, parse_size, read_json, write_json
|
|
11
|
+
from .hook import general_guide, install_hook, installed, settings_path, synced_guide
|
|
12
|
+
from .unison import (ASSETS, VERSION, drop_remote_state, ensure_remote, local_bin, probe, reset_remote_state, run_unison, system_key,
|
|
13
|
+
version_text, write_prf)
|
|
14
|
+
|
|
15
|
+
SETUP_HINT = ("Cài: chạy `suken-sync setup` trước (trong thư mục mở Claude Code). Setup xong sẽ in hướng dẫn dùng lệnh `add` "
|
|
16
|
+
"với các tham số bắt buộc.")
|
|
17
|
+
MARKER = "setup.json"
|
|
18
|
+
EXAMPLE = ("suken-sync add --host linux-box --remote /home/dev/my_project "
|
|
19
|
+
"--local /Users/me/Downloads_linux-box/my_project")
|
|
20
|
+
FIRST_SYNC_OK = (0, 1)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def setup_done():
|
|
24
|
+
return read_json(config_dir() / MARKER, {}).get("unison") == VERSION
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def setup_problems(root, bin_dir):
|
|
28
|
+
problems = []
|
|
29
|
+
if system_key() not in ASSETS and not os.environ.get("SUKEN_SYNC_UNISON_DIR"):
|
|
30
|
+
problems.append(f"máy {system_key()[0]} {system_key()[1]} không được hỗ trợ (chỉ macOS và Linux x86_64)")
|
|
31
|
+
for tool in ("ssh", "scp"):
|
|
32
|
+
if not shutil.which(tool):
|
|
33
|
+
problems.append(f"thiếu lệnh `{tool}`: cài OpenSSH client")
|
|
34
|
+
problem = service.manager_problem()
|
|
35
|
+
if problem:
|
|
36
|
+
problems.append(problem)
|
|
37
|
+
if bin_dir is None:
|
|
38
|
+
problems.append("chưa tải được Unison (xem cảnh báo ở trên), chạy lại khi có mạng")
|
|
39
|
+
else:
|
|
40
|
+
text = version_text(bin_dir / "unison")
|
|
41
|
+
if VERSION not in text:
|
|
42
|
+
problems.append(f"Unison ở {bin_dir} không chạy được hoặc sai bản (cần {VERSION}): {text or 'không có đầu ra'}")
|
|
43
|
+
if sys.platform == "darwin" and not os.access(bin_dir / "unison-fsmonitor", os.X_OK):
|
|
44
|
+
problems.append(f"thiếu unison-fsmonitor chạy được ở {bin_dir}: macOS cần nó để sync tức thì")
|
|
45
|
+
if not installed(root):
|
|
46
|
+
problems.append(f"hook SessionStart chưa cài trong {settings_path(root)}")
|
|
47
|
+
return problems
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cmd_setup(args):
|
|
51
|
+
root = Path(args.dir).resolve()
|
|
52
|
+
if args.remove:
|
|
53
|
+
print(f"Đã gỡ hook: {install_hook(root, remove=True)}")
|
|
54
|
+
print("Các phiên đã thêm vẫn chạy; tháo từng phiên bằng `suken-sync remove <tên>`.")
|
|
55
|
+
return
|
|
56
|
+
bin_dir = None
|
|
57
|
+
try:
|
|
58
|
+
bin_dir = local_bin()
|
|
59
|
+
print(f"Unison {VERSION}: {bin_dir}")
|
|
60
|
+
except (OSError, SystemExit) as e:
|
|
61
|
+
print(f"⚠️ Chưa cài được Unison ({e})")
|
|
62
|
+
print(f"Đã cài hook SessionStart: {install_hook(root)}")
|
|
63
|
+
problems = setup_problems(root, bin_dir)
|
|
64
|
+
if problems:
|
|
65
|
+
raise SystemExit("❌ Setup CHƯA xong, còn thiếu:\n - " + "\n - ".join(problems) + "\nSửa rồi chạy lại `suken-sync setup`.")
|
|
66
|
+
write_json(config_dir() / MARKER, {"version": __version__, "unison": VERSION})
|
|
67
|
+
print("✅ Setup xong: Unison, dịch vụ nền và hook SessionStart đều sẵn sàng.\n")
|
|
68
|
+
print(general_guide())
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def derive_name(args):
|
|
72
|
+
if args.name:
|
|
73
|
+
return args.name
|
|
74
|
+
base = Path((args.remote or "").rstrip("/")).name
|
|
75
|
+
return re.sub(r"[^A-Za-z0-9._-]+", "-", base).strip("-.")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def add_problems(args):
|
|
79
|
+
problems = []
|
|
80
|
+
if not args.host:
|
|
81
|
+
problems.append("thiếu --host: tên SSH của máy Linux (trong ~/.ssh/config hoặc user@host), vd linux-box")
|
|
82
|
+
elif not HOST.match(args.host):
|
|
83
|
+
problems.append(f"--host '{args.host}' không hợp lệ: chỉ gồm chữ, số, . _ - @ và không bắt đầu bằng ký tự đặc biệt")
|
|
84
|
+
paths = (("--remote", args.remote, "đường dẫn TUYỆT ĐỐI của thư mục trên máy Linux, vd /home/dev/my_project"),
|
|
85
|
+
("--local", args.local, "đường dẫn TUYỆT ĐỐI của thư mục sẽ chứa bản sao trên máy này (cũng viết --remote-Mac), "
|
|
86
|
+
"vd /Users/me/Downloads_linux-box/my_project"))
|
|
87
|
+
for flag, value, meaning in paths:
|
|
88
|
+
if not value:
|
|
89
|
+
problems.append(f"thiếu {flag}: {meaning}")
|
|
90
|
+
elif not value.startswith("/") or value.rstrip("/") == "" or not PATH_CHARS.match(value):
|
|
91
|
+
problems.append(f"{flag} '{value}' phải là đường dẫn tuyệt đối (bắt đầu bằng /), không phải thư mục gốc, "
|
|
92
|
+
"không có khoảng trắng hay ký tự đặc biệt")
|
|
93
|
+
if args.threshold and parse_size(args.threshold) is None:
|
|
94
|
+
problems.append(f"--threshold '{args.threshold}' không hiểu: viết như 10MB, 500KB, 2GB")
|
|
95
|
+
if args.remote:
|
|
96
|
+
name = derive_name(args)
|
|
97
|
+
if not NAME.match(name):
|
|
98
|
+
problems.append(f"không đặt được tên phiên từ '{args.remote}': thêm --name (chữ, số, . _ -)")
|
|
99
|
+
elif name in profiles.load_all():
|
|
100
|
+
problems.append(f"đã có phiên '{name}': dùng --name khác hoặc `suken-sync remove {name}` trước")
|
|
101
|
+
if args.local and PATH_CHARS.match(args.local) and args.local.startswith("/"):
|
|
102
|
+
if Path(args.local).is_file():
|
|
103
|
+
problems.append(f"--local '{args.local}' là một file, cần là thư mục")
|
|
104
|
+
if Path(args.local).resolve() == Path.home().resolve():
|
|
105
|
+
problems.append("--local không được là thư mục home, hãy chọn thư mục riêng cho bản sao")
|
|
106
|
+
for other in profiles.overlapping(args.local):
|
|
107
|
+
problems.append(f"--local trùng hoặc lồng với phiên '{other['name']}' ({other['local']})")
|
|
108
|
+
return problems
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def log_tail(done, name=None):
|
|
112
|
+
text = (done.stdout + "\n" + done.stderr).strip()
|
|
113
|
+
log = profiles.logs_dir() / f"{name}.log" if name else None
|
|
114
|
+
if log and log.is_file():
|
|
115
|
+
text += "\n--- log Unison (cuối):\n" + "\n".join(log.read_text(encoding="utf-8", errors="replace").splitlines()[-15:])
|
|
116
|
+
return "\n".join(text.splitlines()[-20:])
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def status_problems(profile):
|
|
120
|
+
name = profile["name"]
|
|
121
|
+
problems = []
|
|
122
|
+
if not service.wait_active(name, 10):
|
|
123
|
+
problems.append(f"dịch vụ nền '{name}' không chạy ({service.unit_path(name)}); xem log ở {profiles.logs_dir()}")
|
|
124
|
+
try:
|
|
125
|
+
done = run_unison(name, [name, "-testserver"], timeout=90)
|
|
126
|
+
if done.returncode:
|
|
127
|
+
problems.append(f"Unison không nối được máy Linux '{profile['host']}' (VPN/mạng?): {log_tail(done)}")
|
|
128
|
+
except subprocess.TimeoutExpired:
|
|
129
|
+
problems.append(f"Unison nối máy Linux '{profile['host']}' quá 90 giây không xong (VPN/mạng?)")
|
|
130
|
+
if not Path(profile["local"]).is_dir():
|
|
131
|
+
problems.append(f"thư mục {profile['local']} không còn")
|
|
132
|
+
elif not installed(profile["local"]):
|
|
133
|
+
problems.append(f"hook SessionStart chưa cài trong {settings_path(profile['local'])}")
|
|
134
|
+
return problems
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def cmd_add(args):
|
|
138
|
+
problems = add_problems(args)
|
|
139
|
+
if problems:
|
|
140
|
+
raise SystemExit("Chưa thêm — còn thiếu hoặc sai:\n - " + "\n - ".join(problems) +
|
|
141
|
+
f"\nVí dụ đủ tham số:\n {EXAMPLE}\nHỏi user giá trị chưa biết, đừng tự đoán.")
|
|
142
|
+
name = derive_name(args)
|
|
143
|
+
remote = args.remote.rstrip("/")
|
|
144
|
+
info = probe(args.host, remote)
|
|
145
|
+
if info["system"] != "Linux x86_64":
|
|
146
|
+
raise SystemExit(f"Máy '{args.host}' là {info['system']}; suken-sync chỉ cài Unison cho Linux x86_64.")
|
|
147
|
+
if info["mode"] == "NODIR":
|
|
148
|
+
raise SystemExit(f"Thư mục {remote} không có trên '{args.host}'. Kiểm tra lại --remote.")
|
|
149
|
+
ensure_remote(args.host, info["home"])
|
|
150
|
+
local = Path(args.local)
|
|
151
|
+
fresh = not local.exists() or not any(local.iterdir())
|
|
152
|
+
local.mkdir(parents=True, exist_ok=True)
|
|
153
|
+
if fresh:
|
|
154
|
+
try:
|
|
155
|
+
local.chmod(int(info["mode"], 8))
|
|
156
|
+
except (OSError, ValueError):
|
|
157
|
+
pass
|
|
158
|
+
profile = {"name": name, "host": args.host, "remote": remote, "local": str(local), "remote_home": info["home"],
|
|
159
|
+
"threshold_kb": parse_size(args.threshold or DEFAULT_THRESHOLD), "ignores": args.ignore or []}
|
|
160
|
+
rows = stubs.scan(profile)
|
|
161
|
+
profiles.save(profile)
|
|
162
|
+
shutil.rmtree(profiles.unison_home(name), ignore_errors=True)
|
|
163
|
+
reset_remote_state(args.host, info["home"], name)
|
|
164
|
+
write_prf(profile, {relative for relative, _ in rows})
|
|
165
|
+
print(f"Tìm thấy {len(rows)} file nặng bên Linux, bỏ ra khỏi đồng bộ.")
|
|
166
|
+
print("Đang đồng bộ lần đầu, có thể lâu nếu thư mục lớn ...", flush=True)
|
|
167
|
+
done = run_unison(name, [name])
|
|
168
|
+
if done.returncode not in FIRST_SYNC_OK:
|
|
169
|
+
message = f"❌ Đồng bộ lần đầu lỗi (mã {done.returncode}), đã huỷ phiên '{name}':\n{log_tail(done, name)}"
|
|
170
|
+
profiles.delete(name)
|
|
171
|
+
raise SystemExit(message)
|
|
172
|
+
print(next((line for line in reversed(done.stdout.splitlines()) if line.startswith("Synchronization complete")),
|
|
173
|
+
"Đồng bộ lần đầu xong"))
|
|
174
|
+
kept, removed = stubs.write(profile, rows)
|
|
175
|
+
print(f"Đã tạo {kept} file bóng cho file nặng (xoá {removed} bóng thừa)")
|
|
176
|
+
print(f"Đã cài dịch vụ nền: {service.install(profile)}")
|
|
177
|
+
print(f"Đã cài hook SessionStart: {install_hook(local)}")
|
|
178
|
+
problems = status_problems(profile)
|
|
179
|
+
if problems:
|
|
180
|
+
raise SystemExit(f"❌ Phiên '{name}' CHƯA xong, còn thiếu:\n - " + "\n - ".join(problems) +
|
|
181
|
+
f"\nSửa rồi chạy `suken-sync status {name}`.")
|
|
182
|
+
print(f"✅ Sync xong: {args.host}:{remote} ⇄ {local}\n")
|
|
183
|
+
print(synced_guide(profile))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def cmd_list(args):
|
|
187
|
+
for p in profiles.pick(None):
|
|
188
|
+
state = "đang chạy" if service.active(p["name"]) else "KHÔNG chạy"
|
|
189
|
+
print(f"{p['name']}: {p['host']}:{p['remote']} ⇄ {p['local']} (bỏ file từ {p['threshold_kb'] / 1024:g} MB, dịch vụ {state})")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def cmd_status(args):
|
|
193
|
+
bad = 0
|
|
194
|
+
for p in profiles.pick(args.name):
|
|
195
|
+
problems = status_problems(p)
|
|
196
|
+
shadows = len(stubs.existing(Path(p["local"]))) if Path(p["local"]).is_dir() else 0
|
|
197
|
+
if problems:
|
|
198
|
+
bad += 1
|
|
199
|
+
print(f"❌ {p['name']}:\n - " + "\n - ".join(problems))
|
|
200
|
+
else:
|
|
201
|
+
print(f"✅ {p['name']}: dịch vụ chạy, nối được '{p['host']}', {shadows} file bóng")
|
|
202
|
+
if bad:
|
|
203
|
+
raise SystemExit(1)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def cmd_refresh(args):
|
|
207
|
+
for p in profiles.pick(args.name):
|
|
208
|
+
rows = stubs.scan(p)
|
|
209
|
+
kept, removed = stubs.write(p, rows)
|
|
210
|
+
write_prf(p, {relative for relative, _ in rows})
|
|
211
|
+
if service.active(p["name"]):
|
|
212
|
+
service.restart(p["name"])
|
|
213
|
+
print(f"{p['name']}: {kept} file bóng cho file nặng bên Linux (xoá {removed} bóng thừa), đã nạp lại danh sách bỏ qua")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def cmd_remove(args):
|
|
217
|
+
for p in profiles.pick(args.name):
|
|
218
|
+
service.uninstall(p["name"])
|
|
219
|
+
drop_remote_state(p["host"], p["remote_home"], p["name"])
|
|
220
|
+
shadows = stubs.remove_all(p) if Path(p["local"]).is_dir() else 0
|
|
221
|
+
if Path(p["local"]).is_dir():
|
|
222
|
+
install_hook(p["local"], remove=True)
|
|
223
|
+
profiles.delete(p["name"])
|
|
224
|
+
print(f"Đã tháo '{p['name']}': dịch vụ, hook, {shadows} file bóng. Code ở {p['local']} và {p['host']}:{p['remote']} giữ nguyên.")
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def cmd_usage(args):
|
|
228
|
+
print(general_guide())
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class SetupOnlyParser(argparse.ArgumentParser):
|
|
232
|
+
def format_help(self):
|
|
233
|
+
return SETUP_HINT + "\n"
|
|
234
|
+
|
|
235
|
+
def format_usage(self):
|
|
236
|
+
return SETUP_HINT + "\n"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def main(argv=None):
|
|
240
|
+
parser = SetupOnlyParser(prog="suken-sync")
|
|
241
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
242
|
+
sub = parser.add_subparsers(dest="command", parser_class=argparse.ArgumentParser)
|
|
243
|
+
|
|
244
|
+
p = sub.add_parser("setup", help="cài Unison, hook SessionStart; in hướng dẫn dùng add")
|
|
245
|
+
p.add_argument("--dir", default=".", help="thư mục mở Claude Code, nơi cài hook (mặc định: thư mục hiện tại)")
|
|
246
|
+
p.add_argument("--remove", action="store_true", help="gỡ hook khỏi thư mục này")
|
|
247
|
+
p.set_defaults(func=cmd_setup)
|
|
248
|
+
|
|
249
|
+
p = sub.add_parser("add", allow_abbrev=False, help="thêm một thư mục Linux cần đồng bộ hai chiều (bắt buộc --host, --remote, --local)")
|
|
250
|
+
p.add_argument("--host", help="tên SSH của máy Linux (bắt buộc)")
|
|
251
|
+
p.add_argument("--remote", help="đường dẫn tuyệt đối của thư mục trên Linux (bắt buộc)")
|
|
252
|
+
p.add_argument("--local", "--remote-Mac", dest="local", help="đường dẫn tuyệt đối thư mục chứa bản sao trên máy này (bắt buộc)")
|
|
253
|
+
p.add_argument("--threshold", help=f"file từ cỡ này trở lên không đồng bộ (mặc định {DEFAULT_THRESHOLD})")
|
|
254
|
+
p.add_argument("--name", help="tên phiên (mặc định: tên thư mục cuối của --remote)")
|
|
255
|
+
p.add_argument("--ignore", action="append", help="mẫu Unison bỏ thêm, vd 'Name node_modules' (lặp lại được)")
|
|
256
|
+
p.set_defaults(func=cmd_add)
|
|
257
|
+
|
|
258
|
+
sub.add_parser("list", help="liệt kê các phiên đã thêm").set_defaults(func=cmd_list)
|
|
259
|
+
|
|
260
|
+
p = sub.add_parser("status", help="kiểm dịch vụ và kết nối của phiên (thoát mã 1 nếu có vấn đề)")
|
|
261
|
+
p.add_argument("name", nargs="?")
|
|
262
|
+
p.set_defaults(func=cmd_status)
|
|
263
|
+
|
|
264
|
+
p = sub.add_parser("refresh", help="quét file nặng mới bên Linux và cập nhật file bóng")
|
|
265
|
+
p.add_argument("name", nargs="?")
|
|
266
|
+
p.set_defaults(func=cmd_refresh)
|
|
267
|
+
|
|
268
|
+
p = sub.add_parser("remove", help="tháo một phiên: dịch vụ, hook, file bóng (không xoá code)")
|
|
269
|
+
p.add_argument("name")
|
|
270
|
+
p.set_defaults(func=cmd_remove)
|
|
271
|
+
|
|
272
|
+
sub.add_parser("usage", help="in hướng dẫn cho agent").set_defaults(func=cmd_usage)
|
|
273
|
+
|
|
274
|
+
args = parser.parse_args(argv)
|
|
275
|
+
if not getattr(args, "func", None):
|
|
276
|
+
print(SETUP_HINT)
|
|
277
|
+
return
|
|
278
|
+
if args.command not in ("setup", "usage") and not setup_done():
|
|
279
|
+
raise SystemExit(SETUP_HINT)
|
|
280
|
+
args.func(args)
|
suken_sync/common.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
STUB_SUFFIX = ".linux-only.txt"
|
|
9
|
+
STUB_MARK = "[BÓNG]"
|
|
10
|
+
DEFAULT_THRESHOLD = "10MB"
|
|
11
|
+
NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
|
12
|
+
HOST = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._@-]*$")
|
|
13
|
+
PATH_CHARS = re.compile(r"^[^\s'\"\\$`;&|<>*?]+$")
|
|
14
|
+
SIZE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*(KB|MB|GB)?\s*$", re.IGNORECASE)
|
|
15
|
+
UNITS = {"KB": 1, "MB": 1024, "GB": 1024 * 1024}
|
|
16
|
+
SSH_OPTIONS = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=20"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def root_override():
|
|
20
|
+
value = os.environ.get("SUKEN_SYNC_HOME")
|
|
21
|
+
return Path(value) if value else None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def xdg(name, fallback):
|
|
25
|
+
return Path(os.environ.get(name) or Path.home() / fallback)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def config_dir():
|
|
29
|
+
root = root_override()
|
|
30
|
+
if root:
|
|
31
|
+
return root / "config"
|
|
32
|
+
if sys.platform == "darwin":
|
|
33
|
+
return Path.home() / "Library" / "Application Support" / "suken-sync"
|
|
34
|
+
return xdg("XDG_CONFIG_HOME", ".config") / "suken-sync"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cache_dir():
|
|
38
|
+
root = root_override()
|
|
39
|
+
if root:
|
|
40
|
+
return root / "cache"
|
|
41
|
+
if sys.platform == "darwin":
|
|
42
|
+
return Path.home() / "Library" / "Caches" / "suken-sync"
|
|
43
|
+
return xdg("XDG_CACHE_HOME", ".cache") / "suken-sync"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def services_dir():
|
|
47
|
+
root = root_override()
|
|
48
|
+
if root:
|
|
49
|
+
return root / "services"
|
|
50
|
+
if sys.platform == "darwin":
|
|
51
|
+
return Path.home() / "Library" / "LaunchAgents"
|
|
52
|
+
return xdg("XDG_CONFIG_HOME", ".config") / "systemd" / "user"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def read_json(path, empty):
|
|
56
|
+
return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else empty
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def write_json(path, data):
|
|
60
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
temp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
|
62
|
+
temp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
63
|
+
os.replace(temp, path)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_size(text):
|
|
67
|
+
match = SIZE.match(text or "")
|
|
68
|
+
if not match:
|
|
69
|
+
return None
|
|
70
|
+
kilobytes = int(float(match.group(1)) * UNITS[(match.group(2) or "MB").upper()])
|
|
71
|
+
return kilobytes if kilobytes > 0 else None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def format_size(size):
|
|
75
|
+
for unit in ("B", "KB", "MB", "GB"):
|
|
76
|
+
if size < 1024 or unit == "GB":
|
|
77
|
+
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
|
78
|
+
size /= 1024
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def ssh(host, command, timeout=60):
|
|
82
|
+
try:
|
|
83
|
+
return subprocess.run(["ssh", *SSH_OPTIONS, host, command], capture_output=True, text=True, timeout=timeout)
|
|
84
|
+
except FileNotFoundError:
|
|
85
|
+
raise SystemExit("Máy này không có lệnh `ssh`. Cài OpenSSH client rồi chạy lại.")
|
|
86
|
+
except subprocess.TimeoutExpired:
|
|
87
|
+
raise SystemExit(f"ssh tới '{host}' quá {timeout} giây không trả lời (VPN hoặc mạng đang chập chờn?).")
|
suken_sync/hook.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
from importlib.resources import files
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .common import read_json
|
|
8
|
+
from .profiles import covering
|
|
9
|
+
|
|
10
|
+
HOOK_MODULE = "suken_sync.hook"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def hook_command():
|
|
14
|
+
return f'"{sys.executable}" -m {HOOK_MODULE}'
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def settings_path(directory):
|
|
18
|
+
return Path(directory) / ".claude" / "settings.local.json"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def is_sync_hook(entry):
|
|
22
|
+
return any(HOOK_MODULE in h.get("command", "") for h in entry.get("hooks", []))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def installed(directory):
|
|
26
|
+
hooks = read_json(settings_path(directory), {}).get("hooks") or {}
|
|
27
|
+
return any(is_sync_hook(entry) for entry in hooks.get("SessionStart", []))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def install_hook(directory, remove=False):
|
|
31
|
+
path = settings_path(directory)
|
|
32
|
+
if remove and not path.is_file():
|
|
33
|
+
return path
|
|
34
|
+
data = read_json(path, {})
|
|
35
|
+
hooks = data.get("hooks", {})
|
|
36
|
+
kept = [entry for entry in hooks.get("SessionStart", []) if not is_sync_hook(entry)]
|
|
37
|
+
if not remove:
|
|
38
|
+
kept.append({"hooks": [{"type": "command", "command": hook_command(), "timeout": 10}]})
|
|
39
|
+
if kept:
|
|
40
|
+
hooks["SessionStart"] = kept
|
|
41
|
+
else:
|
|
42
|
+
hooks.pop("SessionStart", None)
|
|
43
|
+
if hooks:
|
|
44
|
+
data["hooks"] = hooks
|
|
45
|
+
else:
|
|
46
|
+
data.pop("hooks", None)
|
|
47
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
49
|
+
return path
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def text(name):
|
|
53
|
+
return files("suken_sync").joinpath(name).read_text(encoding="utf-8")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def general_guide():
|
|
57
|
+
return text("GUIDE.md")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def synced_guide(profile):
|
|
61
|
+
values = {"{name}": profile["name"], "{host}": profile["host"], "{remote}": profile["remote"],
|
|
62
|
+
"{local}": profile["local"], "{threshold}": f"{profile['threshold_kb'] / 1024:g} MB"}
|
|
63
|
+
guide = text("SYNCED.md")
|
|
64
|
+
for key, value in values.items():
|
|
65
|
+
guide = guide.replace(key, value)
|
|
66
|
+
return guide
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def main():
|
|
70
|
+
try:
|
|
71
|
+
payload = json.load(sys.stdin)
|
|
72
|
+
matched = covering(payload.get("cwd") or os.getcwd())
|
|
73
|
+
print("\n\n".join(synced_guide(p) for p in matched) if matched else general_guide())
|
|
74
|
+
except Exception:
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
if __name__ == "__main__":
|
|
79
|
+
main()
|
suken_sync/profiles.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from .common import config_dir, read_json, write_json
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def profiles_dir():
|
|
8
|
+
return config_dir() / "profiles"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def unison_home(name):
|
|
12
|
+
return config_dir() / "unison" / name
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def logs_dir():
|
|
16
|
+
return config_dir() / "logs"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def load_all():
|
|
20
|
+
folder = profiles_dir()
|
|
21
|
+
if not folder.is_dir():
|
|
22
|
+
return {}
|
|
23
|
+
return {path.stem: read_json(path, {}) for path in sorted(folder.glob("*.json"))}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def save(profile):
|
|
27
|
+
write_json(profiles_dir() / f"{profile['name']}.json", profile)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def delete(name):
|
|
31
|
+
(profiles_dir() / f"{name}.json").unlink(missing_ok=True)
|
|
32
|
+
shutil.rmtree(unison_home(name), ignore_errors=True)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def inside(path, root):
|
|
36
|
+
path, root = Path(path).resolve(), Path(root).resolve()
|
|
37
|
+
return path == root or root in path.parents
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def covering(path):
|
|
41
|
+
return [p for p in load_all().values() if inside(path, p["local"])]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def overlapping(local):
|
|
45
|
+
return [p for p in load_all().values() if inside(local, p["local"]) or inside(p["local"], local)]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pick(name):
|
|
49
|
+
found = load_all()
|
|
50
|
+
if name is None:
|
|
51
|
+
if not found:
|
|
52
|
+
raise SystemExit("Chưa có phiên đồng bộ nào. Thêm bằng `suken-sync add` (xem `suken-sync usage`).")
|
|
53
|
+
return list(found.values())
|
|
54
|
+
if name not in found:
|
|
55
|
+
have = ", ".join(found) or "chưa có phiên nào"
|
|
56
|
+
raise SystemExit(f"Không có phiên '{name}'. Đang có: {have}.")
|
|
57
|
+
return [found[name]]
|
suken_sync/service.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import plistlib
|
|
3
|
+
import shlex
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from .common import root_override, services_dir
|
|
9
|
+
from .profiles import logs_dir, unison_home
|
|
10
|
+
from .unison import local_bin
|
|
11
|
+
|
|
12
|
+
LABEL = "com.suken-sync.{}"
|
|
13
|
+
UNIT = "suken-sync-{}.service"
|
|
14
|
+
RESTART_WAIT_S = 15
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def macos():
|
|
18
|
+
return sys.platform == "darwin"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def unit_path(name):
|
|
22
|
+
return services_dir() / ((LABEL + ".plist").format(name) if macos() else UNIT.format(name))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def command(profile):
|
|
26
|
+
return [sys.executable, "-m", "suken_sync.watch", profile["name"]]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def environment(name):
|
|
30
|
+
env = {"UNISON": str(unison_home(name)), "PATH": f"{local_bin()}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"}
|
|
31
|
+
if root_override():
|
|
32
|
+
env["SUKEN_SYNC_HOME"] = str(root_override())
|
|
33
|
+
return env
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def render(profile):
|
|
37
|
+
name = profile["name"]
|
|
38
|
+
if macos():
|
|
39
|
+
return plistlib.dumps({
|
|
40
|
+
"Label": LABEL.format(name),
|
|
41
|
+
"ProgramArguments": command(profile),
|
|
42
|
+
"EnvironmentVariables": environment(name),
|
|
43
|
+
"RunAtLoad": True,
|
|
44
|
+
"KeepAlive": True,
|
|
45
|
+
"ThrottleInterval": RESTART_WAIT_S,
|
|
46
|
+
"StandardOutPath": str(logs_dir() / f"{name}.out"),
|
|
47
|
+
"StandardErrorPath": str(logs_dir() / f"{name}.err"),
|
|
48
|
+
})
|
|
49
|
+
env = "\n".join(f'Environment="{key}={value}"' for key, value in environment(name).items())
|
|
50
|
+
return (f"[Unit]\nDescription=suken-sync {name}\nAfter=network-online.target\n\n"
|
|
51
|
+
f"[Service]\nExecStart={shlex.join(command(profile))}\n{env}\nRestart=always\nRestartSec={RESTART_WAIT_S}\n\n"
|
|
52
|
+
"[Install]\nWantedBy=default.target\n").encode("utf-8")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def run(arguments):
|
|
56
|
+
return subprocess.run(arguments, capture_output=True, text=True)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def domain():
|
|
60
|
+
return f"gui/{os.getuid()}"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def start(name):
|
|
64
|
+
if macos():
|
|
65
|
+
run(["launchctl", "bootout", f"{domain()}/{LABEL.format(name)}"])
|
|
66
|
+
done = run(["launchctl", "bootstrap", domain(), str(unit_path(name))])
|
|
67
|
+
else:
|
|
68
|
+
run(["systemctl", "--user", "daemon-reload"])
|
|
69
|
+
done = run(["systemctl", "--user", "enable", "--now", str(unit_path(name))])
|
|
70
|
+
if done.returncode:
|
|
71
|
+
raise SystemExit(f"Không bật được dịch vụ nền '{name}': {(done.stderr or done.stdout).strip()}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def restart(name):
|
|
75
|
+
if macos():
|
|
76
|
+
done = run(["launchctl", "kickstart", "-k", f"{domain()}/{LABEL.format(name)}"])
|
|
77
|
+
else:
|
|
78
|
+
done = run(["systemctl", "--user", "restart", UNIT.format(name)])
|
|
79
|
+
if done.returncode:
|
|
80
|
+
raise SystemExit(f"Không khởi động lại được dịch vụ nền '{name}': {(done.stderr or done.stdout).strip()}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def stop(name):
|
|
84
|
+
if macos():
|
|
85
|
+
run(["launchctl", "bootout", f"{domain()}/{LABEL.format(name)}"])
|
|
86
|
+
else:
|
|
87
|
+
run(["systemctl", "--user", "disable", "--now", UNIT.format(name)])
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def active(name):
|
|
91
|
+
if macos():
|
|
92
|
+
done = run(["launchctl", "print", f"{domain()}/{LABEL.format(name)}"])
|
|
93
|
+
return done.returncode == 0 and "state = running" in done.stdout
|
|
94
|
+
return run(["systemctl", "--user", "is-active", UNIT.format(name)]).stdout.strip() == "active"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def wait_active(name, seconds=10):
|
|
98
|
+
deadline = time.monotonic() + seconds
|
|
99
|
+
while time.monotonic() < deadline:
|
|
100
|
+
if active(name):
|
|
101
|
+
return True
|
|
102
|
+
time.sleep(0.5)
|
|
103
|
+
return active(name)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def install(profile):
|
|
107
|
+
path = unit_path(profile["name"])
|
|
108
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
path.write_bytes(render(profile))
|
|
110
|
+
start(profile["name"])
|
|
111
|
+
return path
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def uninstall(name):
|
|
115
|
+
stop(name)
|
|
116
|
+
unit_path(name).unlink(missing_ok=True)
|
|
117
|
+
if not macos():
|
|
118
|
+
run(["systemctl", "--user", "daemon-reload"])
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def manager_problem():
|
|
122
|
+
if macos():
|
|
123
|
+
return None if run(["which", "launchctl"]).returncode == 0 else "không có `launchctl` để chạy dịch vụ nền"
|
|
124
|
+
done = run(["systemctl", "--user", "show-environment"])
|
|
125
|
+
if done.returncode:
|
|
126
|
+
return ("`systemctl --user` không dùng được (cần systemd user session) nên không chạy được dịch vụ nền: "
|
|
127
|
+
f"{(done.stderr or done.stdout).strip()}")
|
|
128
|
+
return None
|
suken_sync/stubs.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shlex
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from .common import STUB_MARK, STUB_SUFFIX, format_size, ssh
|
|
6
|
+
from .profiles import inside
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def limit(profile):
|
|
10
|
+
return profile["threshold_kb"] * 1000
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def find_command(profile):
|
|
14
|
+
return f"find {shlex.quote(profile['remote'])} -type f -size +{limit(profile) - 1}c -printf '%s\\t%P\\n'"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse(lines, profile):
|
|
18
|
+
rows = []
|
|
19
|
+
for line in lines:
|
|
20
|
+
size, _, relative = line.partition("\t")
|
|
21
|
+
if size.isdigit() and relative and int(size) >= limit(profile):
|
|
22
|
+
rows.append((relative, int(size)))
|
|
23
|
+
return rows
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def scan(profile):
|
|
27
|
+
done = ssh(profile["host"], find_command(profile), timeout=300)
|
|
28
|
+
if done.returncode != 0 and not done.stdout:
|
|
29
|
+
raise SystemExit(f"Không quét được file nặng trên '{profile['host']}': {done.stderr.strip()}")
|
|
30
|
+
return parse(done.stdout.splitlines(), profile)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def render(profile, relative, size):
|
|
34
|
+
return (f"{STUB_MARK} Đây không phải file thật, chỉ là tấm thẻ báo file này tồn tại.\n"
|
|
35
|
+
f"File thật: {relative} ({format_size(size)})\n"
|
|
36
|
+
f"Nằm ở máy Linux \"{profile['host']}\": {profile['remote']}/{relative}\n"
|
|
37
|
+
"Không tải về, không build lại, không coi là file lỗi. "
|
|
38
|
+
f"Cần đọc hay chạy nó thì làm bên Linux: ssh {profile['host']}\n")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def existing(local):
|
|
42
|
+
found = []
|
|
43
|
+
for folder, _, names in os.walk(local):
|
|
44
|
+
for name in names:
|
|
45
|
+
path = Path(folder) / name
|
|
46
|
+
if name.endswith(STUB_SUFFIX) and is_stub(path):
|
|
47
|
+
found.append(path)
|
|
48
|
+
return found
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def is_stub(path):
|
|
52
|
+
try:
|
|
53
|
+
with open(path, encoding="utf-8") as f:
|
|
54
|
+
return f.readline().startswith(STUB_MARK)
|
|
55
|
+
except (OSError, UnicodeDecodeError):
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def write(profile, rows):
|
|
60
|
+
local = Path(profile["local"])
|
|
61
|
+
wanted = {}
|
|
62
|
+
for relative, size in rows:
|
|
63
|
+
stub = local / (relative + STUB_SUFFIX)
|
|
64
|
+
if inside(stub, local):
|
|
65
|
+
wanted[stub] = render(profile, relative, size)
|
|
66
|
+
for stub, text in wanted.items():
|
|
67
|
+
if stub.is_file() and stub.read_text(encoding="utf-8") == text:
|
|
68
|
+
continue
|
|
69
|
+
stub.parent.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
stub.write_text(text, encoding="utf-8")
|
|
71
|
+
removed = 0
|
|
72
|
+
for old in existing(local):
|
|
73
|
+
if old not in wanted:
|
|
74
|
+
old.unlink()
|
|
75
|
+
removed += 1
|
|
76
|
+
return len(wanted), removed
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def remove_all(profile):
|
|
80
|
+
count = 0
|
|
81
|
+
for stub in existing(Path(profile["local"])):
|
|
82
|
+
stub.unlink()
|
|
83
|
+
count += 1
|
|
84
|
+
return count
|
suken_sync/unison.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import os
|
|
3
|
+
import platform
|
|
4
|
+
import re
|
|
5
|
+
import shlex
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import tarfile
|
|
9
|
+
import urllib.request
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .common import SSH_OPTIONS, STUB_SUFFIX, cache_dir, ssh
|
|
13
|
+
from .profiles import logs_dir, unison_home
|
|
14
|
+
|
|
15
|
+
VERSION = "2.54.0"
|
|
16
|
+
URL = "https://github.com/bcpierce00/unison/releases/download/v{version}/unison-{version}-{asset}.tar.gz"
|
|
17
|
+
ASSETS = {
|
|
18
|
+
("Darwin", "arm64"): ("macos-arm64", "51cc9ad9f014e5c2ce0876bd9e398bd3cf6e671930d1193d7bc7e4a4b90a791f"),
|
|
19
|
+
("Darwin", "x86_64"): ("macos-x86-64", "4c921bd555e03b47ec4f2e2fadc37acc4cd33b00e4e25b3dbb23454dd60338fe"),
|
|
20
|
+
("Linux", "x86_64"): ("ubuntu-22.04-x86_64-static", "d279dff18682c909d3ddb0b280ab151229b4798b9399b1d227084da424337d24"),
|
|
21
|
+
}
|
|
22
|
+
FSMONITOR_VERSION = "0.3.9"
|
|
23
|
+
FSMONITOR_URL = "https://github.com/autozimu/unison-fsmonitor/releases/download/v{version}/unison-fsmonitor-macos-{arch}.tar.gz"
|
|
24
|
+
FSMONITOR_ASSETS = {
|
|
25
|
+
"arm64": ("aarch64", "13418727fbd2aae950eb4d6f357cfa76a61e7f7aa9986a666ce27a6b323bc68d"),
|
|
26
|
+
"x86_64": ("amd64", "79197d15f3a39c25a76f2188e24c8d4163e4e2b1442ffd98b04ff3761bc76dcd"),
|
|
27
|
+
}
|
|
28
|
+
REMOTE_REL = f".cache/suken-sync/unison-{VERSION}"
|
|
29
|
+
REMOTE_STATE_REL = ".cache/suken-sync/state"
|
|
30
|
+
LINUX = ("Linux", "x86_64")
|
|
31
|
+
SHIPPED = ("unison", "unison-fsmonitor")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def system_key():
|
|
35
|
+
return (platform.system(), platform.machine())
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def sha256(path):
|
|
39
|
+
with open(path, "rb") as f:
|
|
40
|
+
return hashlib.sha256(f.read()).hexdigest()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def download(url, digest, label):
|
|
44
|
+
cache_dir().mkdir(parents=True, exist_ok=True)
|
|
45
|
+
part = cache_dir() / f"download.{os.getpid()}.part"
|
|
46
|
+
print(f"Đang tải {label} ...", flush=True)
|
|
47
|
+
urllib.request.urlretrieve(url, part)
|
|
48
|
+
if sha256(part) != digest:
|
|
49
|
+
part.unlink()
|
|
50
|
+
raise SystemExit(f"{label} tải về sai mã băm (file hỏng hoặc bị thay), đã xoá: {url}")
|
|
51
|
+
return part
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def extract(archive, staging):
|
|
55
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
56
|
+
with tarfile.open(archive) as tar:
|
|
57
|
+
if hasattr(tarfile, "data_filter"):
|
|
58
|
+
tar.extractall(staging, filter="data")
|
|
59
|
+
else:
|
|
60
|
+
tar.extractall(staging)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def unison_folder(key):
|
|
64
|
+
name, digest = ASSETS[key]
|
|
65
|
+
folder = cache_dir() / f"unison-{VERSION}-{name}"
|
|
66
|
+
if not (folder / "bin" / "unison").is_file():
|
|
67
|
+
archive = download(URL.format(version=VERSION, asset=name), digest, f"Unison {VERSION} (~4 MB)")
|
|
68
|
+
staging = cache_dir() / f"unison.{os.getpid()}.unpack"
|
|
69
|
+
extract(archive, staging)
|
|
70
|
+
archive.unlink()
|
|
71
|
+
inner = next(p for p in staging.iterdir() if p.is_dir())
|
|
72
|
+
shutil.rmtree(folder, ignore_errors=True)
|
|
73
|
+
try:
|
|
74
|
+
inner.rename(folder)
|
|
75
|
+
except OSError:
|
|
76
|
+
if not folder.exists():
|
|
77
|
+
raise
|
|
78
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
79
|
+
(folder / "bin" / "unison").chmod(0o755)
|
|
80
|
+
return folder / "bin"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def ensure_fsmonitor(bin_dir, machine):
|
|
84
|
+
target = bin_dir / "unison-fsmonitor"
|
|
85
|
+
if not target.is_file():
|
|
86
|
+
arch, digest = FSMONITOR_ASSETS[machine]
|
|
87
|
+
archive = download(FSMONITOR_URL.format(version=FSMONITOR_VERSION, arch=arch), digest,
|
|
88
|
+
f"unison-fsmonitor {FSMONITOR_VERSION} cho macOS (~2 MB)")
|
|
89
|
+
staging = cache_dir() / f"fsmonitor.{os.getpid()}.unpack"
|
|
90
|
+
extract(archive, staging)
|
|
91
|
+
archive.unlink()
|
|
92
|
+
shutil.move(str(staging / "unison-fsmonitor"), str(target))
|
|
93
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
94
|
+
target.chmod(0o755)
|
|
95
|
+
return target
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def local_bin():
|
|
99
|
+
override = os.environ.get("SUKEN_SYNC_UNISON_DIR")
|
|
100
|
+
if override:
|
|
101
|
+
return Path(override)
|
|
102
|
+
key = system_key()
|
|
103
|
+
if key not in ASSETS:
|
|
104
|
+
raise SystemExit(f"suken-sync chỉ chạy trên macOS (Apple Silicon hoặc Intel) và Linux x86_64, máy này là {key[0]} {key[1]}. "
|
|
105
|
+
"Tự cài Unison cùng bản rồi đặt SUKEN_SYNC_UNISON_DIR trỏ tới thư mục chứa file unison.")
|
|
106
|
+
bin_dir = unison_folder(key)
|
|
107
|
+
if key[0] == "Darwin":
|
|
108
|
+
ensure_fsmonitor(bin_dir, key[1])
|
|
109
|
+
return bin_dir
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def linux_bin():
|
|
113
|
+
override = os.environ.get("SUKEN_SYNC_REMOTE_UNISON_DIR")
|
|
114
|
+
if override:
|
|
115
|
+
return Path(override)
|
|
116
|
+
if system_key() == LINUX:
|
|
117
|
+
return local_bin()
|
|
118
|
+
return unison_folder(LINUX)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def version_text(binary):
|
|
122
|
+
try:
|
|
123
|
+
done = subprocess.run([str(binary), "-version"], capture_output=True, text=True, timeout=30)
|
|
124
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
125
|
+
return ""
|
|
126
|
+
return done.stdout.strip() if done.returncode == 0 else ""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def environment(name):
|
|
130
|
+
return {**os.environ, "UNISON": str(unison_home(name)), "PATH": f"{local_bin()}{os.pathsep}{os.environ.get('PATH', '')}"}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def run_unison(name, arguments, timeout=None):
|
|
134
|
+
return subprocess.run([str(local_bin() / "unison"), *arguments], capture_output=True, text=True, env=environment(name), timeout=timeout)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def probe(host, remote):
|
|
138
|
+
quoted = shlex.quote(remote)
|
|
139
|
+
command = f'uname -sm; printf "%s\\n" "$HOME"; if [ -d {quoted} ]; then stat -c %a {quoted}; else echo NODIR; fi'
|
|
140
|
+
done = ssh(host, command)
|
|
141
|
+
if done.returncode != 0:
|
|
142
|
+
raise SystemExit(f"Không nối được ssh tới '{host}': {done.stderr.strip() or 'không có thông báo'}\n"
|
|
143
|
+
f"Kiểm tra VPN/mạng; `ssh {host}` phải vào được bằng key, không hỏi mật khẩu.")
|
|
144
|
+
lines = done.stdout.splitlines()
|
|
145
|
+
if len(lines) < 3:
|
|
146
|
+
raise SystemExit(f"Máy '{host}' trả lời lạ khi dò thư mục: {done.stdout!r}")
|
|
147
|
+
return {"system": lines[0].strip(), "home": lines[1].strip(), "mode": lines[2].strip()}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def remote_base(home):
|
|
151
|
+
return f"{home}/{REMOTE_REL}"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def ensure_remote(host, home):
|
|
155
|
+
base = remote_base(home)
|
|
156
|
+
check = ssh(host, f"{shlex.quote(base)}/bin/unison -version")
|
|
157
|
+
if check.returncode == 0 and VERSION in check.stdout:
|
|
158
|
+
return base
|
|
159
|
+
print(f"Đang cài Unison {VERSION} lên '{host}' (thư mục riêng ~/{REMOTE_REL}, không đụng gì khác) ...", flush=True)
|
|
160
|
+
prepare = ssh(host, f"rm -rf {shlex.quote(base)} && mkdir -p {shlex.quote(base)}/bin")
|
|
161
|
+
if prepare.returncode:
|
|
162
|
+
raise SystemExit(f"Không tạo được thư mục cài Unison trên '{host}': {prepare.stderr.strip()}")
|
|
163
|
+
files = [str(f) for f in (linux_bin() / name for name in SHIPPED) if f.is_file()]
|
|
164
|
+
copy = subprocess.run(["scp", "-q", *SSH_OPTIONS, *files, f"{host}:{REMOTE_REL}/bin/"], capture_output=True, text=True)
|
|
165
|
+
if copy.returncode:
|
|
166
|
+
raise SystemExit(f"Không chép được Unison lên '{host}': {copy.stderr.strip()}")
|
|
167
|
+
ssh(host, f"chmod +x {shlex.quote(base)}/bin/*")
|
|
168
|
+
check = ssh(host, f"{shlex.quote(base)}/bin/unison -version")
|
|
169
|
+
if check.returncode or VERSION not in check.stdout:
|
|
170
|
+
raise SystemExit(f"Đã chép Unison {VERSION} lên '{host}' nhưng chạy không được: {(check.stderr or check.stdout).strip()}")
|
|
171
|
+
return base
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def glob_escape(text):
|
|
175
|
+
return re.sub(r"([*?\[\]{}\\])", r"\\\1", text)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def reset_remote_state(host, home, name):
|
|
179
|
+
state = shlex.quote(f"{home}/{REMOTE_STATE_REL}/{name}")
|
|
180
|
+
done = ssh(host, f"rm -rf {state} && mkdir -p {state}")
|
|
181
|
+
if done.returncode:
|
|
182
|
+
raise SystemExit(f"Không tạo được thư mục trạng thái trên '{host}': {done.stderr.strip()}")
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def drop_remote_state(host, home, name):
|
|
186
|
+
ssh(host, f"rm -rf {shlex.quote(f'{home}/{REMOTE_STATE_REL}/{name}')}")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def prf_text(profile, heavy=()):
|
|
190
|
+
base = remote_base(profile["remote_home"])
|
|
191
|
+
lines = [
|
|
192
|
+
f"root = {profile['local']}",
|
|
193
|
+
f"root = ssh://{profile['host']}/{profile['remote']}",
|
|
194
|
+
f"servercmd = env UNISON={profile['remote_home']}/{REMOTE_STATE_REL}/{profile['name']} PATH={base}/bin:$PATH {base}/bin/unison",
|
|
195
|
+
"batch = true",
|
|
196
|
+
"silent = true",
|
|
197
|
+
f"maxsizethreshold = {profile['threshold_kb']}",
|
|
198
|
+
"sshargs = -o BatchMode=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3",
|
|
199
|
+
"log = true",
|
|
200
|
+
f"logfile = {logs_dir() / (profile['name'] + '.log')}",
|
|
201
|
+
f"ignore = Name *{STUB_SUFFIX}",
|
|
202
|
+
"ignore = Name .DS_Store",
|
|
203
|
+
"ignore = Path .claude/settings.local.json",
|
|
204
|
+
]
|
|
205
|
+
lines += [f"ignore = {pattern}" for pattern in profile.get("ignores", [])]
|
|
206
|
+
lines += [f"ignore = Path {glob_escape(relative)}" for relative in sorted(heavy)]
|
|
207
|
+
return "\n".join(lines) + "\n"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def write_prf(profile, heavy=()):
|
|
211
|
+
path = unison_home(profile["name"]) / f"{profile['name']}.prf"
|
|
212
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
213
|
+
logs_dir().mkdir(parents=True, exist_ok=True)
|
|
214
|
+
path.write_text(prf_text(profile, heavy), encoding="utf-8")
|
|
215
|
+
return path
|
suken_sync/watch.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import select
|
|
3
|
+
import signal
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from . import profiles, stubs
|
|
9
|
+
from .common import SSH_OPTIONS
|
|
10
|
+
from .unison import environment, local_bin, write_prf
|
|
11
|
+
|
|
12
|
+
SCAN_SECONDS = 5
|
|
13
|
+
RESTART_WAIT_S = 15
|
|
14
|
+
STOP_WAIT_S = 10
|
|
15
|
+
BLOCK_END = b"---"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Scanner:
|
|
19
|
+
def __init__(self, profile):
|
|
20
|
+
command = f"while :; do {stubs.find_command(profile)} 2>/dev/null; echo ---; sleep {SCAN_SECONDS}; done"
|
|
21
|
+
self.profile = profile
|
|
22
|
+
self.buffer = b""
|
|
23
|
+
self.lines = []
|
|
24
|
+
self.proc = subprocess.Popen(
|
|
25
|
+
["ssh", *SSH_OPTIONS, "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", profile["host"], command],
|
|
26
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0)
|
|
27
|
+
|
|
28
|
+
def alive(self):
|
|
29
|
+
return self.proc.poll() is None
|
|
30
|
+
|
|
31
|
+
def read_block(self, timeout):
|
|
32
|
+
ready, _, _ = select.select([self.proc.stdout], [], [], timeout)
|
|
33
|
+
if not ready:
|
|
34
|
+
return None
|
|
35
|
+
chunk = os.read(self.proc.stdout.fileno(), 65536)
|
|
36
|
+
if not chunk:
|
|
37
|
+
return None
|
|
38
|
+
self.buffer += chunk
|
|
39
|
+
block = None
|
|
40
|
+
while b"\n" in self.buffer:
|
|
41
|
+
line, self.buffer = self.buffer.split(b"\n", 1)
|
|
42
|
+
if line.strip() == BLOCK_END:
|
|
43
|
+
block = stubs.parse(self.lines, self.profile)
|
|
44
|
+
self.lines = []
|
|
45
|
+
else:
|
|
46
|
+
self.lines.append(line.decode("utf-8", "replace"))
|
|
47
|
+
return block
|
|
48
|
+
|
|
49
|
+
def close(self):
|
|
50
|
+
stop(self.proc)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def stop(proc):
|
|
54
|
+
if proc is None or proc.poll() is not None:
|
|
55
|
+
return
|
|
56
|
+
proc.terminate()
|
|
57
|
+
try:
|
|
58
|
+
proc.wait(STOP_WAIT_S)
|
|
59
|
+
except subprocess.TimeoutExpired:
|
|
60
|
+
proc.kill()
|
|
61
|
+
proc.wait()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Supervisor:
|
|
65
|
+
def __init__(self, profile):
|
|
66
|
+
self.profile = profile
|
|
67
|
+
self.scanner = None
|
|
68
|
+
self.child = None
|
|
69
|
+
self.paths = None
|
|
70
|
+
self.scanner_at = 0.0
|
|
71
|
+
self.child_at = 0.0
|
|
72
|
+
|
|
73
|
+
def start_child(self):
|
|
74
|
+
log = open(profiles.logs_dir() / f"{self.profile['name']}.out", "ab")
|
|
75
|
+
self.child = subprocess.Popen([str(local_bin() / "unison"), self.profile["name"], "-repeat", "watch", "-ignorelocks"],
|
|
76
|
+
env=environment(self.profile["name"]), stdin=subprocess.DEVNULL, stdout=log, stderr=log)
|
|
77
|
+
|
|
78
|
+
def apply(self, rows):
|
|
79
|
+
stubs.write(self.profile, rows)
|
|
80
|
+
paths = {relative for relative, _ in rows}
|
|
81
|
+
if paths != self.paths:
|
|
82
|
+
stop(self.child)
|
|
83
|
+
self.child = None
|
|
84
|
+
self.paths = paths
|
|
85
|
+
write_prf(self.profile, paths)
|
|
86
|
+
self.child_at = 0.0
|
|
87
|
+
|
|
88
|
+
def step(self):
|
|
89
|
+
now = time.monotonic()
|
|
90
|
+
if self.scanner is not None and not self.scanner.alive():
|
|
91
|
+
self.scanner.close()
|
|
92
|
+
self.scanner = None
|
|
93
|
+
if self.scanner is None and now >= self.scanner_at:
|
|
94
|
+
self.scanner = Scanner(self.profile)
|
|
95
|
+
self.scanner_at = now + RESTART_WAIT_S
|
|
96
|
+
if self.scanner is not None:
|
|
97
|
+
rows = self.scanner.read_block(1.0)
|
|
98
|
+
if rows is not None:
|
|
99
|
+
self.apply(rows)
|
|
100
|
+
else:
|
|
101
|
+
time.sleep(1.0)
|
|
102
|
+
if self.child is not None and self.child.poll() is not None:
|
|
103
|
+
self.child = None
|
|
104
|
+
self.child_at = now + RESTART_WAIT_S
|
|
105
|
+
if self.child is None and self.paths is not None and now >= self.child_at:
|
|
106
|
+
self.start_child()
|
|
107
|
+
|
|
108
|
+
def shutdown(self):
|
|
109
|
+
stop(self.child)
|
|
110
|
+
if self.scanner is not None:
|
|
111
|
+
self.scanner.close()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def run(name):
|
|
115
|
+
profile = profiles.load_all().get(name)
|
|
116
|
+
if not profile:
|
|
117
|
+
raise SystemExit(f"Không có phiên '{name}'.")
|
|
118
|
+
profiles.logs_dir().mkdir(parents=True, exist_ok=True)
|
|
119
|
+
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(0))
|
|
120
|
+
supervisor = Supervisor(profile)
|
|
121
|
+
try:
|
|
122
|
+
while True:
|
|
123
|
+
supervisor.step()
|
|
124
|
+
finally:
|
|
125
|
+
supervisor.shutdown()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def main():
|
|
129
|
+
if len(sys.argv) != 2:
|
|
130
|
+
raise SystemExit("Dùng: python -m suken_sync.watch <tên phiên>")
|
|
131
|
+
run(sys.argv[1])
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
if __name__ == "__main__":
|
|
135
|
+
main()
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: suken-sync
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Đồng bộ hai chiều một thư mục từ máy Linux (qua SSH) về máy macOS hoặc Linux khác bằng Unison: file nặng không đồng bộ mà để file bóng, chạy nền tự nối lại, hook SessionStart dặn Claude Code chạy lệnh bên Linux.
|
|
5
|
+
Author: suken
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: sync,unison,ssh,remote-development,claude-code
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
10
|
+
Classifier: Operating System :: MacOS
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Topic :: System :: Archiving :: Mirroring
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
License-File: THIRD_PARTY_NOTICES.md
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# suken-sync
|
|
20
|
+
|
|
21
|
+
Đồng bộ **hai chiều** một thư mục từ máy Linux (qua SSH) về máy này (macOS hoặc Linux), để agent như Claude Code đọc và
|
|
22
|
+
sửa code ngay trên máy này còn việc chạy (build, test, docker, server) vẫn ở máy Linux.
|
|
23
|
+
|
|
24
|
+
- **File nặng không đồng bộ.** File từ ngưỡng (mặc định 10 MB) trở lên (weight model, `.pdb`, `.so`...) ở lại Linux; trên máy này chỉ có
|
|
25
|
+
file bóng `<tên file>.linux-only.txt` ghi cỡ và vị trí thật, để agent biết file có tồn tại mà không tải về hay build lại.
|
|
26
|
+
- **Chạy nền, tự nối lại** sau khi mở máy, mất mạng hay mất VPN.
|
|
27
|
+
- **Hook SessionStart** của Claude Code dặn agent: máy này chỉ đọc và sửa, mọi lệnh chạy qua `ssh` sang Linux. Không đụng `CLAUDE.md`.
|
|
28
|
+
|
|
29
|
+
## Dùng thế nào
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install suken-sync
|
|
33
|
+
suken-sync setup # bắt buộc chạy trước: cài Unison, hook; in hướng dẫn cho agent
|
|
34
|
+
suken-sync add --host linux-box --remote /home/dev/my_project --local /Users/me/Downloads_linux-box/my_project
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Ngay sau `pip install`, mọi lệnh (trừ `setup`, `usage`) và cả `--help` chỉ nhắc chạy `setup`. `setup` chạy xong thì in hướng dẫn dùng `add`,
|
|
38
|
+
và từ đó mỗi phiên Claude Code mở trong thư mục đã cài hook đều tự nhận hướng dẫn qua hook.
|
|
39
|
+
|
|
40
|
+
`add` **bắt buộc đủ 3 tham số** `--host`, `--remote`, `--local` (cũng viết `--remote-Mac`); thiếu hoặc sai một tham số thì lệnh bị chặn
|
|
41
|
+
ngay, liệt kê từng lỗi kèm ví dụ đủ tham số. Đổi máy: tạo venv mới, `pip install`, `setup`, rồi chạy lại đúng lệnh `add`.
|
|
42
|
+
|
|
43
|
+
## Các lệnh
|
|
44
|
+
|
|
45
|
+
| Lệnh | Làm gì |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| `suken-sync setup [--dir DIR] [--remove]` | tải Unison 2.54.0 (ghim, kiểm sha256; macOS thêm `unison-fsmonitor` 0.3.9) vào cache; cài hook SessionStart vào `DIR/.claude/settings.local.json` (mặc định thư mục hiện tại, giữ nguyên hook khác); kiểm `ssh`, `scp`, dịch vụ nền; thiếu gì thì liệt kê và thoát mã lỗi, đủ thì in hướng dẫn. `--remove` gỡ hook |
|
|
48
|
+
| `suken-sync add --host H --remote R --local L [--threshold 10MB] [--name N] [--ignore PATTERN]` | thêm một thư mục: nối ssh, cài Unison riêng lên Linux (`~/.cache/suken-sync`), quét file nặng, đồng bộ lần đầu, tạo file bóng, cài dịch vụ nền và hook vào `L/.claude/settings.local.json`, kiểm cuối (`✅ Sync xong` hoặc liệt kê chỗ thiếu và thoát mã lỗi). `--ignore` là mẫu Unison (vd `"Name node_modules"`), lặp lại được |
|
|
49
|
+
| `suken-sync list` | liệt kê các phiên |
|
|
50
|
+
| `suken-sync status [tên]` | dịch vụ còn chạy, nối được Linux, hook còn; thoát mã 1 nếu có vấn đề |
|
|
51
|
+
| `suken-sync refresh [tên]` | quét file nặng ngay, nạp lại danh sách bỏ qua và file bóng, khởi động lại dịch vụ (thường không cần: dịch vụ tự quét mỗi 5 giây) |
|
|
52
|
+
| `suken-sync remove <tên>` | tháo phiên: dịch vụ, hook, file bóng, trạng thái Unison ở cả hai máy; **không xoá code** ở cả hai máy |
|
|
53
|
+
| `suken-sync usage` | in hướng dẫn cho agent |
|
|
54
|
+
|
|
55
|
+
## Cách hoạt động
|
|
56
|
+
|
|
57
|
+
1. Mỗi phiên là một dịch vụ nền (macOS: launchd, `KeepAlive`; Linux: systemd user, `Restart=always`, chờ 15 giây giữa các lần dựng lại) chạy một
|
|
58
|
+
bộ giám sát `python -m suken_sync.watch`.
|
|
59
|
+
2. Bộ giám sát giữ một kết nối ssh chạy `find` mỗi 5 giây trên Linux để tìm file từ ngưỡng trở lên. Có file nặng mới thì nó tạo file bóng,
|
|
60
|
+
ghi đường dẫn đó vào danh sách bỏ qua (`ignore = Path ...`) của Unison và khởi động lại Unison trong vài giây.
|
|
61
|
+
3. Unison chạy `-repeat watch` (đồng bộ ngay khi có thay đổi) cùng `maxsizethreshold`: file nặng mới thêm vào thư mục có sẵn bị chặn ngay,
|
|
62
|
+
không chờ bộ giám sát. Riêng file nặng nằm trong **thư mục hoàn toàn mới** thì Unison chép cả thư mục như một khối và bỏ qua ngưỡng
|
|
63
|
+
([recon.ml](https://github.com/bcpierce00/unison/blob/v2.54.0/src/recon.ml)), nên lớp quét ở bước 2 là lớp chặn chính cho trường hợp này.
|
|
64
|
+
4. Độ trễ khi sửa file: khoảng 0,6 giây (Linux sang máy này) đến 1,2 giây (máy này sang Linux), đo trên mạng công ty qua VPN.
|
|
65
|
+
|
|
66
|
+
## An toàn
|
|
67
|
+
|
|
68
|
+
- Không bao giờ dùng `prefer` hay `force` của Unison; xung đột (cùng một file sửa cả hai bên) được bỏ qua và ghi vào log, không bên nào bị ghi đè.
|
|
69
|
+
- Unison giữ nguyên lớp bảo vệ `confirmbigdel`: nếu một bên bỗng mất hàng loạt file (thư mục bị xoá, ổ chưa gắn) thì dừng thay vì xoá bên kia.
|
|
70
|
+
- File bóng và `.claude/settings.local.json` không bao giờ đồng bộ. Gói chỉ xoá file bóng có dòng đầu bắt đầu bằng `[BÓNG]`.
|
|
71
|
+
- Mỗi phiên có trạng thái Unison riêng ở cả hai máy (`remove` xoá sạch), nên `add` lại vào thư mục trống không bị nhầm là "vừa xoá hết".
|
|
72
|
+
- Log: `<thư mục cấu hình>/logs/<tên>.log` và `.out` (macOS: `~/Library/Application Support/suken-sync`, Linux: `~/.config/suken-sync`).
|
|
73
|
+
|
|
74
|
+
## Yêu cầu
|
|
75
|
+
|
|
76
|
+
- Máy này: macOS (Apple Silicon hoặc Intel) hoặc Linux x86_64, Python 3.9 trở lên, `ssh` và `scp`. Linux cần systemd user session; muốn chạy
|
|
77
|
+
khi chưa đăng nhập thì bật `loginctl enable-linger`.
|
|
78
|
+
- Máy Linux ở xa: x86_64, vào được bằng `ssh <host>` bằng key, không hỏi mật khẩu (bật VPN trước nếu cần).
|
|
79
|
+
- Windows không hỗ trợ.
|
|
80
|
+
|
|
81
|
+
## Biến môi trường (dùng khi tự cài hoặc thử)
|
|
82
|
+
|
|
83
|
+
| Biến | Tác dụng |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `SUKEN_SYNC_UNISON_DIR` | thư mục chứa file `unison` (và `unison-fsmonitor`) tự cài, bỏ qua bước tải |
|
|
86
|
+
| `SUKEN_SYNC_REMOTE_UNISON_DIR` | thư mục chứa bản Unison Linux để chép lên máy ở xa |
|
|
87
|
+
| `SUKEN_SYNC_HOME` | dời toàn bộ cấu hình, cache, file dịch vụ vào một thư mục (để thử, không đụng cấu hình thật) |
|
|
88
|
+
|
|
89
|
+
Phần mềm bên thứ ba: xem [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
suken_sync/GUIDE.md,sha256=glFVgtdMliPYdYHnl_Ct0AkDRTPuyiYpzJFQS7lVVy0,3587
|
|
2
|
+
suken_sync/SYNCED.md,sha256=dJv1Q_-18b3-NAhmydJiZ136FcLwi7-lDdkE5QNVQNQ,1043
|
|
3
|
+
suken_sync/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
4
|
+
suken_sync/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
|
5
|
+
suken_sync/cli.py,sha256=uVtSjEigPuFSO8h0C8xB7J8TzYHb0F6Q9FceLx9LPoA,14088
|
|
6
|
+
suken_sync/common.py,sha256=J6FLa2jWquFDrraJ82hjs2QrQbrdEN7sAXzeAIzKcIk,2749
|
|
7
|
+
suken_sync/hook.py,sha256=lusVr4er3ABYb4w-eBa8oYQ4rVTMtiSYzOnThu_oCrA,2191
|
|
8
|
+
suken_sync/profiles.py,sha256=9CFkrAtKhx7wzPENDnytgv78Lpyh_hiP5dRuv0OVjq0,1463
|
|
9
|
+
suken_sync/service.py,sha256=oWomZOIVg31GgqnEFXqIo_vmivUZLTxqa428tWh5NxU,4145
|
|
10
|
+
suken_sync/stubs.py,sha256=SB2Sy8uzOWG7b4H1y5xGD2653SncCvo7Gcm7Dg95tFc,2620
|
|
11
|
+
suken_sync/unison.py,sha256=1AAZ00XGxyzYyp_td_tWAPG9d-OjA7J03gLkM4xVIy4,8673
|
|
12
|
+
suken_sync/watch.py,sha256=th4hebAtUKhSucbKjy5I1b96C0vkMeqX0zULP60cDck,4150
|
|
13
|
+
suken_sync-0.1.0.dist-info/licenses/LICENSE,sha256=QLEsElgGthQyAqdywpU9bQ4mqt82q5suKpdaarlo-2Y,1062
|
|
14
|
+
suken_sync-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=1r20_g2Tf9mBQWF36rIpKq1Ba-pB7krWf1_ajSXqEzs,995
|
|
15
|
+
suken_sync-0.1.0.dist-info/METADATA,sha256=EKsDlmvpu3JG4YCsJNpb6wUldiF9geKpJ6W7-RT4Iik,7048
|
|
16
|
+
suken_sync-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
suken_sync-0.1.0.dist-info/entry_points.txt,sha256=GBwWrm7dEt3P0hmZMzILXH8bBWrtN2coFA1jIjSi6Ec,51
|
|
18
|
+
suken_sync-0.1.0.dist-info/top_level.txt,sha256=4spfgzHsZH2LToqmfnvi8UbM3zRajNMUTv9OYvKSaHY,11
|
|
19
|
+
suken_sync-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 suken
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Thông báo phần mềm bên thứ ba
|
|
2
|
+
|
|
3
|
+
suken-sync (giấy phép MIT) **không đóng gói** mã của phần mềm dưới đây. `suken-sync setup` tải bản phát hành chính thức của chúng
|
|
4
|
+
về thư mục cache của người dùng và kiểm mã băm sha256 đã ghim trước khi dùng.
|
|
5
|
+
|
|
6
|
+
## Unison
|
|
7
|
+
|
|
8
|
+
- Dự án: https://github.com/bcpierce00/unison (bản ghim 2.54.0)
|
|
9
|
+
- Giấy phép: GNU General Public License v3 (xem file LICENSE trong gói tải về, và trang dự án).
|
|
10
|
+
- Vai trò: công cụ đồng bộ hai chiều chạy ở cả máy này và máy Linux; suken-sync chỉ gọi nó như một chương trình riêng.
|
|
11
|
+
|
|
12
|
+
## unison-fsmonitor (chỉ trên macOS)
|
|
13
|
+
|
|
14
|
+
- Dự án: https://github.com/autozimu/unison-fsmonitor (bản ghim 0.3.9)
|
|
15
|
+
- Giấy phép: MIT.
|
|
16
|
+
- Vai trò: theo dõi thay đổi file trên macOS để Unison đồng bộ gần như tức thì (Unison không có sẵn phần này cho macOS).
|
|
17
|
+
Trên Linux, chương trình này đi kèm trong gói Unison.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
suken_sync
|