Module: Twin::CLI
- Defined in:
- lib/twin/cli.rb
Constant Summary collapse
- USAGE =
<<~TXT twin — sync configuration files between machines USAGE: twin interactive picker (all sync-files) twin <name> picker — sync-file by name in sync_dir twin <path> picker — file or directory (absolute or relative) twin list [--all] [--label X] [--file X] [--json] twin status [--all] [--label X] [--file X] [--json] twin sync [-p PATTERN] [--label X] [--file X] [--all] [--dry-run] [--quiet] [-v] [--skip-unavailable] [--force] [--skip-conflicts] twin add <path> scaffold a new sync entry for a local path twin log [-n N] [--json] recent journal entries (default 20) twin doctor check tools, renderers, and sync targets twin --help show this message twin --version show the running version FILE ARGUMENT: bare name (no /) → matched by substring against sync-file names contains / → resolved as path; file or directory both work TARGET-SIDE CHANGES: Before syncing, twin looks for files the target changed more recently AND whose content differs, then asks once for the whole program. --force overwrite them without asking (for automation) --skip-conflicts leave them alone, sync everything else CONFIG: ~/.config/twin/config.yaml TWIN_SYNC_DIR overrides sync_dir TWIN_CONFIG overrides config path TXT
Class Method Summary collapse
-
.cmd_add(cfg, args) ⇒ Object
── add ────────────────────────────────────────────────────────────────────.
-
.cmd_doctor(cfg) ⇒ Object
── doctor ─────────────────────────────────────────────────────────────────.
-
.cmd_list(cfg, args) ⇒ Object
── list / status ──────────────────────────────────────────────────────────.
-
.cmd_log(args) ⇒ Object
── log ────────────────────────────────────────────────────────────────────.
- .cmd_status(cfg, args) ⇒ Object
-
.cmd_sync(cfg, args) ⇒ Object
── sync ───────────────────────────────────────────────────────────────────.
- .format_age(seconds) ⇒ Object
- .job_to_hash(j) ⇒ Object
-
.parse_filter_opts(args) ⇒ Object
── option parsing ─────────────────────────────────────────────────────────.
- .parse_sync_opts(args) ⇒ Object
-
.pick_and_sync(cfg, file:) ⇒ Object
── picker → sync ──────────────────────────────────────────────────────────.
- .program_to_hash(p) ⇒ Object
- .report_conflicts(conflicts) ⇒ Object
-
.resolve_conflicts(cfg, jobs, dry_run:, quiet:, force:, skip_conflicts:) ⇒ Object
Settle what happens to files the target changed more recently, before any job runs.
- .run(argv) ⇒ Object
- .show_diffs(conflicts) ⇒ Object
-
.sync_jobs(cfg, program, jobs, dry_run: false, quiet: false, skip_unavailable: false, force: false, skip_conflicts: false, verbose: false) ⇒ Object
Sync the given jobs.
-
.target_availability(job) ⇒ Object
:ok, or a human-readable reason the target can't be synced right now.
- .tool_available?(name) ⇒ Boolean
Class Method Details
.cmd_add(cfg, args) ⇒ Object
── add ────────────────────────────────────────────────────────────────────
331 332 333 334 335 336 |
# File 'lib/twin/cli.rb', line 331 def cmd_add(cfg, args) result = Twin::Add.run(cfg, args) return unless result && result[:dry_run] cmd_sync(cfg, ["-p", result[:program], "--file=#{File.basename(result[:file])}", "--dry-run"]) end |
.cmd_doctor(cfg) ⇒ Object
── doctor ─────────────────────────────────────────────────────────────────
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 |
# File 'lib/twin/cli.rb', line 370 def cmd_doctor(cfg) ok = true # First line, because "which version am I actually running" is the # question behind a surprising number of the others. puts "twin #{Twin::VERSION}" puts puts "Tools" %w[grubber rsync fzf].each do |bin| if tool_available?(bin) puts " ✓ #{bin}" else puts " ✗ #{bin} (required — not found in PATH)" ok = false end end puts "\nRenderers (preview)" found_renderer = false %w[apex glow bat].each do |bin| if tool_available?(bin) puts " ✓ #{bin}" found_renderer = true else puts " – #{bin} (not installed)" end end puts " ⚠ no renderer found — file preview will fall back to cat" unless found_renderer puts "\nTemplating" if cfg.hosts.empty? puts " – no hosts configured" else %i[host target].each do |attr| name = cfg.send(attr) if name.empty? puts " ✗ #{attr} not set in config" ok = false elsif cfg.hosts.key?(name) puts " ✓ #{attr}: #{name}" else puts " ✗ #{attr} #{name.inspect} not found in hosts" ok = false end end end puts "\nTargets" begin programs = Scanner.load_programs(cfg, show_all: true) puts " ✓ all template tokens resolved" unless cfg.hosts.empty? targets = programs.flat_map(&:jobs).map(&:target).uniq.sort if targets.empty? puts " (no programs loaded)" else targets.each do |tgt| if Twin::Remote.remote?(tgt) host, = Twin::Remote.split(tgt) if Twin::Remote.reachable?(host) puts " ✓ #{tgt} (ssh)" else puts " ✗ #{tgt} (ssh: #{host} not reachable)" ok = false end elsif Twin::Sync.mounted?(tgt) puts " ✓ #{tgt}" else puts " ✗ #{tgt} (not mounted)" ok = false end end end rescue => e puts " ✗ #{e.}" ok = false end puts ok ? "\nAll checks passed." : "\nSome checks failed." exit 1 unless ok end |
.cmd_list(cfg, args) ⇒ Object
── list / status ──────────────────────────────────────────────────────────
135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/twin/cli.rb', line 135 def cmd_list(cfg, args) opts = parse_filter_opts(args) programs = Scanner.load_programs(cfg, **opts.slice(:file, :label, :show_all)) if opts[:json] puts JSON.pretty_generate(programs.map { |p| program_to_hash(p) }) return end programs.each do |p| mark = p.status == :disabled ? "–" : "✓" puts "#{mark} #{p.name} — #{p.description}" end end |
.cmd_log(args) ⇒ Object
── log ────────────────────────────────────────────────────────────────────
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 |
# File 'lib/twin/cli.rb', line 340 def cmd_log(args) n = 20 json = false OptionParser.new do |o| o.on("-n N", Integer) { |v| n = v } o.on("--json") { json = true } end.parse!(args) entries = Twin::Journal.tail(n) if json puts JSON.pretty_generate(entries) return end if entries.empty? puts "journal is empty (#{Twin::Journal.log_path})" return end tty = $stdout.tty? entries.each do |e| ts = Time.parse(e["ts"]).strftime("%Y-%m-%d %H:%M:%S") mark = e["ok"] ? "✓" : "✗" mark = Picker.colorize(e["ok"] ? :in_sync : :both_missing, mark) if tty note = e["ok"] ? (e["changed"] ? "changed" : "no-op") : "error: #{e["error"]}" puts "#{ts} #{mark} #{e["program"]} #{e["path"]} (#{note})" end end |
.cmd_status(cfg, args) ⇒ Object
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
# File 'lib/twin/cli.rb', line 150 def cmd_status(cfg, args) opts = parse_filter_opts(args) programs = Scanner.load_programs(cfg, **opts.slice(:file, :label, :show_all)) if opts[:json] puts JSON.pretty_generate(programs.map { |p| program_to_hash(p) }) return end tty = $stdout.tty? programs.each do |p| icon = Picker::STATUS_ICONS[p.status] || "?" icon = Picker.colorize(p.status, icon) if tty name = tty ? Picker.bold(p.name) : p.name puts "#{icon} #{name}" p.jobs.each do |j| src = j.source_exists ? j.source_mtime.strftime("%Y-%m-%d %H:%M:%S") : "(not found)" tgt = j.target_exists ? j.target_mtime.strftime("%Y-%m-%d %H:%M:%S") : "(not found)" tgt = "(unreachable)" if j.target_unreachable conflict = j.conflict ? (tty ? " #{Picker.colorize(:target_newer, "!")}" : " !") : "" puts " #{j.path}#{conflict}" puts " src #{src}" puts " dst #{tgt}" # Named, not hidden: these belong to the target on purpose. puts " own #{j.owned.join(', ')}" unless j.owned.nil? || j.owned.empty? end end end |
.cmd_sync(cfg, args) ⇒ Object
── sync ───────────────────────────────────────────────────────────────────
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/twin/cli.rb', line 181 def cmd_sync(cfg, args) opts = parse_sync_opts(args) programs = Scanner.load_programs(cfg, **opts.slice(:file, :label, :show_all)) if opts[:pattern] programs = programs.select { |p| p.name.downcase.include?(opts[:pattern].downcase) } end if programs.empty? puts "no matching programs" unless opts[:quiet] return end results = programs.map do |p| sync_jobs(cfg, p, p.active_jobs, dry_run: opts[:dry_run], quiet: opts[:quiet], skip_unavailable: opts[:skip_unavailable], force: opts[:force], skip_conflicts: opts[:skip_conflicts], verbose: opts[:verbose]) end exit 1 unless results.all? end |
.format_age(seconds) ⇒ Object
309 310 311 312 313 314 315 |
# File 'lib/twin/cli.rb', line 309 def format_age(seconds) s = seconds.to_i.abs return "#{s}s" if s < 90 return "#{s / 60}m" if s < 5400 return "#{s / 3600}h" if s < 172_800 "#{s / 86_400}d" end |
.job_to_hash(j) ⇒ Object
499 500 501 502 503 504 505 |
# File 'lib/twin/cli.rb', line 499 def job_to_hash(j) h = j.to_h h[:status] = j.status h[:source_mtime] = j.source_mtime&.iso8601 h[:target_mtime] = j.target_mtime&.iso8601 h end |
.parse_filter_opts(args) ⇒ Object
── option parsing ─────────────────────────────────────────────────────────
458 459 460 461 462 463 464 465 466 467 |
# File 'lib/twin/cli.rb', line 458 def parse_filter_opts(args) opts = { show_all: false, label: nil, file: nil, json: false } OptionParser.new do |o| o.on("--all") { opts[:show_all] = true } o.on("--label=L") { |v| opts[:label] = v } o.on("--file=F") { |v| opts[:file] = v } o.on("--json") { opts[:json] = true } end.parse!(args) opts end |
.parse_sync_opts(args) ⇒ Object
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 |
# File 'lib/twin/cli.rb', line 469 def parse_sync_opts(args) opts = { show_all: false, label: nil, file: nil, pattern: nil, dry_run: false, quiet: false, skip_unavailable: false, force: false, skip_conflicts: false, verbose: false } OptionParser.new do |o| o.on("--all") { opts[:show_all] = true } o.on("--label=L") { |v| opts[:label] = v } o.on("--file=F") { |v| opts[:file] = v } o.on("-v", "--verbose") { opts[:verbose] = true } o.on("--force") { opts[:force] = true } o.on("--skip-conflicts") { opts[:skip_conflicts] = true } o.on("-p", "--pattern=P") { |v| opts[:pattern] = v } o.on("--dry-run") { opts[:dry_run] = true } o.on("-q", "--quiet") { opts[:quiet] = true } o.on("--skip-unavailable") { opts[:skip_unavailable] = true } end.parse!(args) opts end |
.pick_and_sync(cfg, file:) ⇒ Object
── picker → sync ──────────────────────────────────────────────────────────
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
# File 'lib/twin/cli.rb', line 84 def pick_and_sync(cfg, file:) # fzf without a terminal does not fail — it waits, silently, for input # that will never come. Every unattended caller lands here: cron, # `ssh host twin …`, an agent running commands. Say so and point at the # command that does work. unless $stdin.tty? && $stdout.tty? warn "twin: the picker needs a terminal." warn " use `twin sync#{file ? " --file=#{file}" : ""}` for an unattended run" \ " (add --dry-run to preview)." exit 1 end programs = Scanner.load_programs(cfg, file: file, show_all: false) if programs.empty? warn "no active programs found#{" in #{file}" if file}" return end selected_key = nil # [name, sync_file] of last program — used to re-enter loop do program = if selected_key programs.find { |p| [p.name, p.sync_file] == selected_key } else Picker.pick_program(programs) end return unless program jobs = Picker.pick_paths(program, cfg) if jobs == :back # ESC in stage 2 → back to stage 1 selected_key = nil next end if jobs.empty? # Enter without selection → exit return end sync_jobs(cfg, program, jobs) print "\npress Enter to continue, q to quit " $stdout.flush break if $stdin.gets&.strip == "q" # reload so status reflects what was just synced, stay on this program programs = Scanner.load_programs(cfg, file: file, show_all: false) selected_key = [program.name, program.sync_file] end end |
.program_to_hash(p) ⇒ Object
488 489 490 491 492 493 494 495 496 497 |
# File 'lib/twin/cli.rb', line 488 def program_to_hash(p) { name: p.name, status: p.status, sync_file: p.sync_file, label: p.label, description: p.description, jobs: p.jobs.map { |j| job_to_hash(j) }, } end |
.report_conflicts(conflicts) ⇒ Object
291 292 293 294 295 296 297 298 299 |
# File 'lib/twin/cli.rb', line 291 def report_conflicts(conflicts) warn "target has changed since the last sync — #{conflicts.size} file(s) differ:" conflicts.each do |c| delta = c.age_delta age = delta ? " (target #{format_age(delta)} newer)" : "" warn " ! #{c.job.path == c.rel ? c.rel : File.join(c.job.path, c.rel)}#{age}" end warn "syncing would replace them with the source version." end |
.resolve_conflicts(cfg, jobs, dry_run:, quiet:, force:, skip_conflicts:) ⇒ Object
Settle what happens to files the target changed more recently, before any job runs. Returns true (overwrite them), false (leave them, --update keeps them) or :abort (sync nothing at all).
The mtime pre-filter on each Job is coarse and fires often; only files whose content really differs reach the prompt. A prompt that cries wolf gets answered without reading it.
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/twin/cli.rb', line 263 def resolve_conflicts(cfg, jobs, dry_run:, quiet:, force:, skip_conflicts:) return true if force return false if skip_conflicts || dry_run conflicts = jobs.flat_map { |j| Twin::Conflict.detect(cfg, j) } return false if conflicts.empty? report_conflicts(conflicts) unless $stdin.tty? && $stdout.tty? warn "" warn "abort: target has changes of its own and there is no terminal to ask." warn " re-run with --force to overwrite them, or --skip-conflicts to keep them." return :abort end loop do print "\noverwrite these on the target and sync? [y]es / [d]iff / [n]o (abort) " $stdout.flush case $stdin.gets&.strip&.downcase when "y", "yes" then return true when "n", "no", "", nil then puts "aborted — nothing was synced."; return :abort when "d", "diff" then show_diffs(conflicts) else puts "please answer y, d or n." end end end |
.run(argv) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/twin/cli.rb', line 51 def run(argv) cfg = Twin::Config.load cfg.validate! first = argv.first case first when nil pick_and_sync(cfg, file: nil) when "list" then cmd_list(cfg, argv.drop(1)) when "status" then cmd_status(cfg, argv.drop(1)) when "sync" then cmd_sync(cfg, argv.drop(1)) when "add" then cmd_add(cfg, argv.drop(1)) when "log" then cmd_log(argv.drop(1)) when "doctor" then cmd_doctor(cfg) when "-h", "--help", "help" puts USAGE when "-V", "--version", "version" puts "twin #{Twin::VERSION}" when /\A-/ warn "unknown option: #{first}" warn "Run 'twin --help' for usage." exit 1 else # Treat as file.md or directory path pick_and_sync(cfg, file: first) end rescue => e warn "error: #{e.}" exit 1 end |
.show_diffs(conflicts) ⇒ Object
301 302 303 304 305 306 307 |
# File 'lib/twin/cli.rb', line 301 def show_diffs(conflicts) conflicts.each do |c| puts puts "── #{c.rel} " + "─" * [0, 60 - c.rel.length].max puts Twin::Conflict.diff(c) end end |
.sync_jobs(cfg, program, jobs, dry_run: false, quiet: false, skip_unavailable: false, force: false, skip_conflicts: false, verbose: false) ⇒ Object
Sync the given jobs. Returns true when every attempted job succeeded. quiet: print only conflicts, errors, and jobs that changed something verbose: print rsync's full output instead of just the changes skip_unavailable: skip jobs whose target is unmounted/unreachable instead of aborting
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/twin/cli.rb', line 208 def sync_jobs(cfg, program, jobs, dry_run: false, quiet: false, skip_unavailable: false, force: false, skip_conflicts: false, verbose: false) jobs = jobs.select { |j| j.active == 1 } return true if jobs.empty? # one availability check per unique target root: # local targets must be mounted volumes, remote ones reachable via ssh availability = {} jobs.each { |j| availability[j.target] ||= target_availability(j) } jobs, unavailable = jobs.partition { |j| availability[j.target] == :ok } unavailable.map { |j| availability[j.target] }.uniq.each do |reason| if skip_unavailable puts "skipped: #{reason}" unless quiet else warn "abort: #{reason}" exit 1 end end return true if jobs.empty? # Decide about target-side changes BEFORE the first byte moves: a partly # applied program is worse than none at all. resolve_conflicts returns # false when the run must not happen. force = resolve_conflicts(cfg, jobs, dry_run: dry_run, quiet: quiet, force: force, skip_conflicts: skip_conflicts) return false if force == :abort header_printed = false all_ok = true jobs.each do |job| success, output, transferred = Twin::Sync.run_job(cfg, job, dry_run: dry_run, force: force) Twin::Journal.record(job, success: success, transferred: transferred, output: output) unless dry_run all_ok &&= success next if quiet && success && !transferred unless header_printed puts "→ #{program.name}" header_printed = true end puts " • #{job.path}" shown = verbose || !success ? output : Twin::Sync.summarize(output.to_s) puts shown.gsub(/^/, " ") if shown && !shown.strip.empty? warn " error syncing #{job.path}" unless success end all_ok end |
.target_availability(job) ⇒ Object
:ok, or a human-readable reason the target can't be synced right now.
318 319 320 321 322 323 324 325 326 327 |
# File 'lib/twin/cli.rb', line 318 def target_availability(job) if job.remote? host, = Twin::Remote.split(job.target) return :ok if Twin::Remote.reachable?(host) "#{host} is not reachable via ssh" else return :ok if Twin::Sync.mounted?(job.target) "#{job.target} is not a mounted volume" end end |
.tool_available?(name) ⇒ Boolean
452 453 454 |
# File 'lib/twin/cli.rb', line 452 def tool_available?(name) system("command -v #{name} > /dev/null 2>&1") end |