Class: Internator::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/internator/cli.rb

Overview

Command-line interface for the Internator gem

Constant Summary collapse

CONFIG_FILE =

Configuration file for custom options (YAML format).

File.expand_path('~/.internator_config.yml')

Class Method Summary collapse

Class Method Details

.auto_commitObject



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/internator/cli.rb', line 180

def self.auto_commit
  system('git', 'add', '-A')
  status = `git diff --cached --name-status`
  content = `git diff --cached`
  diff = "File status:\n#{status}\n\nDiff:\n#{content}"
  commit_msg = generate_commit_message(diff) || ''

  # Write full commit message to a temp file and commit via -F
  Tempfile.create('internator-commit') do |file|
    file.write(commit_msg)
    file.flush
    file.close
    if system('git', 'commit', '-F', file.path)
      first_line = commit_msg.lines.first.to_s.strip
      puts "✅ Commit made: #{first_line}"
    else
      puts "❌ Error committing"
    end
  end

  if system('git', 'push')
    puts "✅ Push successful"
  else
    puts "❌ Error pushing to remote"
  end
end

.codex_cycle(objectives, iteration) ⇒ Object

Executes one Codex iteration by diffing against the appropriate base branch



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/internator/cli.rb', line 123

def self.codex_cycle(objectives, iteration)
  # Determine configured upstream and current branch name
  upstream = `git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null`.strip
  current_branch = `git rev-parse --abbrev-ref HEAD`.strip
  # Choose diff base:
  # 1) If upstream is tracking current branch, use remote default branch
  # 2) Else if upstream exists, diff against that
  # 3) Otherwise fallback to remote default branch or master
  if !upstream.empty? && upstream.split('/').last == current_branch
    base = detect_default_base || upstream
  elsif !upstream.empty?
    base = upstream
  else
    base = detect_default_base || 'master'
  end
  # Get the diff against the chosen base
  current_diff = `git diff #{base} 2>/dev/null`
  current_diff = "No initial changes" if current_diff.strip.empty?
  prompt = <<~PROMPT
    Objectives: #{objectives}
    Iteration: #{iteration}
    Current Pull Request: #{current_diff}

    #{instructions}
  PROMPT

  CodexService.new(prompt).call
end

.configObject



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/internator/cli.rb', line 13

def self.config
  @config ||= begin
    if File.exist?(CONFIG_FILE)
      YAML.load_file(CONFIG_FILE)
    else
      {}
    end
  rescue => e
    warn "⚠️ Could not parse config file #{CONFIG_FILE}: #{e.message}"
    {}
  end
end

.detect_default_baseObject

Detect the repository’s default branch across remotes (e.g., main, master, develop)



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/internator/cli.rb', line 106

def self.detect_default_base
  remotes = `git remote`.split("\n").reject(&:empty?)
  remotes.unshift('origin') unless remotes.include?('origin')
  remotes.each do |remote|
    # Try to resolve remote HEAD via rev-parse
    ref = `git rev-parse --abbrev-ref #{remote}/HEAD 2>/dev/null`.strip
    return ref unless ref.empty?
    # Fallback to symbolic-ref
    sym = `git symbolic-ref refs/remotes/#{remote}/HEAD 2>/dev/null`.strip
    if sym.start_with?('refs/remotes/')
      return sym.sub('refs/remotes/', '')
    end
  end
  nil
end

.generate_commit_message(diff) ⇒ Object

Generate a concise commit message for the given diff using OpenAI



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/internator/cli.rb', line 153

def self.generate_commit_message(diff)
  api_key = ENV["OPENAI_API_KEY"]
  uri = URI("https://api.openai.com/v1/chat/completions")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  headers = {
    "Content-Type" => "application/json",
    "Authorization" => "Bearer #{api_key}"
  }
  body = {
    model: "gpt-4o-mini",
    messages: [
      { role: "system", content: "You are a helpful assistant that generates concise git commit messages." },
      { role: "user", content: "Generate a concise commit message for the following diff:\n\n#{diff}" }
    ],
    temperature: 0.3
  }
  response = http.post(uri.request_uri, JSON.generate(body), headers)
  if response.is_a?(Net::HTTPSuccess)
    json = JSON.parse(response.body)
    msg = json.dig("choices", 0, "message", "content")
    return msg.strip if msg
  end
rescue
  nil
end

.instructionsObject

Load custom instructions from config or fall back to built-in defaults



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
# File 'lib/internator/cli.rb', line 27

def self.instructions
  main = <<~MAIN_INSTRUCTIONS
    1. If there are changes in the PR, first check if it has already been completed; if so, do nothing.
    2. Make ONLY one incremental change.
    3. Prioritize completing main objectives.
  MAIN_INSTRUCTIONS

  # Load custom instructions from ~/.internator_config.yml or fall back to built-in defaults
  secondary =
    if config.is_a?(Hash) && config['instructions'].is_a?(String)
      config['instructions'].strip
    else
      <<~SECONDARY_INSTRUCTIONS
        1. Do not overuse code comments; if the method name says it all, comments are not necessary.
        2. Please treat files as if Vim were saving them with `set binary` and `set noeol`, i.e. do not add a final newline at the end of the file.
      SECONDARY_INSTRUCTIONS
    end

  <<~INSTRUCTIONS.chomp
  Main instructions:
  #{main}
  Secondary instructions:
  #{secondary}
  INSTRUCTIONS
end

.run(args = ARGV) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/internator/cli.rb', line 53

def self.run(args = ARGV)
  unless system("which codex > /dev/null 2>&1")
    abort "❌ 'codex' CLI is not installed or not in PATH. Please install it from https://github.com/openai/codex"
  end

  if ENV["OPENAI_API_KEY"].to_s.strip.empty?
    abort "❌ OPENAI_API_KEY not set. Please set the environment variable."
  end

  if args.empty? || args.size > 2
    abort "❌ Usage: internator \"<PR Objectives>\" [delay_mins]"
  end

  objectives = args[0]
  delay_mins = if args[1]
                 Integer(args[1]) rescue abort("❌ Invalid delay_mins: must be an integer")
               else
                 0
               end

  iteration = 1
  Signal.trap("INT") do
    puts "\n🛑 Interrupt received. Exiting cleanly..."
    exit
  end

  begin
    loop do
      puts "\n🌀 Iteration ##{iteration} - #{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"
      exit_code = codex_cycle(objectives, iteration)
      if exit_code != 0
        puts "🚨 Codex process exited with code #{exit_code}. Stopping."
        break
      end

      if `git status --porcelain`.strip.empty?
        puts "🎉 Objectives completed; no new changes. Exiting loop..."
        break
      end

      auto_commit
      puts "⏳ Waiting #{delay_mins} minutes for next iteration... Current time: #{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"
      sleep(delay_mins * 60)
      iteration += 1
    end
  rescue => e
    puts "🚨 Critical error: #{e.message}"
  ensure
    puts "\n🏁 Process completed - #{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"
  end
end