syncdot 1.0.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.
- syncdot/__init__.py +1 -0
- syncdot/__main__.py +768 -0
- syncdot/config.py +82 -0
- syncdot/lock.py +61 -0
- syncdot/migrate.py +74 -0
- syncdot/renderer.py +138 -0
- syncdot/repo.py +262 -0
- syncdot/state.py +159 -0
- syncdot/sync.py +1349 -0
- syncdot/systemd.py +108 -0
- syncdot-1.0.0.dist-info/METADATA +648 -0
- syncdot-1.0.0.dist-info/RECORD +16 -0
- syncdot-1.0.0.dist-info/WHEEL +5 -0
- syncdot-1.0.0.dist-info/entry_points.txt +2 -0
- syncdot-1.0.0.dist-info/licenses/LICENSE +22 -0
- syncdot-1.0.0.dist-info/top_level.txt +1 -0
syncdot/__main__.py
ADDED
|
@@ -0,0 +1,768 @@
|
|
|
1
|
+
"""
|
|
2
|
+
syncdot — bidirectional dotfile sync with profiles and templating.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
syncdot init <repo> Set syncdot up on this machine
|
|
6
|
+
syncdot sync [--dry-run] Bidirectional sync
|
|
7
|
+
syncdot push [<path>...] Force disk → git (all, or just <path>s)
|
|
8
|
+
syncdot pull [<path>...] Force git → disk (all, or just <path>s)
|
|
9
|
+
syncdot status [<path>...] Show per-file state (--diff for details)
|
|
10
|
+
syncdot add <path>... Track files/dirs, copying them to the repo (--remote R)
|
|
11
|
+
syncdot checkout <remote>... Track repo files, writing them to disk (--local L)
|
|
12
|
+
syncdot remove <path>... Stop tracking files/dirs (disk copies are kept)
|
|
13
|
+
syncdot var list|set|unset Manage template variables (vars.yaml)
|
|
14
|
+
syncdot env list|set|unset|hook Manage session environment variables
|
|
15
|
+
syncdot profile list List available profiles
|
|
16
|
+
syncdot profile set <name> Switch active profile
|
|
17
|
+
syncdot profile new <name> Create a new profile branch
|
|
18
|
+
syncdot service install Sync automatically at login (opt-in)
|
|
19
|
+
syncdot service uninstall Stop syncing at login
|
|
20
|
+
syncdot service status Show the login service status
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import functools
|
|
26
|
+
import glob
|
|
27
|
+
import shutil
|
|
28
|
+
import os
|
|
29
|
+
import sys
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
import click
|
|
33
|
+
import yaml
|
|
34
|
+
|
|
35
|
+
from . import __version__
|
|
36
|
+
from .config import Config, CONFIG_PATH, profile_branch
|
|
37
|
+
from .lock import LockTimeout, repo_lock
|
|
38
|
+
from .migrate import migrate_from_dotsync
|
|
39
|
+
from .repo import Repo, GitError, normalize_github_url
|
|
40
|
+
from .renderer import RenderError
|
|
41
|
+
from .sync import NOT_SET_UP, Action, PullDeclined, Syncer, find_private
|
|
42
|
+
from . import systemd
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ── Helpers ────────────────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
# Exit codes (part of the stable interface): 0 success, 1 error, 2 usage error
|
|
48
|
+
# (from click), EXIT_PENDING from `status --exit-code` when something would change
|
|
49
|
+
EXIT_PENDING = 3
|
|
50
|
+
|
|
51
|
+
ACTION_SYMBOLS = {
|
|
52
|
+
Action.NOTHING: click.style("·", fg="bright_black"),
|
|
53
|
+
Action.PULL: click.style("↓", fg="cyan"),
|
|
54
|
+
Action.PUSH: click.style("↑", fg="green"),
|
|
55
|
+
Action.CONFLICT: click.style("!", fg="yellow"),
|
|
56
|
+
Action.UNTRACK: click.style("−", fg="red"),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def print_results(results, verbose: bool = False, pending: bool = False) -> int:
|
|
61
|
+
"""Print per-file results and a summary (pending=True words it as not yet
|
|
62
|
+
done). Returns the number of errors."""
|
|
63
|
+
errors = 0
|
|
64
|
+
for r in results:
|
|
65
|
+
sym = ACTION_SYMBOLS[r.action]
|
|
66
|
+
dest = str(r.dest).replace(str(Path.home()), "~")
|
|
67
|
+
line = f" {sym} {dest}"
|
|
68
|
+
if r.skipped:
|
|
69
|
+
sym = click.style("-", fg="bright_black")
|
|
70
|
+
line = f" {sym} {dest}" + click.style(f" [skipped: {r.skipped}]", fg="bright_black")
|
|
71
|
+
if r.resolved_by:
|
|
72
|
+
line += click.style(f" [{r.resolved_by}]", fg="yellow")
|
|
73
|
+
if r.error:
|
|
74
|
+
line += click.style(f" ERROR: {r.error}", fg="red")
|
|
75
|
+
errors += 1
|
|
76
|
+
if verbose or r.action != Action.NOTHING or r.error or r.skipped:
|
|
77
|
+
click.echo(line)
|
|
78
|
+
|
|
79
|
+
counts = {a: sum(1 for r in results if r.action == a and not r.skipped and not r.error) for a in Action}
|
|
80
|
+
skipped = sum(1 for r in results if r.skipped)
|
|
81
|
+
parts = []
|
|
82
|
+
if counts[Action.PULL]:
|
|
83
|
+
parts.append(click.style(f"↓ {counts[Action.PULL]} " + ("to pull" if pending else "pulled"), fg="cyan"))
|
|
84
|
+
if counts[Action.PUSH]:
|
|
85
|
+
parts.append(click.style(f"↑ {counts[Action.PUSH]} " + ("to push" if pending else "pushed"), fg="green"))
|
|
86
|
+
if counts[Action.CONFLICT]:
|
|
87
|
+
parts.append(click.style(f"! {counts[Action.CONFLICT]} conflicts", fg="yellow"))
|
|
88
|
+
if counts[Action.UNTRACK]:
|
|
89
|
+
parts.append(click.style(f"− {counts[Action.UNTRACK]} " + ("to untrack" if pending else "untracked"), fg="red"))
|
|
90
|
+
if counts[Action.NOTHING] and not parts:
|
|
91
|
+
parts.append(click.style("already in sync", fg="bright_black"))
|
|
92
|
+
if skipped:
|
|
93
|
+
parts.append(click.style(f"{skipped} skipped", fg="bright_black"))
|
|
94
|
+
if errors:
|
|
95
|
+
parts.append(click.style(f"{errors} errors", fg="red"))
|
|
96
|
+
|
|
97
|
+
click.echo("\n " + " ".join(parts))
|
|
98
|
+
if any(r.skipped == NOT_SET_UP for r in results):
|
|
99
|
+
click.echo(click.style(
|
|
100
|
+
"\n Files not synced on this machine yet are left alone. Run `syncdot pull <path>`\n"
|
|
101
|
+
" to take the repo's version or `syncdot push <path>` to keep this machine's\n"
|
|
102
|
+
" (`syncdot pull` alone takes the repo's version of everything).", fg="bright_black"))
|
|
103
|
+
return errors
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def locked(command):
|
|
107
|
+
"""Run a command while holding the syncdot lock, so runs never overlap."""
|
|
108
|
+
@functools.wraps(command)
|
|
109
|
+
def wrapper(*args, **kwargs):
|
|
110
|
+
cfg = load_config_or_exit()
|
|
111
|
+
def on_wait(pid: str) -> None:
|
|
112
|
+
click.echo(click.style(f"Another syncdot is running (pid {pid}); waiting for it…",
|
|
113
|
+
fg="yellow"), err=True)
|
|
114
|
+
try:
|
|
115
|
+
with repo_lock(cfg.state_path.parent / "lock", on_wait=on_wait):
|
|
116
|
+
return command(*args, **kwargs)
|
|
117
|
+
except (LockTimeout, GitError, RenderError) as e:
|
|
118
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
119
|
+
sys.exit(1)
|
|
120
|
+
return wrapper
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def load_config_or_exit() -> Config:
|
|
124
|
+
try:
|
|
125
|
+
return Config.load()
|
|
126
|
+
except FileNotFoundError as e:
|
|
127
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
128
|
+
sys.exit(1)
|
|
129
|
+
except Exception as e:
|
|
130
|
+
click.echo(click.style(f"Config error: {e}", fg="red"), err=True)
|
|
131
|
+
sys.exit(1)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ── CLI root ───────────────────────────────────────────────────────────────────
|
|
135
|
+
|
|
136
|
+
@click.group()
|
|
137
|
+
@click.version_option(__version__, prog_name="syncdot")
|
|
138
|
+
def cli():
|
|
139
|
+
"""syncdot — bidirectional dotfile sync with profiles and templating."""
|
|
140
|
+
for line in migrate_from_dotsync():
|
|
141
|
+
click.echo(click.style(f"syncdot was called dotsync up to 0.8.0. {line}", fg="yellow"),
|
|
142
|
+
err=True)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# ── init ───────────────────────────────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
@cli.command()
|
|
148
|
+
@click.argument("repo")
|
|
149
|
+
@click.option("--profile", default="base", show_default=True, help="Profile to use on this machine.")
|
|
150
|
+
@click.option("--new", is_flag=True,
|
|
151
|
+
help="Start a new syncdot repo locally, for a GitHub repo that doesn't exist yet "
|
|
152
|
+
"(it's pushed on your first `syncdot add`).")
|
|
153
|
+
def init(repo: str, profile: str, new: bool):
|
|
154
|
+
"""Set syncdot up on this machine with REPO, your dotfiles repo.
|
|
155
|
+
|
|
156
|
+
REPO is a git URL or a GitHub owner/repo shorthand; HTTPS GitHub URLs are
|
|
157
|
+
converted to SSH so your existing key is used. An existing syncdot repo is
|
|
158
|
+
cloned, an empty one is set up as a new syncdot repo. Only the clone and
|
|
159
|
+
~/.config/syncdot/config.yaml are written: nothing in your home directory
|
|
160
|
+
changes until you pull, push or checkout.
|
|
161
|
+
"""
|
|
162
|
+
_init(repo, profile, new)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@cli.command(hidden=True)
|
|
166
|
+
@click.option("--repo-url", prompt="GitHub repo URL")
|
|
167
|
+
@click.option("--profile", default="base")
|
|
168
|
+
@click.option("--clone/--init", default=True)
|
|
169
|
+
def install(repo_url: str, profile: str, clone: bool):
|
|
170
|
+
"""Old name for `syncdot init` (before 0.8.0)."""
|
|
171
|
+
new_flag = "" if clone else " --new"
|
|
172
|
+
click.echo(click.style(f"`syncdot install` is now `syncdot init <repo>{new_flag}`.", fg="yellow"),
|
|
173
|
+
err=True)
|
|
174
|
+
_init(repo_url, profile, new=not clone)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _init(repo_url: str, profile: str, new: bool) -> None:
|
|
178
|
+
normalized = normalize_github_url(repo_url)
|
|
179
|
+
if normalized != repo_url:
|
|
180
|
+
click.echo(f"Using SSH (existing GitHub key) instead of HTTPS: {normalized}")
|
|
181
|
+
repo_url = normalized
|
|
182
|
+
cfg = Config(profile=profile)
|
|
183
|
+
|
|
184
|
+
if cfg.repo_path.exists() and (cfg.repo_path / ".git").exists():
|
|
185
|
+
click.echo(f"Repo already exists at {cfg.repo_path}, keeping it.")
|
|
186
|
+
elif new:
|
|
187
|
+
click.echo(f"Starting a new syncdot repo at {cfg.repo_path} …")
|
|
188
|
+
Repo.init(cfg.repo_path, repo_url)
|
|
189
|
+
else:
|
|
190
|
+
click.echo(f"Cloning {repo_url} → {cfg.repo_path} …")
|
|
191
|
+
try:
|
|
192
|
+
repo = Repo.clone(repo_url, cfg.repo_path)
|
|
193
|
+
except GitError as e:
|
|
194
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
195
|
+
click.echo("If the repo doesn't exist on GitHub yet, create it empty, or run "
|
|
196
|
+
f"`syncdot init {repo_url} --new` to start locally.", err=True)
|
|
197
|
+
sys.exit(1)
|
|
198
|
+
branches = repo.remote_branches()
|
|
199
|
+
if not branches:
|
|
200
|
+
# A brand-new, empty GitHub repo: set it up instead of leaving a broken clone
|
|
201
|
+
click.echo("The repo is empty, so setting it up as a new syncdot repo …")
|
|
202
|
+
shutil.rmtree(cfg.repo_path)
|
|
203
|
+
Repo.init(cfg.repo_path, repo_url)
|
|
204
|
+
else:
|
|
205
|
+
# The repo's default branch may not be base (e.g. GitHub's `main`),
|
|
206
|
+
# in which case git checked out the wrong branch or nothing at all
|
|
207
|
+
target = cfg.branch if cfg.branch in branches else "base"
|
|
208
|
+
if target not in branches:
|
|
209
|
+
shutil.rmtree(cfg.repo_path)
|
|
210
|
+
click.echo(click.style(
|
|
211
|
+
f"{repo_url} has no `base` branch, so it doesn't look like a syncdot repo "
|
|
212
|
+
f"(branches: {', '.join(branches)}). Point syncdot at your dotfiles repo, "
|
|
213
|
+
"or at a new empty one.", fg="red"), err=True)
|
|
214
|
+
sys.exit(1)
|
|
215
|
+
repo.checkout(target)
|
|
216
|
+
|
|
217
|
+
cfg.write_default(profile)
|
|
218
|
+
|
|
219
|
+
if click.confirm("Sync automatically at login? (you can turn it on later with "
|
|
220
|
+
"`syncdot service install`)", default=False):
|
|
221
|
+
try:
|
|
222
|
+
for line in systemd.install():
|
|
223
|
+
click.echo(line)
|
|
224
|
+
except systemd.SystemdError as e:
|
|
225
|
+
click.echo(click.style(f"Skipped the service: {e}", fg="yellow"), err=True)
|
|
226
|
+
|
|
227
|
+
click.echo(click.style("\nsyncdot is set up. Nothing on disk was changed. Next:", fg="green"))
|
|
228
|
+
click.echo(" syncdot add ~/.vimrc ~/.config/kitty # start tracking files from this machine")
|
|
229
|
+
click.echo(" syncdot status # joining an existing repo: see what's there,")
|
|
230
|
+
click.echo(" syncdot pull # then take the repo's files (or `pull <path>`)")
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# ── sync ───────────────────────────────────────────────────────────────────────
|
|
234
|
+
|
|
235
|
+
@cli.command()
|
|
236
|
+
@click.option("--dry-run", is_flag=True, help="Show what would happen without making changes.")
|
|
237
|
+
@click.option("-v", "--verbose", is_flag=True)
|
|
238
|
+
@locked
|
|
239
|
+
def sync(dry_run: bool, verbose: bool):
|
|
240
|
+
"""Bidirectional sync: pull remote changes, push local changes, resolve conflicts."""
|
|
241
|
+
cfg = load_config_or_exit()
|
|
242
|
+
label = "[DRY RUN] " if dry_run else ""
|
|
243
|
+
click.echo(f"{label}Syncing profile {click.style(cfg.profile, fg='cyan')} …\n")
|
|
244
|
+
syncer = Syncer(cfg, dry_run=dry_run)
|
|
245
|
+
results = syncer.sync()
|
|
246
|
+
errors = print_results(results, verbose=verbose, pending=dry_run)
|
|
247
|
+
for note in syncer.notes:
|
|
248
|
+
click.echo(f"\n {note}")
|
|
249
|
+
if errors:
|
|
250
|
+
sys.exit(1)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# ── push ───────────────────────────────────────────────────────────────────────
|
|
254
|
+
|
|
255
|
+
@cli.command()
|
|
256
|
+
@click.argument("paths", nargs=-1)
|
|
257
|
+
@click.option("--dry-run", is_flag=True)
|
|
258
|
+
@click.option("-v", "--verbose", is_flag=True)
|
|
259
|
+
@locked
|
|
260
|
+
def push(paths: tuple[str, ...], dry_run: bool, verbose: bool):
|
|
261
|
+
"""Copy this machine's files to the repo: all of them, or only PATHS.
|
|
262
|
+
|
|
263
|
+
PATHS are tracked files or directories on disk. Quoted glob patterns
|
|
264
|
+
are matched against tracked paths, so '~/.config/foo/*' works even for
|
|
265
|
+
files missing from disk.
|
|
266
|
+
"""
|
|
267
|
+
cfg = load_config_or_exit()
|
|
268
|
+
click.echo(f"Pushing disk → repo (profile: {click.style(cfg.profile, fg='cyan')}) …\n")
|
|
269
|
+
syncer = Syncer(cfg, dry_run=dry_run)
|
|
270
|
+
try:
|
|
271
|
+
results = syncer.push_all(list(paths))
|
|
272
|
+
except (ValueError, GitError, RenderError) as e:
|
|
273
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
274
|
+
sys.exit(1)
|
|
275
|
+
errors = print_results(results, verbose=verbose or bool(paths), pending=dry_run)
|
|
276
|
+
for note in syncer.notes:
|
|
277
|
+
click.echo(f"\n {note}")
|
|
278
|
+
if errors:
|
|
279
|
+
sys.exit(1)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ── pull ───────────────────────────────────────────────────────────────────────
|
|
283
|
+
|
|
284
|
+
@cli.command()
|
|
285
|
+
@click.argument("paths", nargs=-1)
|
|
286
|
+
@click.option("-y", "--yes", is_flag=True, help="Overwrite local changes without asking.")
|
|
287
|
+
@click.option("--dry-run", is_flag=True)
|
|
288
|
+
@click.option("-v", "--verbose", is_flag=True)
|
|
289
|
+
@locked
|
|
290
|
+
def pull(paths: tuple[str, ...], yes: bool, dry_run: bool, verbose: bool):
|
|
291
|
+
"""Copy the repo's files to this machine: all of them, or only PATHS.
|
|
292
|
+
|
|
293
|
+
PATHS are tracked files or directories on disk. Quoted glob patterns
|
|
294
|
+
are matched against tracked paths, so '~/.config/foo/*' works even for
|
|
295
|
+
files missing from disk. If this would overwrite local changes that
|
|
296
|
+
aren't in the repo, pull lists those files and asks first (--yes skips
|
|
297
|
+
the question).
|
|
298
|
+
"""
|
|
299
|
+
cfg = load_config_or_exit()
|
|
300
|
+
click.echo(f"Pulling repo → disk (profile: {click.style(cfg.profile, fg='cyan')}) …\n")
|
|
301
|
+
syncer = Syncer(cfg, dry_run=dry_run)
|
|
302
|
+
|
|
303
|
+
def confirm(at_risk: list[Path]) -> bool:
|
|
304
|
+
if yes:
|
|
305
|
+
return True
|
|
306
|
+
click.echo(click.style("These local files have changes that aren't in the repo, and "
|
|
307
|
+
"pulling overwrites them:", fg="yellow"))
|
|
308
|
+
for dest in at_risk:
|
|
309
|
+
click.echo(" " + str(dest).replace(str(Path.home()), "~", 1))
|
|
310
|
+
click.echo("(`syncdot status --diff` shows the changes; `syncdot push <path>` keeps one.)")
|
|
311
|
+
try:
|
|
312
|
+
return click.confirm("Overwrite them?", default=False)
|
|
313
|
+
except click.Abort:
|
|
314
|
+
click.echo()
|
|
315
|
+
return False
|
|
316
|
+
|
|
317
|
+
try:
|
|
318
|
+
results = syncer.pull_all(list(paths), confirm=confirm)
|
|
319
|
+
except PullDeclined as e:
|
|
320
|
+
click.echo(click.style(f"{e} Run with --yes to overwrite without asking.", fg="red"), err=True)
|
|
321
|
+
sys.exit(1)
|
|
322
|
+
except (ValueError, GitError, RenderError) as e:
|
|
323
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
324
|
+
sys.exit(1)
|
|
325
|
+
if print_results(results, verbose=verbose or bool(paths), pending=dry_run):
|
|
326
|
+
sys.exit(1)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ── status ─────────────────────────────────────────────────────────────────────
|
|
330
|
+
|
|
331
|
+
@cli.command()
|
|
332
|
+
@click.argument("paths", nargs=-1)
|
|
333
|
+
@click.option("--diff", "show_diff", is_flag=True, help="Show how each differing file differs.")
|
|
334
|
+
@click.option("--no-fetch", is_flag=True, help="Don't check the remote; compare with the local clone only.")
|
|
335
|
+
@click.option("--exit-code", is_flag=True,
|
|
336
|
+
help=f"Exit with {EXIT_PENDING} if anything isn't in sync (0 if all is).")
|
|
337
|
+
@locked
|
|
338
|
+
def status(paths: tuple[str, ...], show_diff: bool, no_fetch: bool, exit_code: bool):
|
|
339
|
+
"""Show what `sync` would do for each file, without changing anything.
|
|
340
|
+
|
|
341
|
+
Changes waiting on GitHub are fetched and included (--no-fetch skips
|
|
342
|
+
that). PATHS limits it to those tracked files or directories (quoted
|
|
343
|
+
globs are matched against tracked paths). --diff also shows how each
|
|
344
|
+
differing file differs: `-` lines are the repo's version, `+` lines this
|
|
345
|
+
machine's.
|
|
346
|
+
"""
|
|
347
|
+
cfg = load_config_or_exit()
|
|
348
|
+
click.echo(f"Status (profile: {click.style(cfg.profile, fg='cyan')}) …\n")
|
|
349
|
+
syncer = Syncer(cfg, dry_run=True)
|
|
350
|
+
try:
|
|
351
|
+
results = syncer.status(list(paths), fetch=not no_fetch, with_diff=show_diff)
|
|
352
|
+
except ValueError as e:
|
|
353
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
354
|
+
sys.exit(1)
|
|
355
|
+
print_results(results, verbose=True, pending=True)
|
|
356
|
+
for r in results:
|
|
357
|
+
if r.diff:
|
|
358
|
+
print_diff(r.diff)
|
|
359
|
+
# Files that sync couldn't handle are reported, not a failure of status itself
|
|
360
|
+
if exit_code and any(r.action != Action.NOTHING or r.skipped == NOT_SET_UP or r.error
|
|
361
|
+
for r in results):
|
|
362
|
+
sys.exit(EXIT_PENDING)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def print_diff(lines: list[str]) -> None:
|
|
366
|
+
if not lines:
|
|
367
|
+
return
|
|
368
|
+
click.echo()
|
|
369
|
+
colours = {"+++": "bright_white", "---": "bright_white", "+": "green", "-": "red", "@": "cyan"}
|
|
370
|
+
for line in lines:
|
|
371
|
+
line = line.rstrip("\n")
|
|
372
|
+
colour = next((c for prefix, c in colours.items() if line.startswith(prefix)), None)
|
|
373
|
+
click.echo(click.style(line, fg=colour, bold=line.startswith(("+++", "---"))) if colour else line)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# ── add ────────────────────────────────────────────────────────────────────────
|
|
377
|
+
|
|
378
|
+
@cli.command()
|
|
379
|
+
@click.argument("paths", nargs=-1, required=True)
|
|
380
|
+
@click.option("--remote", metavar="REMOTE", help="Where to store it under files/.")
|
|
381
|
+
@click.option("--allow-private", is_flag=True,
|
|
382
|
+
help="Track files only you can read (e.g. mode 600), which often hold secrets.")
|
|
383
|
+
@click.option("--dry-run", is_flag=True, help="Show what would happen without making changes.")
|
|
384
|
+
@locked
|
|
385
|
+
def add(paths: tuple[str, ...], remote: str | None, allow_private: bool, dry_run: bool):
|
|
386
|
+
"""Start tracking PATHS (files or directories), stored under files/ in the repo.
|
|
387
|
+
|
|
388
|
+
Several paths can be given at once, and glob patterns are expanded
|
|
389
|
+
(quote them to let syncdot expand them, e.g. '~/.config/foo/*.conf').
|
|
390
|
+
Everything is added in a single commit; paths that can't be added are
|
|
391
|
+
reported and the rest are still added.
|
|
392
|
+
|
|
393
|
+
--remote defaults to the path relative to your home directory, so
|
|
394
|
+
~/.config/foo is stored as files/.config/foo (paths outside ~ need
|
|
395
|
+
--remote). If --remote ends with /, is an existing directory, or several
|
|
396
|
+
paths are given, each path's name is kept inside it. Directories are copied verbatim
|
|
397
|
+
(no .j2 rendering).
|
|
398
|
+
|
|
399
|
+
Symlinks are never copied: PATHS themselves can't be symlinks, and
|
|
400
|
+
symlinks inside a directory (plus nested .git directories) are skipped
|
|
401
|
+
and left untouched on every sync. Binary files are skipped unless
|
|
402
|
+
include_binary: true is set in the config. Private files (no access for
|
|
403
|
+
group or others, e.g. mode 600) are refused unless --allow-private is
|
|
404
|
+
given, since they often hold secrets.
|
|
405
|
+
"""
|
|
406
|
+
try:
|
|
407
|
+
locals_ = expand_paths(paths)
|
|
408
|
+
except ValueError as e:
|
|
409
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
410
|
+
sys.exit(1)
|
|
411
|
+
cfg = load_config_or_exit()
|
|
412
|
+
syncer = Syncer(cfg, dry_run=dry_run)
|
|
413
|
+
try:
|
|
414
|
+
results = syncer.add(locals_, remote, allow_private)
|
|
415
|
+
except (ValueError, GitError) as e:
|
|
416
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
417
|
+
sys.exit(1)
|
|
418
|
+
print_results(results, verbose=True, pending=dry_run)
|
|
419
|
+
for r in results:
|
|
420
|
+
if not r.error:
|
|
421
|
+
dest = str(r.dest).replace(str(Path.home()), "~")
|
|
422
|
+
click.echo(f" Tracking {dest} as {click.style(r.source, fg='cyan')}")
|
|
423
|
+
if allow_private:
|
|
424
|
+
private = [r.dest for r in results if not r.error and find_private(r.dest) is not None]
|
|
425
|
+
for dest in private:
|
|
426
|
+
shown = str(dest).replace(str(Path.home()), "~")
|
|
427
|
+
click.echo(click.style(
|
|
428
|
+
f" Warning: {shown} is private here, but git doesn't store permissions: on "
|
|
429
|
+
"other machines it arrives with default permissions (usually 644), readable "
|
|
430
|
+
"by other users. Its contents are also in your dotfiles repo.", fg="yellow"))
|
|
431
|
+
if any(r.error for r in results):
|
|
432
|
+
sys.exit(1)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def expand_paths(patterns: tuple[str, ...]) -> list[Path]:
|
|
436
|
+
"""Expand ~ and glob patterns, dropping duplicates while keeping order."""
|
|
437
|
+
seen: dict[Path, None] = {}
|
|
438
|
+
for pattern in patterns:
|
|
439
|
+
expanded = os.path.expanduser(pattern)
|
|
440
|
+
if glob.has_magic(expanded) and not os.path.lexists(expanded):
|
|
441
|
+
matches = sorted(glob.glob(expanded, include_hidden=True))
|
|
442
|
+
if not matches:
|
|
443
|
+
raise ValueError(f"No files match {pattern}")
|
|
444
|
+
else:
|
|
445
|
+
matches = [expanded]
|
|
446
|
+
for m in matches:
|
|
447
|
+
seen.setdefault(Path(os.path.abspath(m)), None)
|
|
448
|
+
return list(seen)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
# ── checkout ───────────────────────────────────────────────────────────────────
|
|
452
|
+
|
|
453
|
+
@cli.command()
|
|
454
|
+
@click.argument("remotes", nargs=-1, required=True)
|
|
455
|
+
@click.option("--local", type=click.Path(path_type=Path), help="Where to write it on disk.")
|
|
456
|
+
@click.option("--force", is_flag=True, help="Overwrite existing local files that differ.")
|
|
457
|
+
@click.option("--dry-run", is_flag=True, help="Show what would happen without making changes.")
|
|
458
|
+
@locked
|
|
459
|
+
def checkout(remotes: tuple[str, ...], local: Path | None, force: bool, dry_run: bool):
|
|
460
|
+
"""Start tracking REMOTES that are already in the repo (the reverse of add).
|
|
461
|
+
|
|
462
|
+
REMOTES are paths or glob patterns relative to files/ (quote globs
|
|
463
|
+
so syncdot matches them inside the repo). Each one is written to disk
|
|
464
|
+
and added to the manifest in a single commit; ones that can't be
|
|
465
|
+
checked out are reported and the rest are still checked out.
|
|
466
|
+
|
|
467
|
+
--local defaults to ~/<remote> (minus any .j2 suffix). If it ends with
|
|
468
|
+
/, is an existing directory, or several remotes are given, each
|
|
469
|
+
remote's name is kept inside it. An existing local file with different
|
|
470
|
+
content is left alone unless --force is given.
|
|
471
|
+
"""
|
|
472
|
+
cfg = load_config_or_exit()
|
|
473
|
+
syncer = Syncer(cfg, dry_run=dry_run)
|
|
474
|
+
try:
|
|
475
|
+
results = syncer.checkout(list(remotes), local, force)
|
|
476
|
+
except (ValueError, GitError, RenderError) as e:
|
|
477
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
478
|
+
sys.exit(1)
|
|
479
|
+
print_results(results, verbose=True, pending=dry_run)
|
|
480
|
+
for r in results:
|
|
481
|
+
if not r.error and not r.skipped:
|
|
482
|
+
dest = str(r.dest).replace(str(Path.home()), "~")
|
|
483
|
+
click.echo(f" Tracking {click.style(r.source, fg='cyan')} as {dest}")
|
|
484
|
+
if any(r.error for r in results):
|
|
485
|
+
sys.exit(1)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
# ── remove ─────────────────────────────────────────────────────────────────────
|
|
489
|
+
|
|
490
|
+
@cli.command()
|
|
491
|
+
@click.argument("paths", nargs=-1, required=True)
|
|
492
|
+
@click.option("--dry-run", is_flag=True, help="Show what would happen without making changes.")
|
|
493
|
+
@locked
|
|
494
|
+
def remove(paths: tuple[str, ...], dry_run: bool):
|
|
495
|
+
"""Stop tracking PATHS (files or directories).
|
|
496
|
+
|
|
497
|
+
Removes their manifest entries and their copies in the repo, in one
|
|
498
|
+
commit. The files on disk are left untouched, and may already be
|
|
499
|
+
deleted. Quoted globs are matched against tracked paths.
|
|
500
|
+
"""
|
|
501
|
+
cfg = load_config_or_exit()
|
|
502
|
+
syncer = Syncer(cfg, dry_run=dry_run)
|
|
503
|
+
try:
|
|
504
|
+
results = syncer.remove(list(paths))
|
|
505
|
+
except (ValueError, GitError) as e:
|
|
506
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
507
|
+
sys.exit(1)
|
|
508
|
+
print_results(results, verbose=True, pending=dry_run)
|
|
509
|
+
verb = "Would stop tracking" if dry_run else "No longer tracking"
|
|
510
|
+
for r in results:
|
|
511
|
+
click.echo(f" {verb} {click.style(r.source, fg='cyan')} (disk copy kept)")
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
# ── var ────────────────────────────────────────────────────────────────────────
|
|
515
|
+
|
|
516
|
+
@cli.group()
|
|
517
|
+
def var():
|
|
518
|
+
"""Manage template variables (vars.yaml on the active profile's branch)."""
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
@var.command("list")
|
|
522
|
+
@locked
|
|
523
|
+
def var_list():
|
|
524
|
+
"""List variables for the active profile."""
|
|
525
|
+
cfg = load_config_or_exit()
|
|
526
|
+
variables = Syncer(cfg, dry_run=True).var_list()
|
|
527
|
+
if not variables:
|
|
528
|
+
click.echo("No variables set. Add one with `syncdot var set name=value`.")
|
|
529
|
+
return
|
|
530
|
+
width = max(len(n) for n in variables)
|
|
531
|
+
for name, value in variables.items():
|
|
532
|
+
shown = value if isinstance(value, str) else yaml.safe_dump(
|
|
533
|
+
value, default_flow_style=True, width=float("inf")).strip().removesuffix("...").strip()
|
|
534
|
+
click.echo(f" {click.style(name.ljust(width), fg='cyan')} = {shown}")
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
@var.command("set")
|
|
538
|
+
@click.argument("assignments", nargs=-1, required=True, metavar="NAME=VALUE...")
|
|
539
|
+
@click.option("--yaml", "as_yaml", is_flag=True,
|
|
540
|
+
help="Parse values as YAML (numbers, booleans, lists) instead of plain strings.")
|
|
541
|
+
@click.option("--dry-run", is_flag=True, help="Show what would happen without making changes.")
|
|
542
|
+
@locked
|
|
543
|
+
def var_set(assignments: tuple[str, ...], as_yaml: bool, dry_run: bool):
|
|
544
|
+
"""Set template variables and re-render the templates that use them.
|
|
545
|
+
|
|
546
|
+
Values are stored as strings unless --yaml is given. Quote values with
|
|
547
|
+
spaces for your shell: syncdot var set fullname="Ariel Shatil".
|
|
548
|
+
"""
|
|
549
|
+
values = {}
|
|
550
|
+
for a in assignments:
|
|
551
|
+
name, sep, value = a.partition("=")
|
|
552
|
+
if not sep or not name:
|
|
553
|
+
click.echo(click.style(f"Expected NAME=VALUE, got {a!r}", fg="red"), err=True)
|
|
554
|
+
sys.exit(1)
|
|
555
|
+
if as_yaml:
|
|
556
|
+
try:
|
|
557
|
+
value = yaml.safe_load(value)
|
|
558
|
+
except yaml.YAMLError as e:
|
|
559
|
+
click.echo(click.style(f"Invalid YAML for {name}: {e}", fg="red"), err=True)
|
|
560
|
+
sys.exit(1)
|
|
561
|
+
values[name] = value
|
|
562
|
+
_run_var_edit(lambda syncer: syncer.var_set(values), "Would set" if dry_run else "Set",
|
|
563
|
+
list(values), dry_run)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
@var.command("unset")
|
|
567
|
+
@click.argument("names", nargs=-1, required=True)
|
|
568
|
+
@click.option("--force", is_flag=True, help="Unset even if a template still uses the variable.")
|
|
569
|
+
@click.option("--dry-run", is_flag=True, help="Show what would happen without making changes.")
|
|
570
|
+
@locked
|
|
571
|
+
def var_unset(names: tuple[str, ...], force: bool, dry_run: bool):
|
|
572
|
+
"""Remove template variables.
|
|
573
|
+
|
|
574
|
+
Refuses if a tracked template still uses one of them, since it could no
|
|
575
|
+
longer be rendered, unless --force is given.
|
|
576
|
+
"""
|
|
577
|
+
_run_var_edit(lambda syncer: syncer.var_unset(list(names), force),
|
|
578
|
+
"Would unset" if dry_run else "Unset", list(names), dry_run)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _run_var_edit(action, verb: str, names: list[str], dry_run: bool) -> None:
|
|
582
|
+
cfg = load_config_or_exit()
|
|
583
|
+
syncer = Syncer(cfg, dry_run=dry_run)
|
|
584
|
+
try:
|
|
585
|
+
results = action(syncer)
|
|
586
|
+
except (ValueError, GitError, RenderError) as e:
|
|
587
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
588
|
+
sys.exit(1)
|
|
589
|
+
click.echo(f"{verb} {', '.join(click.style(n, fg='cyan') for n in names)} "
|
|
590
|
+
f"(profile: {click.style(cfg.profile, fg='cyan')}).")
|
|
591
|
+
if results:
|
|
592
|
+
click.echo("\nUpdated files:" if not dry_run else "\nFiles to update:")
|
|
593
|
+
print_results(results, verbose=True, pending=dry_run)
|
|
594
|
+
if any(r.error for r in results):
|
|
595
|
+
sys.exit(1)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
# ── env ────────────────────────────────────────────────────────────────────────
|
|
599
|
+
|
|
600
|
+
@cli.group()
|
|
601
|
+
def env():
|
|
602
|
+
"""Manage environment variables for your session (env: in vars.yaml)."""
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
@env.command("list")
|
|
606
|
+
@locked
|
|
607
|
+
def env_list():
|
|
608
|
+
"""List environment variables for the active profile."""
|
|
609
|
+
cfg = load_config_or_exit()
|
|
610
|
+
rows = Syncer(cfg, dry_run=True).env_list()
|
|
611
|
+
if not rows:
|
|
612
|
+
click.echo("No environment variables set. Add one with `syncdot env set NAME=value`.")
|
|
613
|
+
return
|
|
614
|
+
width = max(len(r[0]) for r in rows)
|
|
615
|
+
for name, raw, rendered, error in rows:
|
|
616
|
+
line = f" {click.style(name.ljust(width), fg='cyan')} = {raw}"
|
|
617
|
+
if error:
|
|
618
|
+
line += click.style(f" ERROR: {error}", fg="red")
|
|
619
|
+
elif rendered != raw:
|
|
620
|
+
line += click.style(f" → {rendered}", fg="bright_black")
|
|
621
|
+
click.echo(line)
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
@env.command("set")
|
|
625
|
+
@click.argument("assignments", nargs=-1, required=True, metavar="NAME=VALUE...")
|
|
626
|
+
@click.option("--dry-run", is_flag=True, help="Show what would happen without making changes.")
|
|
627
|
+
@locked
|
|
628
|
+
def env_set(assignments: tuple[str, ...], dry_run: bool):
|
|
629
|
+
"""Set environment variables and regenerate the session environment.
|
|
630
|
+
|
|
631
|
+
Values may use template variables: syncdot env set GIT_AUTHOR_EMAIL='{{ email }}'
|
|
632
|
+
(single quotes keep your shell from touching them).
|
|
633
|
+
"""
|
|
634
|
+
values = {}
|
|
635
|
+
for a in assignments:
|
|
636
|
+
name, sep, value = a.partition("=")
|
|
637
|
+
if not sep or not name:
|
|
638
|
+
click.echo(click.style(f"Expected NAME=VALUE, got {a!r}", fg="red"), err=True)
|
|
639
|
+
sys.exit(1)
|
|
640
|
+
values[name] = value
|
|
641
|
+
_run_var_edit(lambda syncer: syncer.env_set(values), "Would set" if dry_run else "Set",
|
|
642
|
+
list(values), dry_run)
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
@env.command("unset")
|
|
646
|
+
@click.argument("names", nargs=-1, required=True)
|
|
647
|
+
@click.option("--dry-run", is_flag=True, help="Show what would happen without making changes.")
|
|
648
|
+
@locked
|
|
649
|
+
def env_unset(names: tuple[str, ...], dry_run: bool):
|
|
650
|
+
"""Remove environment variables."""
|
|
651
|
+
_run_var_edit(lambda syncer: syncer.env_unset(list(names)),
|
|
652
|
+
"Would unset" if dry_run else "Unset", list(names), dry_run)
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
@env.command("hook")
|
|
656
|
+
def env_hook():
|
|
657
|
+
"""Print the line that loads syncdot's environment in your shell."""
|
|
658
|
+
cfg = load_config_or_exit()
|
|
659
|
+
path = str(Syncer(cfg, dry_run=True).env_path).replace(str(Path.home()), "~", 1)
|
|
660
|
+
click.echo(f"The systemd user session reads {path} by itself.")
|
|
661
|
+
click.echo("For shells, add this line to ~/.profile (login shells, SSH), and to")
|
|
662
|
+
click.echo("~/.bashrc or ~/.zshrc to have it in every interactive shell too:\n")
|
|
663
|
+
click.echo(f" [ -r {path} ] && {{ set -a; . {path}; set +a; }}\n")
|
|
664
|
+
click.echo("Open a new shell to pick up changes.")
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
# ── profile ────────────────────────────────────────────────────────────────────
|
|
668
|
+
|
|
669
|
+
@cli.group()
|
|
670
|
+
def profile():
|
|
671
|
+
"""Manage profiles (git branches)."""
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
@profile.command("list")
|
|
675
|
+
@locked
|
|
676
|
+
def profile_list():
|
|
677
|
+
"""List available profiles."""
|
|
678
|
+
cfg = load_config_or_exit()
|
|
679
|
+
repo = Repo(cfg.repo_path)
|
|
680
|
+
result = repo._run("branch", "-a")
|
|
681
|
+
branches = [b.strip().lstrip("* ") for b in result.stdout.splitlines()]
|
|
682
|
+
profiles = [b.removeprefix("remotes/origin/").removeprefix("profiles/") for b in branches
|
|
683
|
+
if b.removeprefix("remotes/origin/") == "base" or "profiles/" in b]
|
|
684
|
+
profiles = sorted(set(profiles), key=lambda p: (p != "base", p))
|
|
685
|
+
|
|
686
|
+
click.echo("Available profiles:\n")
|
|
687
|
+
for p in profiles:
|
|
688
|
+
marker = click.style(" ← active", fg="green") if p == cfg.profile else ""
|
|
689
|
+
click.echo(f" {p}{marker}")
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
@profile.command("set")
|
|
693
|
+
@click.argument("name")
|
|
694
|
+
@locked
|
|
695
|
+
def profile_set(name: str):
|
|
696
|
+
"""Switch the active profile."""
|
|
697
|
+
cfg = load_config_or_exit()
|
|
698
|
+
branch = profile_branch(name)
|
|
699
|
+
repo = Repo(cfg.repo_path)
|
|
700
|
+
|
|
701
|
+
if not repo.branch_exists(branch) and not repo.branch_exists(branch, remote=True):
|
|
702
|
+
click.echo(click.style(f"Profile {name!r} does not exist. Use `syncdot profile new {name}` to create it.", fg="red"), err=True)
|
|
703
|
+
sys.exit(1)
|
|
704
|
+
|
|
705
|
+
# Rewrite config with new profile
|
|
706
|
+
with CONFIG_PATH.open() as f:
|
|
707
|
+
data = yaml.safe_load(f)
|
|
708
|
+
data["profile"] = name
|
|
709
|
+
with CONFIG_PATH.open("w") as f:
|
|
710
|
+
yaml.dump(data, f, default_flow_style=False)
|
|
711
|
+
|
|
712
|
+
click.echo(f"Active profile set to {click.style(name, fg='cyan')}.")
|
|
713
|
+
click.echo("Run `syncdot pull` to apply the new profile to disk.")
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
@profile.command("new")
|
|
717
|
+
@click.argument("name")
|
|
718
|
+
@locked
|
|
719
|
+
def profile_new(name: str):
|
|
720
|
+
"""Create a new profile branch from base."""
|
|
721
|
+
cfg = load_config_or_exit()
|
|
722
|
+
repo = Repo(cfg.repo_path)
|
|
723
|
+
try:
|
|
724
|
+
repo.create_profile_branch(name)
|
|
725
|
+
click.echo(f"Created profile {click.style(name, fg='cyan')} (branch: profiles/{name}).")
|
|
726
|
+
click.echo("Switch to it with `syncdot profile set` and edit files/ or vars.yaml on that")
|
|
727
|
+
click.echo("branch to override base. Changes to base are merged in on every sync.")
|
|
728
|
+
except GitError as e:
|
|
729
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
730
|
+
sys.exit(1)
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
# ── service ────────────────────────────────────────────────────────────────────
|
|
734
|
+
|
|
735
|
+
@cli.group()
|
|
736
|
+
def service():
|
|
737
|
+
"""Manage the systemd user service."""
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
@service.command("install")
|
|
741
|
+
def service_install():
|
|
742
|
+
"""Sync automatically at login (systemd user service)."""
|
|
743
|
+
_run_systemd(systemd.install)
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
@service.command("uninstall")
|
|
747
|
+
def service_uninstall():
|
|
748
|
+
"""Stop syncing automatically at login."""
|
|
749
|
+
_run_systemd(systemd.uninstall)
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
@service.command("status")
|
|
753
|
+
def service_status():
|
|
754
|
+
"""Show the status of the login service."""
|
|
755
|
+
_run_systemd(lambda: [systemd.status()])
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def _run_systemd(action) -> None:
|
|
759
|
+
try:
|
|
760
|
+
for line in action():
|
|
761
|
+
click.echo(line)
|
|
762
|
+
except systemd.SystemdError as e:
|
|
763
|
+
click.echo(click.style(str(e), fg="red"), err=True)
|
|
764
|
+
sys.exit(1)
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
if __name__ == "__main__":
|
|
768
|
+
cli()
|