Class: Git::Gpt::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/git/gpt.rb

Instance Method Summary collapse

Instance Method Details

#find_file(filename) ⇒ Object

Find the closest .git-gpt-config.yml file in the current directory, any parent directory or the users home directory



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/git/gpt.rb', line 60

def find_file(filename)
  paths = []
  path_pieces = Dir.pwd.split(File::SEPARATOR)
  while path_pieces.any?
    path = path_pieces.join(File::SEPARATOR)
    path_pieces.pop
    paths << [path, filename].join(File::SEPARATOR)
  end
  paths << [ENV["HOME"], filename].join(File::SEPARATOR) if ENV["HOME"]
  result = paths.detect { |path| File.exist?(path) }
  result
end

#run(argv = nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
# File 'lib/git/gpt.rb', line 12

def run(argv=nil)
  prompt ="You are a software engineer working on a project. You write diligent and detailed commit messages. You are working on a new feature and you are ready to commit your changes.\n\nThe current git status is:\n\n$GIT_STATUS\n\nThe current git diff is:\n\n$GIT_DIFF\n\nPlease write a commit message for this change. Format the commit message using markdown. You may use bullet points. Please comment specifically on any files with significant changes.\n"

  config = {
    "model" => "gpt-3.5-turbo",
    "temperature" => 0.7,
    "prompt" => prompt,
    "openai_api_key" => ENV["OPENAI_API_KEY"],
    "openai_organization_id" => ENV["OPENAI_ORGANIZATION_ID"]
  }
  config_filename = find_file(".git-gpt-config.yml")
  config_file = YAML.load_file(config_filename) if config_filename
  config.merge!(config_file) if config_file

  if config["openai_api_key"].nil?
    puts "Please set OPENAI_API_KEY environment variable"
    exit 1
  end

  git_status = `git status #{argv.join(" ")}`
  git_diff = `git diff #{argv.join(" ")}`

  prompt = config["prompt"].gsub("$GIT_STATUS", git_status).gsub("$GIT_DIFF", git_diff)

  client = OpenAI::Client.new(access_token: config["openai_api_key"], organization_id: config["openai_organization_id"])
  response = client.chat(
    parameters: {
      model: config["model"],
      temperature: config["temperature"],
      messages: [{ role: "user", content: prompt }]
    }
  )
  puts response.dig("choices", 0, "message", "content")
end