Class: Hiiro::TaskManager

Inherits:
Object
  • Object
show all
Defined in:
lib/hiiro/tasks.rb

Defined Under Namespace

Classes: Config

Constant Summary collapse

TASKS_DIR =
File.join(Dir.home, '.config', 'hiiro', 'tasks')
APPS_FILE =
File.join(Dir.home, '.config', 'hiiro', 'apps.yml')

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hiiro, scope: :task, environment: nil) ⇒ TaskManager

Returns a new instance of TaskManager.



21
22
23
24
25
# File 'lib/hiiro/tasks.rb', line 21

def initialize(hiiro, scope: :task, environment: nil)
  @hiiro = hiiro
  @scope = scope
  @environment = environment || Environment.current
end

Instance Attribute Details

#environmentObject (readonly)

Returns the value of attribute environment.



19
20
21
# File 'lib/hiiro/tasks.rb', line 19

def environment
  @environment
end

#hiiroObject (readonly)

Returns the value of attribute hiiro.



19
20
21
# File 'lib/hiiro/tasks.rb', line 19

def hiiro
  @hiiro
end

#scopeObject (readonly)

Returns the value of attribute scope.



19
20
21
# File 'lib/hiiro/tasks.rb', line 19

def scope
  @scope
end

Class Method Details

.add_resolvers(hiiro, scope: :task) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/hiiro/tasks.rb', line 9

def self.add_resolvers(hiiro, scope: :task)
  tm = new(hiiro, scope: scope)
  hiiro.add_resolver(:task,
    -> { tm.select_task_interactive }
  ) { |name|
    task = tm.task_by_name(name)
    task&.name || name
  }
end

Instance Method Details

#app_path(app_name = nil) ⇒ Object



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
# File 'lib/hiiro/tasks.rb', line 473

def app_path(app_name = nil)
  task = current_task
  tree_root = if task
    tree = environment.find_tree(task.tree_name)
    tree&.path || File.join(Hiiro::WORK_DIR, task.tree_name)
  else
    Hiiro::Git.new(nil, Dir.pwd).root
  end

  if app_name.nil?
    print tree_root
    return
  end

  result = environment.app_matcher.find_all(app_name)

  case result.count
  when 0
    puts "ERROR: No matches found"
    puts
    puts "Possible Apps:"
    environment.all_apps.each { |a| puts format("  %-20s => %s", a.name, a.relative_path) }
  when 1
    print result.first.item.resolve(tree_root)
  else
    puts "Multiple matches found:"
    result.matches.each { |m| puts format("  %-20s => %s", m.item.name, m.item.relative_path) }
  end
end

#apply_sparse_checkout(path, group_names) ⇒ Object



638
639
640
641
642
643
644
645
646
# File 'lib/hiiro/tasks.rb', line 638

def apply_sparse_checkout(path, group_names)
  dirs = SparseGroups.dirs_for_groups(group_names)
  if dirs.empty?
    puts "WARNING: No directories found for sparse groups: #{group_names.join(', ')}"
    return
  end
  puts "Applying sparse checkout (groups: #{group_names.join(', ')})..."
  Hiiro::Git.new(nil, path).sparse_checkout(path, dirs)
end

#branch(task_name = nil) ⇒ Object



419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/hiiro/tasks.rb', line 419

def branch(task_name = nil)
  if task_name.nil?
    branch = select_branch_interactive
    return unless branch
    print branch
    return
  end

  task = task_by_name(task_name)
  unless task
    puts "Task not found: #{task_name}"
    return
  end

  if task.branch
    print task.branch
  elsif task.tree&.detached?
    puts "(detached HEAD)"
  else
    puts "(no branch)"
  end
end

#capture_tmux_windows(session) ⇒ Object



648
649
650
651
652
653
654
# File 'lib/hiiro/tasks.rb', line 648

