Module: Twin::Scanner

Defined in:
lib/twin/scanner.rb

Class Method Summary collapse

Class Method Details

.build_job(r, vars = {}) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
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
185
186
187
188
189
190
# File 'lib/twin/scanner.rb', line 138

def build_job(r, vars = {})
  path              = r["Path"].to_s
  source            = r["Source"].to_s
  target            = r["Target"].to_s
  target_path_field = r["Target-Path"].then { |v| v.to_s.empty? ? nil : v.to_s }
  return nil if path.empty? || source.empty? || target.empty?

  render   = r["Render"] == true
  excludes = (r["Exclude"] || "").split(",").map(&:strip).reject(&:empty?)
  remote   = Twin::Remote.remote?(target)

  if render && remote
    raise "#{r["Program"]}: Render is not supported for remote targets (#{target})"
  end

  src_full = File.join(source, path)
  tgt_full = File.join(target, target_path_field || path)
  src_exists, src_mtime = stat(src_full)
  # Remote targets are stat'ed in one batched ssh call after all jobs are
  # built (fill_remote_stats) — until then they read as missing.
  tgt_exists, tgt_mtime = remote ? [false, nil] : stat(tgt_full)

  # Render jobs: status is content-based (mtime is meaningless for a rendered
  # target). conflict stays false so the mtime conflict-warning skips them.
  render_outdated = render ? render_outdated?(src_full, tgt_full, vars, path) : nil

  # Same 60s tolerance as Job#status, so mtime jitter never flags a conflict.
  conflict = !render && src_exists && tgt_exists && tgt_mtime && src_mtime &&
             tgt_mtime - src_mtime >= 60

  Job.new(
    program:          r["Program"].to_s,
    path:             path,
    description:      r["Description"].to_s,
    active:           (r["Active"] || 0).to_i,
    excludes:         excludes,
    label:            r["Label"].to_s,
    source:           source,
    target:           target,
    cmd:              r["Cmd"].to_s,
    delete:           r["Delete"] == true,
    render:           render,
    render_outdated:  render_outdated,
    target_path_field: target_path_field,
    sync_file:        r["_note_file"].to_s,
    source_exists:    src_exists,
    target_exists:    tgt_exists,
    source_mtime:     src_mtime,
    target_mtime:     tgt_mtime,
    conflict:         !!conflict,
    target_unreachable: false,
  )
end

.fill_remote_stats(jobs) ⇒ Object

Remote targets can't be stat'ed locally — batch them into one ssh round-trip per host. A failed ssh marks the jobs unreachable instead of aborting the scan (local jobs stay usable).



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/twin/scanner.rb', line 88

def fill_remote_stats(jobs)
  jobs.select { |j| j.remote? && j.active == 1 }
      .group_by { |j| Twin::Remote.split(j.target).first }
      .each do |host, host_jobs|
    stats = Twin::Remote.stat_paths(host, host_jobs.map { |j| Twin::Remote.split(j.target_path).last })
    host_jobs.each do |j|
      rpath = Twin::Remote.split(j.target_path).last
      if stats.nil?
        j.target_unreachable = true
        next
      end
      mtime = stats[rpath]
      j.target_exists = !mtime.nil?
      j.target_mtime  = mtime
      j.conflict      = j.source_exists && mtime && j.source_mtime &&
                        mtime - j.source_mtime >= 60
    end
  end
end

.group(jobs) ⇒ Object



133
134
135
136
# File 'lib/twin/scanner.rb', line 133

def group(jobs)
  jobs.group_by { |j| [j.program, j.sync_file] }
      .map { |(name, _file), js| Program.new(name: name, jobs: js) }
end

.load_jobs(cfg, scan_path: nil) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/twin/scanner.rb', line 62

def load_jobs(cfg, scan_path: nil)
  raise "grubber not found in PATH" unless system("command -v grubber > /dev/null 2>&1")

  dir = scan_path || cfg.sync_dir
  stdout, stderr, status = Open3.capture3(
    "grubber", "extract", dir, "-b", "--format", "json"
  )
  raise "grubber: #{stderr.force_encoding('UTF-8').strip}" unless status.success?

  begin
    records = JSON.parse(stdout.force_encoding("UTF-8"))
  rescue JSON::ParserError => e
    raise "grubber returned invalid JSON: #{e.message}"
  end
  vars = cfg.var_map
  jobs = records.filter_map do |r|
    context = "#{r["Program"]} in #{File.basename(r["_note_file"].to_s)}"
    build_job(Twin::Template.substitute_record(r, vars, context: context), vars)
  end
  fill_remote_stats(jobs)
  jobs
end

.load_programs(cfg, file: nil, label: nil, show_all: false) ⇒ Object



108
109
110
111
112
113
114
115
# File 'lib/twin/scanner.rb', line 108

def load_programs(cfg, file: nil, label: nil, show_all: false)
  scan_path, name_filter = resolve_file_arg(cfg, file)
  jobs = load_jobs(cfg, scan_path: scan_path)
  jobs = jobs.select { |j| j.sync_file.include?(name_filter) } if name_filter
  jobs = jobs.select { |j| j.label == label }                   if label && !label.empty?
  jobs = jobs.select { |j| j.active == 1 }                     unless show_all
  group(jobs)
end

.render_outdated?(src_full, tgt_full, vars, context) ⇒ Boolean

For a render job: is the target out of date with the rendered template? nil when source is missing/a directory (status falls through to those). True when target is absent or content differs, or the template can't be rendered (unresolved token) — i.e. needs attention.

Returns:

  • (Boolean)


203
204
205
206
207
208
209
# File 'lib/twin/scanner.rb', line 203

def render_outdated?(src_full, tgt_full, vars, context)
  return nil unless File.file?(src_full)
  rendered = Twin::Template.render_file(src_full, vars, context: context)
  !File.exist?(tgt_full) || File.binread(tgt_full) != rendered
rescue
  true
end

.resolve_file_arg(cfg, file) ⇒ Object

Returns [scan_path, name_filter] for a given file argument.

  • nil / empty → [nil, nil] scan sync_dir, no filter
  • path to a dir → [dir, nil] scan that dir, no filter
  • path to a file → [dirname, basename] scan parent dir, filter by filename
  • bare name (no /) → [nil, name] scan sync_dir, filter by name


122
123
124
125
126
127
128
129
130
131
# File 'lib/twin/scanner.rb', line 122

def resolve_file_arg(cfg, file)
  return [nil, nil] if file.nil? || file.empty?
  if file.include?("/") || file == "." || file == ".."
    expanded = File.expand_path(file)
    return [expanded, nil]                             if File.directory?(expanded)
    return [File.dirname(expanded), File.basename(expanded)] if File.file?(expanded)
    raise "not found: #{file}"
  end
  [nil, file]
end

.stat(path) ⇒ Object



192
193
194
195
196
197
# File 'lib/twin/scanner.rb', line 192

def stat(path)
  st = File.stat(path)
  [true, st.mtime]
rescue Errno::ENOENT, Errno::EACCES
  [false, nil]
end