Module: CommitGenerator

Defined in:
lib/commit_generator.rb

Class Method Summary collapse

Class Method Details

.generate_commit_message(changes_summary:, must_have_text: nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/commit_generator.rb', line 17

def self.generate_commit_message(changes_summary:, must_have_text: nil)
  output = OpenAIWrapper.call_api(
    messages: [
      {
        role: 'system',
        content: 'You are a helpful assistant that generates concise and semantic git commit messages.'
      },
      {
        role: 'user',
        content: "Generate a conventional git commit message limited to 72 characters for the following changes in a JSON format with a key 'commit_message', ensuring it includes the text: '#{must_have_text}':\n\n#{changes_summary}"
      }
    ]
  )
  JSON.parse(output)['commit_message']
end

.get_file_diff(file_path) ⇒ Object



13
14
15
# File 'lib/commit_generator.rb', line 13

def self.get_file_diff(file_path)
  `git diff --staged #{file_path}`
end

.get_staged_filesObject



9
10
11
# File 'lib/commit_generator.rb', line 9

def self.get_staged_files
  `git diff --name-only --staged`.split("\n")
end

.main(no_commit: false, must_have_text: nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/commit_generator.rb', line 33

def self.main(no_commit: false, must_have_text: nil)
  if openai_api_key.nil?
    puts 'No AUTOGITC_KEY key found in environment variables.'
    return
  end

  staged_files = get_staged_files

  if staged_files.empty?
    puts 'No files are staged for commit.'
    return
  end

  changes_summary = staged_files.map do |file|
    diff = get_file_diff(file)
    "Changes in #{file}:\n#{diff}\n"
  end.join("\n")

  commit_message = generate_commit_message(
    changes_summary: changes_summary,
    must_have_text: must_have_text
  )
  puts 'Generated commit message:'
  puts commit_message

  `git commit -m "#{commit_message}"` unless no_commit
end

.openai_api_keyObject



5
6
7
# File 'lib/commit_generator.rb', line 5

def self.openai_api_key
  ENV['AUTOGITC_KEY']
end