def capture_tmux_windows(session)
  output = `tmux list-windows -t #{session} -F '\#{window_index}:\#{window_name}:\#{pane_current_path}' 2>/dev/null`
  output.lines.map(&:strip).map { |line|
    idx, name, path = line.split(':')
    { 'index' => idx, 'name' => name, 'path' => path }
  }
end

#cd_to_app(app_name = nil) ⇒ Object



453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/hiiro/tasks.rb', line 453

def cd_to_app(app_name = nil)
  task = current_task
  unless task
    puts "ERROR: Not currently in a task session"
    return
  end

  if app_name.nil? || app_name.empty?
    tree = environment.find_tree(task.tree_name)
    send_cd(tree&.path || File.join(Hiiro::WORK_DIR, task.tree_name))
    return
  end

  result = resolve_app(app_name, task)
  return unless result

  _resolved_name, app_path = result
  send_cd(app_path)
end

#cd_to_task(task) ⇒ Object



442
443
444
445
446
447
448
449
450
451
# File 'lib/hiiro/tasks.rb', line 442

def cd_to_task(task)
  unless task
    puts "Task not found"
    return
  end

  tree = environment.find_tree(task.tree_name)
  path = tree ? tree.path : File.join(Hiiro::WORK_DIR, task.tree_name)
  send_cd(path)
end

#configObject



27
28
29
# File 'lib/hiiro/tasks.rb', line 27

def config
  environment.config
end

#current_sessionObject



109
110
111
# File 'lib/hiiro/tasks.rb', line 109

def current_session
  environment.session
end

#current_taskObject



105
106
107
# File 'lib/hiiro/tasks.rb', line 105

def current_task
  environment.task
end

#current_treeObject



113
114
115
# File 'lib/hiiro/tasks.rb', line 113

def current_tree
  environment.tree
end

#filter_tasks(prefixes = []) ⇒ Object

Return tasks (sorted by name) optionally narrowed by prefix matches. Each prefix matches if a task’s name (or short_name in subtask scope) starts with it. Multiple prefixes are OR’d together.



263
264
265
266
267
268
# File 'lib/hiiro/tasks.rb', line 263

def filter_tasks(prefixes = [])
  key = (scope == :subtask) ? :short_name : :name
  list = (scope == :subtask ? tasks : environment.all_tasks)
  list = list.select { |t| prefixes.any? { |p| t.public_send(key).start_with?(p) } } if prefixes.any?
  list.sort_by(&key)
end

#list(tags_filter: []) ⇒ Object



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
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/hiiro/tasks.rb', line 270

