Module: Legion::Extensions::Exec::Helpers::Worktree

Defined in:
lib/legion/extensions/exec/helpers/worktree.rb

Class Method Summary collapse

Class Method Details

.create(task_id:, branch: nil, base_ref: 'HEAD', repo_path: nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/legion/extensions/exec/helpers/worktree.rb', line 12

def create(task_id:, branch: nil, base_ref: 'HEAD', repo_path: nil)
  branch ||= "legion/#{task_id}"
  path = worktree_path(task_id)
  return { success: false, reason: :already_exists } if Dir.exist?(path)

  FileUtils.mkdir_p(File.dirname(path))
  args = ['git', 'worktree', 'add', path, '-b', branch, base_ref]
  opts = repo_path ? { chdir: repo_path } : {}
  _stdout, stderr, status = Open3.capture3(*args, **opts)
  if status.success?
    { success: true, path: path, branch: branch }
  else
    { success: false, reason: :git_error, message: stderr.strip }
  end
rescue Errno::ENOENT, Errno::ENOTDIR, Errno::EACCES => e
  { success: false, reason: :invalid_repo_path, message: e.message }
end

.list(repo_path: nil) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/legion/extensions/exec/helpers/worktree.rb', line 46

def list(repo_path: nil)
  args = ['git', 'worktree', 'list', '--porcelain']
  opts = repo_path ? { chdir: repo_path } : {}
  stdout, stderr, status = Open3.capture3(*args, **opts)
  if status.success?
    worktrees = parse_worktree_list(stdout)
    { success: true, worktrees: worktrees }
  else
    { success: false, reason: :git_error, message: stderr.strip }
  end
rescue Errno::ENOENT, Errno::ENOTDIR, Errno::EACCES => e
  { success: false, reason: :invalid_repo_path, message: e.message }
end

.remove(task_id:, repo_path: nil) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/legion/extensions/exec/helpers/worktree.rb', line 30

def remove(task_id:, repo_path: nil)
  path = worktree_path(task_id)
  return { success: false, reason: :not_found } unless Dir.exist?(path)

  args = ['git', 'worktree', 'remove', path, '--force']
  opts = repo_path ? { chdir: repo_path } : {}
  _stdout, stderr, status = Open3.capture3(*args, **opts)
  if status.success?
    { success: true }
  else
    { success: false, reason: :git_error, message: stderr.strip }
  end
rescue Errno::ENOENT, Errno::ENOTDIR, Errno::EACCES => e
  { success: false, reason: :invalid_repo_path, message: e.message }
end

.worktree_path(task_id) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/legion/extensions/exec/helpers/worktree.rb', line 60

def worktree_path(task_id)
  base = if defined?(Legion::Settings)
           Legion::Settings.dig(:fleet, :workspace, :worktree_base) ||
             Legion::Settings.dig(:worktree, :base_dir)
         end
  File.join(base || File.join(Dir.pwd, '.legion-worktrees'), task_id.to_s)
end