Module: AIGit::Git

Defined in:
lib/ai_git/git.rb

Constant Summary collapse

NOT_A_REPOSITORY =
"Not a git repository (or any of the parent directories)."
MAX_ERROR_DETAIL =
500

Class Method Summary collapse

Class Method Details

.capture(*argv) ⇒ Object



58
59
60
61
62
63
# File 'lib/ai_git/git.rb', line 58

def capture(*argv)
  stdout, stderr, status = Open3.capture3(*argv)
  return stdout if status.success?

  raise command_error(argv, stderr, status)
end

.command_error(argv, stderr, status) ⇒ Object



74
75
76
77
78
79
80
# File 'lib/ai_git/git.rb', line 74

def command_error(argv, stderr, status)
  detail = stderr.to_s.strip
  detail = "#{detail[0, MAX_ERROR_DETAIL]}" if detail.length > MAX_ERROR_DETAIL
  header = "Command failed: #{argv.join(' ')} (exit #{status.exitstatus})"

  detail.empty? ? header : "#{header}\n#{detail}"
end

.commit_with_message(message) ⇒ Object



82
83
84
85
86
87
88
89
# File 'lib/ai_git/git.rb', line 82

def commit_with_message(message)
  Tempfile.create("ai_git_commit_msg") do |file|
    file.write(message)
    file.flush

    run_command("git", "commit", "-F", file.path)
  end
end

.current_branchObject



45
46
47
48
49
50
51
52
# File 'lib/ai_git/git.rb', line 45

def current_branch
  ensure_repository!
  stdout, _stderr, status = Open3.capture3("git", "symbolic-ref", "--quiet", "--short", "HEAD")
  return nil unless status.success?

  branch = stdout.chomp
  branch.empty? ? nil : branch
end

.detached_head?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/ai_git/git.rb', line 54

def detached_head?
  current_branch.nil?
end

.diffObject



40
41
42
43
# File 'lib/ai_git/git.rb', line 40

def diff
  ensure_repository!
  capture("git", "diff", "--cached")
end

.ensure_repository!Object

Raises:



31
32
33
# File 'lib/ai_git/git.rb', line 31

def ensure_repository!
  raise NOT_A_REPOSITORY unless repository?
end

.push_current_branchObject



91
92
93
# File 'lib/ai_git/git.rb', line 91

def push_current_branch
  run_command("git", "push", "-u", "origin", "HEAD")
end

.repository?Boolean

Returns:

  • (Boolean)


26
27
28
29
# File 'lib/ai_git/git.rb', line 26

def repository?
  _stdout, _stderr, status = Open3.capture3("git", "rev-parse", "--git-dir")
  status.success?
end

.run_command(cmd, *args) ⇒ Object



65
66
67
68
69
70
71
72
# File 'lib/ai_git/git.rb', line 65

def run_command(cmd, *args)
  argv = [cmd, *args.map(&:to_s)]
  _stdout, stderr, status = Open3.capture3(*argv)

  return if status.success?

  raise command_error(argv, stderr, status)
end

.staged_filesObject



35
36
37
38
# File 'lib/ai_git/git.rb', line 35

def staged_files
  ensure_repository!
  capture("git", "diff", "--cached", "--name-only")
end