Module: NA::Plugins

Defined in:
lib/na/plugins.rb

Overview

Plugins module for NA

Class Method Summary collapse

Class Method Details

.action_name?(name) ⇒ Boolean

Returns:

  • (Boolean)


357
358
359
360
361
# File 'lib/na/plugins.rb', line 357

def action_name?(name)
  return false if name.to_s.strip.empty?

  %w[update delete complete finish restore unfinish archive add_tag delete_tag remove_tag move].include?(name.to_s.downcase)
end

.create_plugin(name, language: nil) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/na/plugins.rb', line 194

def create_plugin(name, language: nil)
  base = File.basename(name)
  ext = File.extname(base)
  if ext.empty? && language
    ext = language.start_with?('.') ? language : ".#{language.split('/').last}"
  end
  ext = '.sh' if ext.empty?
  she = language&.start_with?('/') ? language : infer_shebang_for_extension(ext)
  file = File.join(plugins_home, base.sub(File.extname(base), '') + ext)
  content = []
  content << she
  content << "# name: #{base.sub(File.extname(base), '')}"
  content << '# input: json'
  content << '# output: json'
  content << '# New plugin template'
  content << ''
  content << '# Read STDIN and echo back unchanged'
  content << 'if command -v python3 >/dev/null 2>&1; then'
  content << "  python3 - \"$@\" <<'PY'"
  content << 'import sys, json'
  content << 'data = json.load(sys.stdin)'
  content << 'json.dump(data, sys.stdout)'
  content << 'PY'
  content << 'else'
  content << '  cat'
  content << 'fi'
  File.write(file, content.join("\n"))
  file
end

.create_sample_plugins(dir, force: false) ⇒ Object



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/na/plugins.rb', line 494

def create_sample_plugins(dir, force: false)
  py = File.join(dir, 'Add Foo.py')
  sh = File.join(dir, 'Add Bar.sh')

  if force || !File.exist?(py)
    FileUtils.rm_f(py)
    File.write(py, "      #!/usr/bin/env python3\n      # name: Add Foo\n      # input: json\n      # output: json\n      import sys, json, time\n      data = json.load(sys.stdin)\n      now = time.strftime('%Y-%m-%d %H:%M:%S')\n      for a in data:\n          tags = a.get('tags', [])\n          tags.append({'name':'foo','value':now})\n          a['tags'] = tags\n      json.dump(data, sys.stdout)\n    PY\n  end\n  unless File.exist?(sh)\n    File.write(sh, <<~SH)\n      #!/usr/bin/env bash\n      # name: Add Bar\n      # input: text\n      # output: text\n      while IFS= read -r line; do\n        if [[ -z \"$line\" ]]; then continue; fi\n        if [[ \"$line\" == *\"||\"* ]]; then\n          fileline=${line%%||*}\n          rest=${line#*||}\n          parents=${rest%%||*}; rest=${rest#*||}\n          text=${rest%%||*}; rest=${rest#*||}\n          note=${rest%%||*}; tags=${rest#*||}\n          if [[ -z \"$tags\" ]]; then tags=\"bar\"; else tags=\"$tags;bar\"; fi\n          echo \"$fileline||$parents||$text||$note||$tags\"\n        else\n          echo \"$line\"\n        fi\n      done\n    SH\n  end\n\n  return unless force || !File.exist?(sh)\n\n  FileUtils.rm_f(sh)\n  File.write(sh, <<~SH)\n    #!/usr/bin/env bash\n    # name: Add Bar\n    # input: text\n    # output: text\n    while IFS= read -r line; do\n      if [[ -z \"$line\" ]]; then continue; fi\n      if [[ \"$line\" == *\"||\"* ]]; then\n        fileline=${line%%||*}\n        rest=${line#*||}\n        parents=${rest%%||*}; rest=${rest#*||}\n        text=${rest%%||*}; rest=${rest#*||}\n        note=${rest%%||*}; tags=${rest#*||}\n        if [[ -z \"$tags\" ]]; then tags=\"bar\"; else tags=\"$tags;bar\"; fi\n        echo \"$fileline||$parents||$text||$note||$tags\"\n      else\n        echo \"$line\"\n      fi\n    done\n  SH\n  File.chmod(0o755, sh)\nend\n")

.default_readme_contentsObject



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
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
# File 'lib/na/plugins.rb', line 374

