Class: CommitMsgAi::Cli
- Inherits:
-
Object
- Object
- CommitMsgAi::Cli
- Defined in:
- lib/commit_msg_ai/cli.rb
Overview
The ‘CommitMsgAi::Cli` class provides a command-line interface for generating commit messages using the Commit Message AI service. It fetches the staged git diff, communicates with the AI service to generate a commit message, and allows the user to confirm or edit the message before committing the changes.
Class Method Summary collapse
- .ask_user_to_confirm_or_edit(commit_message) ⇒ Object
- .git_diff ⇒ Object
- .run ⇒ Object
- .split_commit_message(message) ⇒ Object
Class Method Details
.ask_user_to_confirm_or_edit(commit_message) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/commit_msg_ai/cli.rb', line 50 def self.ask_user_to_confirm_or_edit() puts "\nSuggested Commit Message:\n\n#{commit_message}" loop do puts "\nDo you want to:" puts '1. Use this message as-is.' puts '2. Edit this message.' puts '3. Abort the commit process.' print "\nEnter your choice (1, 2, or 3): " case gets.strip when '1' return when '2' puts "\nEnter your custom commit message (leave blank to keep the original):" puts print '> ' = $stdin.read.strip return .empty? ? : when '3' puts "\nCommit process aborted." exit 0 else puts "\nInvalid choice. Please try again." end end end |
.git_diff ⇒ Object
40 41 42 43 44 45 46 47 48 |
# File 'lib/commit_msg_ai/cli.rb', line 40 def self.git_diff stdout, stderr, status = Open3.capture3('git diff --staged') raise "Error getting git diff: #{stderr}" unless status.success? stdout.strip rescue StandardError => e puts e. exit 1 end |
.run ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/commit_msg_ai/cli.rb', line 15 def self.run api_token = ENV.fetch('OPENAI_ACCESS_TOKEN', nil) unless api_token puts 'Error: Missing OpenAI API token. Please set OPENAI_ACCESS_TOKEN in your environment variables.' exit 1 end diff = git_diff if diff.empty? puts 'No staged changes to commit.' exit 0 end commit_ai = CommitMsgAi::Client.new(api_token) = commit_ai.(diff) = ask_user_to_confirm_or_edit() subject, body = () puts "\nFinal Commit Message:\n\n#{final_message}" puts "\nRunning git commit..." system("git commit -m #{Shellwords.escape(subject)} -m #{Shellwords.escape(body)}") end |
.split_commit_message(message) ⇒ Object
77 78 79 80 81 82 |
# File 'lib/commit_msg_ai/cli.rb', line 77 def self.() lines = .strip.split("\n", 2) subject = lines[0] body = lines[1..]&.join("\n") || '' [subject, body] end |