Module: Worktrees::GitOperations

Defined in:
lib/worktrees/git_operations.rb

Class Method Summary collapse

Class Method Details

.branch_exists?(branch_name) ⇒ Boolean



36
37
38
# File 'lib/worktrees/git_operations.rb', line 36

def branch_exists?(branch_name)
  system('git', 'show-ref', '--verify', '--quiet', "refs/heads/#{branch_name}")
end

.create_worktree(path, branch, base_ref) ⇒ Object



6
7
8
9
10
11
12
13
14
15
# File 'lib/worktrees/git_operations.rb', line 6

def create_worktree(path, branch, base_ref)
  # Check if branch already exists
  if branch_exists?(branch)
    # Checkout existing branch
    system('git', 'worktree', 'add', path, branch)
  else
    # Create new branch from base_ref
    system('git', 'worktree', 'add', '-b', branch, path, base_ref)
  end
end

.current_branchObject



40
41
42
# File 'lib/worktrees/git_operations.rb', line 40

def current_branch
  `git rev-parse --abbrev-ref HEAD`.strip
end

.delete_branch(branch_name, force: false) ⇒ Object



62
63
64
65
# File 'lib/worktrees/git_operations.rb', line 62

def delete_branch(branch_name, force: false)
  flag = force ? '-D' : '-d'
  system('git', 'branch', flag, branch_name)
end

.fetch_ref(ref) ⇒ Object



58
59
60
# File 'lib/worktrees/git_operations.rb', line 58

def fetch_ref(ref)
  system('git', 'fetch', 'origin', ref)
end

.has_unpushed_commits?(branch_name) ⇒ Boolean



48
49
50
51
52
53
54
55
56
# File 'lib/worktrees/git_operations.rb', line 48

def has_unpushed_commits?(branch_name)
  begin
    output = `git rev-list @{u}..HEAD`
    $?.success? && !output.strip.empty?
  rescue StandardError
    # No upstream branch or other error - consider as no unpushed commits
    false
  end
end

.is_clean?(worktree_path) ⇒ Boolean



44
45
46
# File 'lib/worktrees/git_operations.rb', line 44

def is_clean?(worktree_path)
  system('git', 'diff-index', '--quiet', 'HEAD', chdir: worktree_path)
end

.is_merged?(branch_name, base_branch = 'main') ⇒ Boolean



67
68
69
70
# File 'lib/worktrees/git_operations.rb', line 67

def is_merged?(branch_name, base_branch = 'main')
  # Check if all commits in branch_name are reachable from base_branch
  system('git', 'merge-base', '--is-ancestor', branch_name, base_branch)
end

.list_worktreesObject



17
18
19
20
21
22
23
24
25
26
# File 'lib/worktrees/git_operations.rb', line 17

def list_worktrees
  begin
    output = `git worktree list --porcelain`
    raise GitError, "Failed to list worktrees: git command failed" unless $?.success?

    parse_worktree_list(output)
  rescue StandardError => e
    raise GitError, "Failed to list worktrees: #{e.message}"
  end
end

.remove_worktree(path, force: false) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/worktrees/git_operations.rb', line 28

def remove_worktree(path, force: false)
  args = ['git', 'worktree', 'remove']
  args << '--force' if force
  args << path

  system(*args)
end