def default_readme_contents
  "    # NA Plugins\n\n    Put your scripts in this folder. Each plugin must start with a shebang (#!) so NA knows how to execute it.\n\n    - Plugins receive input on STDIN and must write output to STDOUT\n    - Do not modify the original files; NA applies changes based on your output\n    - Do not change `file_path` or `line` in your output\n    - You may change `parents` (to move), `text`, `note`, and `tags`\n\n    ## Metadata (optional)\n    Add a comment block (after the shebang) with key: value pairs to declare defaults. Keys are case-insensitive.\n\n    ```\n    # input: json\n    # output: json\n    # name: My Fancy Plugin\n    ```\n\n    CLI flags `--input/--output/--divider` override metadata when provided.\n\n    ## Formats\n    Valid input/output formats: `json`, `yaml`, `csv`, `text`.\n\n    Text format line:\n    ```\n    ACTION||ARGS||file_path:line||parents||text||note||tags\n    ```\n    - If the first token isn\u2019t a known ACTION, it\u2019s treated as `file_path:line` and ACTION defaults to `UPDATE`.\n    - `parents`: `Parent>Child>Leaf`\n    - `tags`: `name(value);name;other(value)`\n\n    JSON/YAML object schema per action:\n    ```json\n    {\n      \"action\": { \"action\": \"UPDATE\", \"arguments\": [\"arg1\"] },\n      \"file_path\": \"/path/to/todo.taskpaper\",\n      \"line\": 15,\n      \"parents\": [\"Project\", \"Subproject\"],\n      \"text\": \"- Do something @tag(value)\",\n      \"note\": \"Notes can\\nspan lines\",\n      \"tags\": [ { \"name\": \"tag\", \"value\": \"value\" } ]\n    }\n    ```\n\n    ACTION values (case-insensitive): `UPDATE` (default), `DELETE`, `COMPLETE`/`FINISH`, `RESTORE`/`UNFINISH`, `ARCHIVE`, `ADD_TAG`, `DELETE_TAG`/`REMOVE_TAG`, `MOVE`.\n    - For `ADD_TAG`, `DELETE_TAG`/`REMOVE_TAG`, and `MOVE`, provide arguments (e.g., tags or target project).\n\n    ## Examples\n\n    JSON input example (2 actions):\n    ```json\n    [\n      {\n        \"file_path\": \"/projects/todo.taskpaper\",\n        \"line\": 21,\n        \"parents\": [\"Inbox\"],\n        \"text\": \"- Example action\",\n        \"note\": \"\",\n        \"tags\": []\n      },\n      {\n        \"file_path\": \"/projects/todo.taskpaper\",\n        \"line\": 42,\n        \"parents\": [\"Work\", \"Feature\"],\n        \"text\": \"- Add feature @na\",\n        \"note\": \"Spec TKT-123\",\n        \"tags\": [{\"name\":\"na\",\"value\":\"\"}]\n      }\n    ]\n    ```\n\n    Text input example (2 actions):\n    ```\n    UPDATE||||/projects/todo.taskpaper:21||Inbox||- Example action||||\n    MOVE||Work:NewFeature||/projects/todo.taskpaper:42||Work>Feature||- Add feature @na||Spec TKT-123||na\n    ```\n\n    A plugin would read from STDIN, transform, and write the same shape to STDOUT. For example, a shell plugin that adds `@bar`:\n    ```bash\n    #!/usr/bin/env bash\n    # input: text\n    # output: text\n    while IFS= read -r line; do\n      [[ -z \"$line\" ]] && continue\n      IFS='||' read -r a1 a2 a3 a4 a5 a6 a7 <<<\"$line\"\n      # If first token is not an action, treat it as file:line\n      case \"${a1^^}\" in\n        UPDATE|DELETE|COMPLETE|FINISH|RESTORE|UNFINISH|ARCHIVE|ADD_TAG|DELETE_TAG|REMOVE_TAG|MOVE) : ;;\n        *) a7=\"$a6\"; a6=\"$a5\"; a5=\"$a4\"; a4=\"$a3\"; a3=\"$a2\"; a2=\"\"; a1=\"UPDATE\";;\n      esac\n      tags=\"$a7\"; tags=${tags:+\"$tags;bar\"}; tags=${tags:-bar}\n      echo \"$a1||$a2||$a3||$a4||$a5||$a6||$tags\"\n    done\n    ```\n\n    Python example (JSON):\n    ```python\n    #!/usr/bin/env python3\n    # input: json\n    # output: json\n    import sys, json, time\n    data = json.load(sys.stdin)\n    for a in data:\n        act = a.get('action') or {'action':'UPDATE','arguments':[]}\n        a['action'] = act\n        tags = a.get('tags', [])\n        tags.append({'name':'foo','value':time.strftime('%Y-%m-%d %H:%M:%S')})\n        a['tags'] = tags\n    json.dump(data, sys.stdout)\n    ```\n\n    Tips:\n    - Always preserve `file_path` and `line`\n    - Return only actions you want changed; others can be omitted\n    - For text IO, the field divider defaults to `||` and can be overridden with `--divider`\n  MD\nend\n"

