Module: Legion::Extensions::Exec::Helpers::Checkpoint

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

Class Method Summary collapse

Class Method Details

.list_checkpoints(task_id:) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/legion/extensions/exec/helpers/checkpoint.rb', line 42

def list_checkpoints(task_id:)
  pattern = "refs/checkpoints/#{task_id}/"
  stdout, = Open3.capture3('git', 'for-each-ref', '--format=%(refname) %(creatordate:iso8601)', pattern)
  checkpoints = stdout.strip.split("\n").filter_map do |line|
    next if line.strip.empty?

    parts = line.split(' ', 2)
    label = parts[0].sub(pattern, '')
    { label: label, created_at: parts[1] }
  end
  { success: true, checkpoints: checkpoints }
end

.prune(task_id:) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/legion/extensions/exec/helpers/checkpoint.rb', line 55

def prune(task_id:)
  pattern = "refs/checkpoints/#{task_id}/"
  stdout, = Open3.capture3('git', 'for-each-ref', '--format=%(refname)', pattern)
  refs = stdout.strip.split("\n").reject(&:empty?)
  refs.each { |ref| Open3.capture3('git', 'update-ref', '-d', ref) }
  { success: true, pruned: refs.size }
end

.restore(worktree_path:, label:, task_id:) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/legion/extensions/exec/helpers/checkpoint.rb', line 34

def restore(worktree_path:, label:, task_id:)
  ref = "refs/checkpoints/#{task_id}/#{label}"
  Dir.chdir(worktree_path) do
    _stdout, stderr, status = Open3.capture3('git', 'checkout', ref, '--', '.')
    status.success? ? { success: true, ref: ref } : { success: false, message: stderr.strip }
  end
end

.save(worktree_path:, label:, task_id:) ⇒ Object



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

def save(worktree_path:, label:, task_id:)
  Dir.chdir(worktree_path) do
    Open3.capture3('git', 'add', '-A')

    tree_sha, _err, tree_status = Open3.capture3('git', 'write-tree')
    return { success: false, reason: :write_tree_failed } unless tree_status.success?

    tree_sha = tree_sha.strip
    commit_sha, _err, commit_status = Open3.capture3(
      'git', 'commit-tree', tree_sha, '-m', "checkpoint: #{label}"
    )
    return { success: false, reason: :commit_tree_failed } unless commit_status.success?

    commit_sha = commit_sha.strip
    ref = "refs/checkpoints/#{task_id}/#{label}"
    _out, _err, ref_status = Open3.capture3('git', 'update-ref', ref, commit_sha)
    return { success: false, reason: :update_ref_failed } unless ref_status.success?

    Open3.capture3('git', 'reset', 'HEAD')
    { success: true, ref: ref, commit: commit_sha }
  end
end