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, targets, remote hosts
    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

Class Method Details

.cmd_add(cfg, args) ⇒ Object

── add ────────────────────────────────────────────────────────────────────



381
382
383
384
385
386
# File 'lib/twin/cli.rb', line 381

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 ─────────────────────────────────────────────────────────────────



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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/twin/cli.rb', line 420

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
      reachable_hosts = []
      targets.each do |tgt|
        if Twin::Remote.remote?(tgt)
          host, = Twin::Remote.split(tgt)
          if Twin::Remote.reachable?(host)
            puts "#{tgt}  (ssh)"
            reachable_hosts << host
          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
      ok = doctor_remote_tools(reachable_hosts.uniq) && ok
    end
  rescue => e
    puts "#{e.message}"
    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 ────────────────────────────────────────────────────────────────────



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
# File 'lib/twin/cli.rb', line 390

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
178
179
180
181
182
183
184
# 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))
  verify_drift(cfg, programs)

  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|
      conflict = j.conflict ? (tty ? "  #{Picker.colorize(:target_newer, "!")}" : "  !") : ""
      puts "    #{j.path}#{conflict}"
      if j.directory
        # Directory mtimes prove nothing — the drift verdict replaces them.
        puts "      #{j.drift ? drift_summary(j.drift) : "(not checked — target unavailable)"}"
      else
        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
        puts "      src #{src}"
        puts "      dst #{tgt}"
        puts "      content identical, timestamps differ" if j.content_equal
      end
      # 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 ───────────────────────────────────────────────────────────────────



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/twin/cli.rb', line 231

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

.doctor_remote_tools(hosts) ⇒ Object

Probe each reachable ssh host once for what the far side must provide. A missing rsync fails doctor — the first sync would die mid-run with a raw protocol error. Missing stat/date or md5/md5sum only degrade (unknown mtimes, conservative conflicts), so they warn and say so.



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
# File 'lib/twin/cli.rb', line 513

def doctor_remote_tools(hosts)
  return true if hosts.empty?
  ok = true
  puts "\nRemote tools"
  hosts.each do |host|
    tools = Twin::Remote.preflight(host)
    if tools.nil?
      puts "#{host}  (probe failed)"
      ok = false
      next
    end
    problems = []
    unless tools["rsync"]
      problems << "rsync missing — syncs will fail (OpenWrt: opkg install rsync)"
      ok = false
    end
    unless tools["stat"] || tools["date"]
      problems << "no stat or date — remote mtimes read as unknown"
    end
    unless tools["md5"] || tools["md5sum"]
      problems << "no md5 or md5sum — timestamp-only files stay flagged as conflicts"
    end
    if problems.empty?
      have = ["rsync", tools["stat"] ? "stat" : "date", tools["md5"] ? "md5" : "md5sum"]
      puts "#{host}  (#{have.join(', ')})"
    else
      puts "  #{tools["rsync"] ? "" : ""}  #{host}  #{problems.join('; ')}"
    end
  end
  ok
end

.drift_summary(d) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/twin/cli.rb', line 212

def drift_summary(d)
  if d.in_sync?
    note = d.time_only.empty? ? "" : " (#{d.time_only.size} timestamp-only)"
    return "in sync#{note}"
  end
  parts = []
  parts << "#{d.pending.size} to sync: #{list_some(d.pending)}" unless d.pending.empty?
  unless d.conflicts.empty?
    parts << "#{d.conflicts.size} changed on target: #{list_some(d.conflicts.map(&:rel))} (twin sync will ask)"
  end
  parts.join("; ")
end

.format_age(seconds) ⇒ Object



359
360
361
362
363
364
365
# File 'lib/twin/cli.rb', line 359

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



588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/twin/cli.rb', line 588

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[:drift]        = j.drift && {
    pending:   j.drift.pending,
    time_only: j.drift.time_only,
    conflicts: j.drift.conflicts.map(&:rel),
  }
  h
end

.list_some(rels, max = 3) ⇒ Object



225
226
227
# File 'lib/twin/cli.rb', line 225

def list_some(rels, max = 3)
  rels.take(max).join(", ") + (rels.size > max ? ", …" : "")
end

.parse_filter_opts(args) ⇒ Object

── option parsing ─────────────────────────────────────────────────────────



547
548
549
550
551
552
553
554
555
556
# File 'lib/twin/cli.rb', line 547

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



558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'lib/twin/cli.rb', line 558

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



577
578
579
580
581
582
583
584
585
586
# File 'lib/twin/cli.rb', line 577

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



341
342
343
344
345
346
347
348
349
# File 'lib/twin/cli.rb', line 341

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.



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/twin/cli.rb', line 313

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.message}"
  exit 1
end

.show_diffs(conflicts) ⇒ Object



351
352
353
354
355
356
357
# File 'lib/twin/cli.rb', line 351

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



258
259
260
261
262
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/twin/cli.rb', line 258

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.



368
369
370
371
372
373
374
375
376
377
# File 'lib/twin/cli.rb', line 368

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

Returns:

  • (Boolean)


505
506
507
# File 'lib/twin/cli.rb', line 505

def tool_available?(name)
  system("command -v #{name} > /dev/null 2>&1")
end

.verify_drift(cfg, programs) ⇒ Object

Ask rsync what a sync of each directory job would actually do — the dry-runs are subprocess I/O, so a few run in parallel. File jobs are already content-checked by the scanner and need no second look.



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/twin/cli.rb', line 189

def verify_drift(cfg, programs)
  jobs = programs.flat_map(&:jobs).select do |j|
    j.directory && j.active == 1 && !j.target_unreachable &&
      j.source_exists && j.target_exists
  end
  return if jobs.empty?

  queue = Queue.new
  jobs.each { |j| queue << j }
  Array.new([4, jobs.size].min) do
    Thread.new do
      loop do
        j = begin
          queue.pop(true)
        rescue ThreadError
          break
        end
        j.drift = Twin::Conflict.drift(cfg, j)
      end
    end
  end.each(&:join)
end