.disable_plugin(name) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/na/plugins.rb', line 181

def disable_plugin(name)
  path = resolve_plugin(name)
  return path if path && File.dirname(path) == plugins_disabled_home

  enabled_map = Dir.exist?(plugins_home) ? Dir.children(plugins_home) : []
  from = enabled_map.map { |e| File.join(plugins_home, e) }
                    .find { |p| File.basename(p).downcase.start_with?(name.to_s.downcase) }
  from ||= File.join(plugins_home, name)
  to = File.join(plugins_disabled_home, File.basename(from))
  FileUtils.mv(from, to)
  to
end

.enable_plugin(name) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/na/plugins.rb', line 166

def enable_plugin(name)
  # Try by resolved path; if already enabled, return
  path = resolve_plugin(name)
  return path if path && File.dirname(path) == plugins_home

  # Find in disabled by normalized name
  disabled_map = Dir.exist?(plugins_disabled_home) ? Dir.children(plugins_disabled_home) : []
  from = disabled_map.map { |e| File.join(plugins_disabled_home, e) }
                     .find { |p| File.basename(p).downcase.start_with?(name.to_s.downcase) }
  from ||= File.join(plugins_disabled_home, name)
  to = File.join(plugins_home, File.basename(from))
  FileUtils.mv(from, to)
  to
end

.ensure_plugins_home(force_samples: false) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/na/plugins.rb', line 33

def ensure_plugins_home(force_samples: false)
  dir = plugins_home
  dis = plugins_disabled_home
  FileUtils.mkdir_p(dir) unless File.directory?(dir)
  FileUtils.mkdir_p(dis) unless File.directory?(dis)

  readme = File.join(dir, 'README.md')
  File.write(readme, default_readme_contents) unless File.exist?(readme)

  return if samples_generated? || force_samples

  create_sample_plugins(dis)
  mark_samples_generated
end

.generate_sample_pluginsObject



48
49
50
51
52
53
# File 'lib/na/plugins.rb', line 48

def generate_sample_plugins
  dis = plugins_disabled_home
  FileUtils.mkdir_p(dis) unless File.directory?(dis)
  create_sample_plugins(dis, force: true)
  mark_samples_generated
end

.infer_shebang_for_extension(ext) ⇒ Object



112
113
114
115
116
117
118
119
120
121
# File 'lib/na/plugins.rb', line 112

def infer_shebang_for_extension(ext)
  case ext.downcase
  when '.rb' then '#!/usr/bin/env ruby'
  when '.py' then '#!/usr/bin/env python3'
  when '.zsh' then '#!/usr/bin/env zsh'
  when '.fish' then '#!/usr/bin/env fish'
  when '.js', '.mjs' then '#!/usr/bin/env node'
  else '#!/usr/bin/env bash'
  end
end

.list_pluginsObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/na/plugins.rb', line 55

def list_plugins
  dir = plugins_home
  return {} unless File.directory?(dir)

  Dir.children(dir).each_with_object({}) do |entry, acc|
    path = File.join(dir, entry)
    next unless File.file?(path)
    next if entry =~ /\.(md|bak)$/i
    next unless shebang?(path)

    base = File.basename(entry, File.extname(entry))
    key = base.gsub(/[\s_]/, '')
    acc[key.downcase] = path
  end
end

.list_plugins_disabledObject



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/na/plugins.rb', line 71

def list_plugins_disabled
  dir = plugins_disabled_home
  return {} unless File.directory?(dir)

  Dir.children(dir).each_with_object({}) do |entry, acc|
    path = File.join(dir, entry)
    next unless File.file?(path)
    next if entry =~ /\.(md|bak)$/i
    next unless shebang?(path)

    base = File.basename(entry, File.extname(entry))
    key = base.gsub(/[\s_]/, '')
    acc[key.downcase] = path
  end
end

.mark_samples_generatedObject



28
29
30
31
# File 'lib/na/plugins.rb', line 28