def list(tags_filter: [])
  tag_store = Hiiro::Tags.new(:task)
  items = tasks

  if tags_filter.any?
    items = items.select { |t| (tag_store.get(t.name) & tags_filter).any? }
  end

  if items.empty?
    if tags_filter.any?
      puts "No #{scope == :subtask ? 'subtasks' : 'tasks'} match tags: #{tags_filter.join(', ')}"
    else
      puts scope == :subtask ? "No subtasks found" : "No tasks found"
      puts "Use 'h #{scope} start NAME' to create one."
    end
    return
  end

  current = current_task
  label = scope == :subtask ? "Subtasks" : "Tasks"
  if scope == :subtask && current
    parent = current_parent_task
    label = "Subtasks of '#{parent&.name}'" if parent
  end

  puts "#{label}:"
  puts

  client_map = Hiiro::Tmux::Session.client_map

  # Collect rows as {prefix, name, tree, branch, session} so we can
  # compute max column widths before rendering.
  rows = []
  items.each do |task|
    marker = (current && current.name == task.name) ? "*" : " "
    attach = client_map.key?(task.session_name) ? "@" : " "
    rows << { prefix: "#{marker}#{attach} ", **task.display_data(scope: scope, environment: environment) }

    if scope == :task
      subtasks(task).each do |st|
        sub_marker = (current && current.name == st.name) ? "*" : " "
        sub_attach = client_map.key?(st.session_name) ? "@" : " "
        rows << { prefix: "#{sub_marker}#{sub_attach} - ", **st.display_data(scope: :subtask, environment: environment) }
      end
    end
  end

  # Column widths: the name column absorbs the variable-length prefix so
  # that tree/branch/session always start at the same position.
  name_col   = rows.map { |r| r[:prefix].length + r[:name].length }.max
  tree_col   = rows.map { |r| r[:tree].length }.max
  branch_col = rows.map { |r| r[:branch].length }.max

  cols = ENV['COLUMNS']&.to_i&.then { |c| c > 0 ? c : nil }

  rows.each do |r|
    name_pad = name_col - r[:prefix].length
    tags     = tag_store.get(r[:name])
    tag_str  = tags.any? ? "  " + Hiiro::Tags.badges(tags) : ""
    line = r[:prefix] + format("%-#{name_pad}s  %-#{tree_col}s  %-#{branch_col}s  %s",
                               r[:name], r[:tree], r[:branch], r[:session]) + tag_str
    puts cols ? line[0, cols] : line
  end

  available = environment.all_trees.reject { |t|
    environment.all_tasks.any? { |task| task.tree_name == t.name }
  }

  if available.any?
    puts
    avail_name_col = [available.map { |t| t.name.length }.max, name_col].max
    available.each do |tree|
      branch_str = tree.branch ? "[#{tree.branch}]" : tree.detached? ? "[(detached)]" : ""
      line = format("  %-#{avail_name_col}s  (available)  %s", tree.name, branch_str).rstrip
      puts cols ? line[0, cols] : line
    end
  end

  if scope == :task
    task_session_names = environment.all_tasks.map(&:session_name)
    extra_sessions = environment.all_sessions.reject { |s| task_session_names.include?(s.name) }
    if extra_sessions.any?
      puts
      extra_name_col = [extra_sessions.map { |s| s.name.length }.max, name_col].max
      extra_sessions.sort_by(&:name).each do |session|
        attach = client_map.key?(session.name) ? "@" : " "
        line = format(" %s %-#{extra_name_col}s  (tmux session)", attach, session.name)
        puts cols ? line[0, cols] : line
      end
    end
  end
end

#list_appsObject



404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/hiiro/tasks.rb', line 404

def list_apps
  apps = environment.all_apps
  if apps.any?
    puts "Configured apps:"
    puts
    apps.each do |app|
      puts format("  %-20s => %s", app.name, app.relative_path)
    end
  else
    puts "No apps configured."
    puts "Create #{APPS_FILE} with format:"
    puts "  app_name: relative/path/from/repo"
  end
end

#open_app(app_name) ⇒ Object



389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/hiiro/tasks.rb', line 389

def open_app(app_name)
  task = current_task
  unless task
    puts "ERROR: Not currently in a task session"
    return
  end

  result = resolve_app(app_name, task)
  return unless result

  resolved_name, app_path = result
  system('tmux', 'new-window', '-n', resolved_name, '-c', app_path)
  puts "Opened '#{resolved_name}' in new window (#{app_path})"
end

#resolve_name(name) ⇒ Object