def mark_samples_generated
  FileUtils.mkdir_p(File.dirname(samples_generated_flag))
  File.write(samples_generated_flag, Time.now.iso8601) unless File.exist?(samples_generated_flag)
end

.normalize_action_block(action_name, args) ⇒ Object



363
364
365
366
367
368
369
370
371
372
# File 'lib/na/plugins.rb', line 363

def normalize_action_block(action_name, args)
  name = (action_name || 'UPDATE').to_s.upcase
  name = 'DELETE_TAG' if name == 'REMOVE_TAG'
  name = 'COMPLETE' if name == 'FINISH'
  name = 'RESTORE' if name == 'UNFINISH'
  {
    'action' => name,
    'arguments' => args.is_a?(Array) ? args : args.to_s.split(/[,;]/).map(&:strip).reject(&:empty?)
  }
end

.parse_actions(str, format: 'json', divider: '||') ⇒ Object



253
254
255
256
257
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
# File 'lib/na/plugins.rb', line 253

def parse_actions(str, format: 'json', divider: '||')
  case format.to_s.downcase
  when 'json'
    JSON.parse(str)
  when 'yaml', 'yml'
    YAML.safe_load(str, permitted_classes: [Time], aliases: true)
  when 'csv'
    rows = CSV.parse(str.to_s, headers: true)
    rows = CSV.parse(str.to_s) if rows.nil? || rows.empty?
    rows.map do |row|
      r = if row.is_a?(CSV::Row)
            row.to_h
          else
            {
              'action' => row[0], 'arguments' => row[1], 'file_path' => row[2], 'line' => row[3],
              'parents' => row[4], 'text' => row[5], 'note' => row[6], 'tags' => row[7]
            }
          end
      {
        'file_path' => r['file_path'].to_s,
        'line' => r['line'].to_i,
        'parents' => (r['parents'].to_s.empty? ? [] : r['parents'].split('>').map(&:strip)),
        'text' => r['text'].to_s,
        'note' => r['note'].to_s,
        'tags' => parse_tags(r['tags']),
        'action' => normalize_action_block(r['action'], r['arguments'])
      }
    end
  when 'text', 'txt'
    str.to_s.split(/\r?\n/).reject(&:empty?).map { |line| parse_text(line, divider: divider) }
  end
end

.parse_plugin_metadata(file) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/na/plugins.rb', line 123

def (file)
  meta = { 'input' => nil, 'output' => nil, 'name' => nil }
  lines = File.readlines(file, chomp: true)
  return meta if lines.empty?

  # skip shebang
  i = 0
  i += 1 if lines[0].to_s.start_with?('#!')
  # skip leading blanks
  i += 1 while i < lines.length && lines[i].strip.empty?
  while i < lines.length
    line = lines[i]
    break if line.strip.empty?

    # strip common comment leaders
    stripped = line.sub(%r{^\s*(#|//)}, '').strip
    if (m = stripped.match(/^([A-Za-z]+)\s*:\s*(.+)$/))
      key = m[1].downcase
      val = m[2].strip
      case key
      when 'input', 'output'
        meta[key] = val.downcase
      when 'name', 'title'
        meta['name'] = val
      end
    end
    break if meta.values_at('input', 'output', 'name').compact.size == 3

    i += 1
  end
  meta
end

.parse_tags(str) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
# File 'lib/na/plugins.rb', line 336

def parse_tags(str)
  return [] if str.to_s.strip.empty?

  str.split(';').map do |part|
    if (m = part.match(/^([^()]+)\((.*)\)$/))
      { 'name' => m[1].strip, 'value' => m[2].to_s }
    else
      { 'name' => part.strip, 'value' => '' }
    end
  end
end

.parse_text(line, divider: '||') ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/na/plugins.rb', line 300

def parse_text(line, divider: '||')
  tokens = line.split(divider, 7)
  action_token = tokens[0].to_s.strip
  if action_name?(action_token)
    act = action_token
    args = tokens[1]
    fileline = tokens[2]
    parents = tokens[3]
    text = tokens[4]
    note = tokens[5]
    tags = tokens[6]
  else
    act = 'UPDATE'
    args = ''
    fileline = tokens[0]
    parents = tokens[1]
    text = tokens[2]
    note = tokens[3]
    tags = tokens[4]
  end
  fp, ln = (fileline || '').split(':', 2)
  {
    'file_path' => fp.to_s,
    'line' => ln.to_i,
    'parents' => (parents.to_s.empty? ? [] : parents.split('>').map(&:strip)),
    'text' => text.to_s,
    'note' => note.to_s.gsub('\\n', "\n"),
    'tags' => parse_tags(tags),
    'action' => normalize_action_block(act, args)
  }
end

.plugins_disabled_homeObject



16
17
18
# File 'lib/na/plugins.rb', line 16

def plugins_disabled_home
  File.expand_path('~/.local/share/na/plugins_disabled')
end

.plugins_homeObject



12
13
14
# File 'lib/na/plugins.rb', line 12

def plugins_home
  File.expand_path('~/.local/share/na/plugins')
end

.resolve_plugin(name) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/na/plugins.rb', line 87

def resolve_plugin(name)
  return nil unless name && !name.to_s.strip.empty?

  normalized = name.to_s.strip.gsub(/[\s_]/, '').downcase
  candidates = list_plugins
  return candidates[normalized] if candidates.key?(normalized)

  # Fallback: try exact filename match in dir
  path = File.join(plugins_home, name)
  return path if File.file?(path)

  # Also check disabled folder
  path = File.join(plugins_disabled_home, name)
  File.file?(path) ? path : nil
end

.run_plugin(file, stdin_str) ⇒ Object



156
157
158
159
160
161
162
163
164
# File 'lib/na/plugins.rb', line 156

def run_plugin(file, stdin_str)
  interp = shebang_for(file)
  cmd = interp ? %(#{interp} #{Shellwords.escape(file)}) : %(sh #{Shellwords.escape(file)})
  IO.popen(cmd, 'r+', err: i[child out]) do |io|
    io.write(stdin_str.to_s)
    io.close_write
    io.read
  end
end

.samples_generated?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/na/plugins.rb', line 24

def samples_generated?
  File.exist?(samples_generated_flag)
end

.samples_generated_flagObject



20
21
22
# File 'lib/na/plugins.rb', line 20

def samples_generated_flag
  File.expand_path('~/.local/share/na/.samples_generated')
end

.serialize_actions(actions, format: 'json', divider: '||') ⇒ Object



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
# File 'lib/na/plugins.rb', line 224

def serialize_actions(actions, format: 'json', divider: '||')
  case format.to_s.downcase
  when 'json'
    JSON.pretty_generate(actions)
  when 'yaml', 'yml'
    YAML.dump(actions)
  when 'csv'
    CSV.generate(force_quotes: true) do |csv|
      csv << %w[action arguments file_path line parents text note tags]
      actions.each do |a|
        csv << [
          (a['action'] && a['action']['action']) || 'UPDATE',
          Array(a['action'] && a['action']['arguments']).join(','),
          a['file_path'],
          a['line'],
          Array(a['parents']).join('>'),
          a['text'] || '',
          a['note'] || '',
          serialize_tags(a['tags'])
        ]
      end
    end
  when 'text', 'txt'
    actions.map { |a| serialize_text(a, divider: divider) }.join("\n")
  else
    JSON.generate(actions)
  end
end

.serialize_tags(tags) ⇒ Object



332
333
334
# File 'lib/na/plugins.rb', line 332

def serialize_tags(tags)
  Array(tags).map { |t| t['value'].to_s.empty? ? t['name'].to_s : %(#{t['name']}(#{t['value']})) }.join(';')
end

.serialize_text(action, divider: '||') ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/na/plugins.rb', line 286

def serialize_text(action, divider: '||')
  parts = []
  act = action['action'] && action['action']['action']
  args = Array(action['action'] && action['action']['arguments']).join(',')
  parts << (act || 'UPDATE')
  parts << args
  parts << "#{action['file_path']}:#{action['line']}"
  parts << Array(action['parents']).join('>')
  parts << (action['text'] || '')
  parts << (action['note'] || '').gsub("\n", '\\n')
  parts << serialize_tags(action['tags'])
  parts.join(divider)
end

.shebang?(file) ⇒ Boolean

Returns:

  • (Boolean)


348
349
350
351
352
353
354
355
# File 'lib/na/plugins.rb', line 348

def shebang?(file)
  first = begin
    File.open(file, 'r', &:readline)
  rescue StandardError
    ''
  end
  first.start_with?('#!')
end

.shebang_for(file) ⇒ Object



103
104
105
106
107
108
109
110
# File 'lib/na/plugins.rb', line 103

def shebang_for(file)
  first = begin
    File.open(file, 'r', &:readline)
  rescue StandardError
    ''
  end
  first.start_with?('#!') ? first.sub('#!', '').strip : nil
end