Resolve a name to a Task or FallbackTarget (~/proj/* directory). Falls back to ~/proj/* prefix match when no task matches.



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/hiiro/tasks.rb', line 68

def resolve_name(name)
  return nil if name.nil?

  task = task_by_name(name)
  return task if task

  proj_dirs = Dir.glob(File.expand_path('~/proj/*/'))
  dir_names = proj_dirs.map { |d| File.basename(d) }
  result = Hiiro::Matcher.by_prefix(dir_names, name)
  if result.one?
    dir_name = result.first.item
    return FallbackTarget.from_project(dir_name, File.expand_path("~/proj/#{dir_name}"))
  elsif result.ambiguous?
    STDERR.puts "Ambiguous project match for '#{name}': #{result.matches.map(&:item).join(', ')}"
  end

  nil
end

#resolve_path(target) ⇒ Object

Resolve the filesystem path for a Task or FallbackTarget.



88
89
90
91
92
93
94
95
# File 'lib/hiiro/tasks.rb', line 88

def resolve_path(target)
  return nil unless target

  return target.path if target.is_a?(FallbackTarget)

  tree = environment.find_tree(target.tree_name)
  tree ? tree.path : File.join(Hiiro::WORK_DIR, target.tree_name)
end

#resume_task(tree, task_name: nil) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/hiiro/tasks.rb', line 238

def resume_task(tree, task_name: nil)
  unless tree
    puts "No available worktree selected"
    return
  end

  # Derive a default task name from the tree name: "foo/main" -> "foo"
  task_name ||= tree.name.end_with?('/main') ? tree.name.chomp('/main') : tree.name

  if task_by_name(task_name)
    puts "Task '#{task_name}' already exists"
    return
  end

  color_index = Hiiro::TaskColors.next_index(config.tasks.map(&:color_index).compact)
  task = Task.new(name: task_name, tree: tree.name, session: task_name, color_index: color_index)
  config.save_task(task)
  puts "Resumed task '#{task_name}' from worktree '#{tree.name}'"

  switch_to_task(task)
end

#saveObject



378
379
380
381
382
383
384
385
386
387
# File 'lib/hiiro/tasks.rb', line 378

def save
  task = current_task
  unless task
    puts "ERROR: Not currently in a task session"
    return
  end

  windows = capture_tmux_windows(task.session_name)
  puts "Saved task '#{task.name}' state (#{windows.count} windows)"
end

#select_branch_interactive(prompt = nil) ⇒ Object



560
561
562
563
564
565
566
567
568
569
# File 'lib/hiiro/tasks.rb', line 560

def select_branch_interactive(prompt = nil)
  name_map = if scope == :subtask
    tasks.sort_by(&:short_name).each_with_object({}) { |t, h| h[format('%-25s  | %s', t.short_name, t.branch)] = t.branch }
  else
    environment.all_tasks.sort_by(&:name).each_with_object({}) { |t, h| h[format('%-25s  | %s', t.name, t.branch)] = t.branch }
  end
  return nil if name_map.empty?

  hiiro.fuzzyfind_from_map(name_map)
end

#select_task_interactive(prompt = nil) ⇒ Object

— Interactive selection with sk —



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
# File 'lib/hiiro/tasks.rb', line 505

def select_task_interactive(prompt = nil)
  task_list = if scope == :subtask
    tasks.sort_by(&:short_name)
  else
    environment.all_tasks.sort_by(&:name)
  end

  mapping = {}

  all_data = task_list.map { |t| [t, t.display_data(scope: scope, environment: environment)] }
  name_col   = all_data.map { |_, d| d[:name].length }.max || 0
  tree_col   = all_data.map { |_, d| d[:tree].length }.max || 0
  branch_col = all_data.map { |_, d| d[:branch].length }.max || 0

  all_data.each do |task, d|
    line = format("%-#{name_col}s  %-#{tree_col}s  %-#{branch_col}s  %s",
                  d[:name], d[:tree], d[:branch], d[:session])
    mapping[line] = task
  end

  # Add non-task tmux sessions (exclude sessions that belong to tasks)
  if scope == :task
    task_session_names = environment.all_tasks.map(&:session_name)
    extra_sessions = environment.all_sessions.reject { |s| task_session_names.include?(s.name) }
    extra_sessions.sort_by(&:name).each do |session|
      line = format("%-25s  (tmux session)", session.name)
      mapping[line] = session
    end
  end

  return nil if mapping.empty?

  selected = hiiro.fuzzyfind_from_map(mapping)
  selected
end

#send_cd(path) ⇒ Object



571
572
573
574
575
576
577
578
# File 'lib/hiiro/tasks.rb', line 571

def send_cd(path)
  pane = ENV['TMUX_PANE']
  if pane
    system('tmux', 'send-keys', '-t', pane, "cd #{path}\n")
  else
    system('tmux', 'send-keys', "cd #{path}\n")
  end
end

#start_task(name, app_name: nil, sparse_groups: []) ⇒ Object

— Actions —



119
120
121
122
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
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
# File 'lib/hiiro/tasks.rb', line 119

def start_task(name, app_name: nil, sparse_groups: [])
  existing = task_by_name(name)
  if existing
    puts "Task '#{existing.name}' already exists. Switching..."
    tree_path = existing.tree&.path
    if tree_path
      if sparse_groups.any?
        apply_sparse_checkout(tree_path, sparse_groups)
      else
        Hiiro::Git.new(nil, tree_path).disable_sparse_checkout(tree_path)
      end
    end
    switch_to_task(existing, app_name: app_name)
    return
  end

  task_name = scope == :subtask ? "#{current_parent_task.name}/#{name}" : name
  subtree_name = scope == :subtask ? "#{current_parent_task.name}/#{name}" : "#{name}/main"

  target_path = File.join(Hiiro::WORK_DIR, subtree_name)

  git = Hiiro::Git.new(nil, Hiiro::REPO_PATH)
  available = find_available_tree
  if available
    puts "Renaming worktree '#{available.name}' to '#{subtree_name}'..."
    FileUtils.mkdir_p(File.dirname(target_path))
    unless git.move_worktree(available.path, target_path, repo_path: Hiiro::REPO_PATH)
      puts "ERROR: Failed to rename worktree"
      return
    end
  else
    puts "Creating new worktree '#{subtree_name}'..."
    FileUtils.mkdir_p(File.dirname(target_path))
    unless git.add_worktree_detached(target_path, repo_path: Hiiro::REPO_PATH)
      puts "ERROR: Failed to create worktree"
      return
    end
  end

  apply_sparse_checkout(target_path, sparse_groups) if sparse_groups.any?

  session_name = task_name
  color_index = Hiiro::TaskColors.next_index(config.tasks.map(&:color_index).compact)
  task = Task.new(name: task_name, tree: subtree_name, session: session_name, color_index: color_index)
  config.save_task(task)

  base_dir = target_path
  if app_name
    app = environment.find_app(app_name)
    base_dir = app.resolve(target_path) if app
  end

  Dir.chdir(base_dir)
  # Create the session detached first so colors are applied before the user attaches
  unless system('tmux', 'has-session', '-t', "=#{session_name}", err: File::NULL)
    system('tmux', 'new-session', '-d', '-s', session_name, '-c', Dir.pwd)
  end
  Hiiro::TaskColors.apply(session_name, color_index)
  hiiro.start_tmux_session(session_name)

  puts "Started task '#{task_name}' in worktree '#{subtree_name}'"
end

#statusObject



363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/hiiro/tasks.rb', line 363

def status
  task = current_task
  unless task
    puts "Not currently in a task session"
    return
  end

  puts "Task: #{task.name}"
  puts "Worktree: #{task.tree_name}"
  tree = environment.find_tree(task.tree_name)
  puts "Path: #{tree&.path || '(unknown)'}"
  puts "Session: #{task.session_name}"
  puts "Parent: #{task.parent_name}" if task.subtask?
end

#stop_task(task) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
# File 'lib/hiiro/tasks.rb', line 226

def stop_task(task)
  unless task
    puts "Task not found"
    return
  end

  config.remove_task(task.name)
  subtasks(task).each { |st| config.remove_task(st.name) }

  puts "Stopped task '#{task.name}' (worktree available for reuse)"
end

#subtasks(task) ⇒ Object



45
46
47
# File 'lib/hiiro/tasks.rb', line 45

def subtasks(task)
  environment.all_tasks.select { |t| t.parent_name == task.name }
end

#switch_to_task(task, app_name: nil, force: false) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
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
223
224
# File 'lib/hiiro/tasks.rb', line 182

def switch_to_task(task, app_name: nil, force: false)
  unless task
    puts "Task not found"
    return
  end

  tree = environment.find_tree(task.tree_name)
  tree_path = tree ? tree.path : File.join(Hiiro::WORK_DIR, task.tree_name)

  session_name = task.session_name
  session_exists = system('tmux', 'has-session', '-t', "=#{session_name}", err: File::NULL)

  if session_exists
    session = environment.find_session(session_name)
    if session&.attached? && !force
      puts "Session '#{session_name}' is already attached. Use -f to switch anyway."
      exit 1
    end
    Hiiro::TaskColors.apply(session_name, task.color_index) if task.color_index
    hiiro.start_tmux_session(session_name)
  else
    base_dir = tree_path
    if app_name
      app = environment.find_app(app_name)
      base_dir = app.resolve(tree_path) if app
    end

    if Dir.exist?(base_dir)
      Dir.chdir(base_dir)
      # Create detached first so colors are applied before the user attaches
      unless system('tmux', 'has-session', '-t', "=#{session_name}", err: File::NULL)
        system('tmux', 'new-session', '-d', '-s', session_name, '-c', Dir.pwd)
      end
      Hiiro::TaskColors.apply(session_name, task.color_index) if task.color_index
      hiiro.start_tmux_session(session_name)
    else
      puts "ERROR: Path '#{base_dir}' does not exist"
      return
    end
  end

  puts "Switched to '#{task.name}'"
end

#task_by_name(name) ⇒ Object



59
60
61
62
63
64
# File 'lib/hiiro/tasks.rb', line 59

def task_by_name(name)
  return slash_lookup(name) if name.include?('/')

  key = (scope == :subtask) ? :short_name : :name
  Hiiro::Matcher.new(tasks, key).by_prefix(name).first&.item
end

#task_by_service_info(info) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/hiiro/tasks.rb', line 49

def task_by_service_info(info)
  if name = info['task']
    task_by_name(name)
  elsif session = info['tmux_session']
    task_by_session(session)
  elsif tree = info['tree']
    task_by_tree(tree)
  end
end

#task_by_session(session_name) ⇒ Object



101
102
103
# File 'lib/hiiro/tasks.rb', line 101

def task_by_session(session_name)
  environment.task_matcher.resolve(session_name, :session_name).resolved&.item
end

#task_by_tree(tree_name) ⇒ Object



97
98
99
# File 'lib/hiiro/tasks.rb', line 97

def task_by_tree(tree_name)
  environment.task_matcher.resolve(tree_name, :tree_name).resolved&.item
end

#tasksObject

— Scope-aware queries —



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/hiiro/tasks.rb', line 33

def tasks
  if scope == :subtask
    parent = current_parent_task
    return [] unless parent
    main_task = Task.new(name: "#{parent.name}/main", tree: parent.tree_name, session: parent.session_name)
    subtask_list = environment.all_tasks.select { |t| t.parent_name == parent.name }
    [main_task, *subtask_list]
  else
    environment.all_tasks.select(&:top_level?)
  end
end

#value_for_task(task_name = nil, &block) ⇒ Object



541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/hiiro/tasks.rb', line 541

def value_for_task(task_name = nil, &block)
  if task_name
    target = resolve_name(task_name)
    return block.call(target) if target
  end

  task_list = scope == :subtask ? tasks.sort_by(&:short_name) : environment.all_tasks.sort_by(&:name)

  mapping = task_list.each_with_object({}) do |task, h|
    name = scope == :subtask ? task.short_name : task.name
    val = block.call(task)&.to_s

    line = format("%-25s  | %s", name, val)
    h[line] = val
  end

  hiiro.fuzzyfind_from_map(mapping)
end