Class: N2B::GitHubClient
- Inherits:
-
Object
- Object
- N2B::GitHubClient
- Defined in:
- lib/n2b/github_client.rb
Defined Under Namespace
Classes: GitHubApiError
Instance Method Summary collapse
- #classify_error_severity(error_text) ⇒ Object
- #clean_error_description(text) ⇒ Object
- #execute_vcs_command_with_timeout(command, timeout_seconds) ⇒ Object
- #extract_file_reference(text) ⇒ Object
- #extract_git_info ⇒ Object
- #extract_missing_tests(test_coverage_text) ⇒ Object
- #extract_requirements_status(requirements_text) ⇒ Object
- #fetch_issue(issue_input) ⇒ Object
- #generate_templated_comment(comment_data) ⇒ Object
- #get_config(reconfigure: false, advanced_flow: false) ⇒ Object
-
#initialize(config) ⇒ GitHubClient
constructor
A new instance of GitHubClient.
- #prepare_template_data(comment_data) ⇒ Object
- #resolve_template_path(template_key, config) ⇒ Object
- #test_connection ⇒ Object
- #update_issue(issue_input, comment_data) ⇒ Object
Constructor Details
#initialize(config) ⇒ GitHubClient
Returns a new instance of GitHubClient.
10 11 12 13 14 15 16 17 |
# File 'lib/n2b/github_client.rb', line 10 def initialize(config) @config = config @github_config = @config['github'] || {} unless @github_config['repo'] && @github_config['access_token'] raise ArgumentError, "GitHub repo and access token must be configured in N2B settings." end @api_base = @github_config['api_base'] || 'https://api.github.com' end |
Instance Method Details
#classify_error_severity(error_text) ⇒ Object
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/n2b/github_client.rb', line 102 def classify_error_severity(error_text) text = error_text.downcase case text when /security|sql injection|xss|csrf|vulnerability|exploit|attack/ 'CRITICAL' when /performance|n\+1|timeout|memory leak|slow query|bottleneck/ 'IMPORTANT' when /error|exception|bug|fail|crash|break/ 'IMPORTANT' when /style|convention|naming|format|indent|space/ 'LOW' else 'IMPORTANT' end end |
#clean_error_description(text) ⇒ Object
128 129 130 |
# File 'lib/n2b/github_client.rb', line 128 def clean_error_description(text) text.gsub(/\S+\.(?:rb|js|py|java|cpp|c|h|ts|jsx|tsx|php|go|rs|swift|kt)(?:\s+(?:line|lines?)\s+\d+(?:-\d+)?|:\d+(?:-\d+)?|\s*\(line\s+\d+\))?:?\s*/i, '').strip end |
#execute_vcs_command_with_timeout(command, timeout_seconds) ⇒ Object
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
# File 'lib/n2b/github_client.rb', line 224 def execute_vcs_command_with_timeout(command, timeout_seconds) require 'open3' begin # Use Open3.popen3 with manual timeout handling to avoid thread issues stdin, stdout, stderr, wait_thr = Open3.popen3(command) stdin.close # Manual timeout implementation start_time = Time.now while wait_thr.alive? if Time.now - start_time > timeout_seconds # Kill the process begin Process.kill('TERM', wait_thr.pid) sleep(0.5) Process.kill('KILL', wait_thr.pid) if wait_thr.alive? rescue Errno::ESRCH # Process already dead end stdout.close stderr.close return { success: false, error: "Command timed out after #{timeout_seconds} seconds" } end sleep(0.1) end # Process completed within timeout stdout_content = stdout.read stderr_content = stderr.read stdout.close stderr.close exit_status = wait_thr.value if exit_status.success? { success: true, stdout: stdout_content, stderr: stderr_content } else { success: false, error: stderr_content.empty? ? "Command failed with exit code #{exit_status.exitstatus}" : stderr_content } end rescue => e { success: false, error: "Unexpected error: #{e.}" } end end |
#extract_file_reference(text) ⇒ Object
118 119 120 121 122 123 124 125 126 |
# File 'lib/n2b/github_client.rb', line 118 def extract_file_reference(text) if match = text.match(/(\S+\.(?:rb|js|py|java|cpp|c|h|ts|jsx|tsx|php|go|rs|swift|kt))(?:\s+(?:line|lines?)\s+(\d+(?:-\d+)?)|:(\d+(?:-\d+)?)|\s*\(line\s+(\d+)\))?/i) file = match[1] line = match[2] || match[3] || match[4] line ? "#{file}:#{line}" : file else 'General' end end |
#extract_git_info ⇒ Object
178 179 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# File 'lib/n2b/github_client.rb', line 178 def extract_git_info begin if File.exist?('.git') branch = execute_vcs_command_with_timeout('git branch --show-current', 5) branch = branch[:success] ? branch[:stdout].strip : 'unknown' branch = 'unknown' if branch.empty? diff_result = execute_vcs_command_with_timeout('git diff --stat HEAD~1', 5) if diff_result[:success] diff_stats = diff_result[:stdout].strip files_changed = diff_stats.scan(/(\d+) files? changed/).flatten.first || '0' lines_added = diff_stats.scan(/(\d+) insertions?/).flatten.first || '0' lines_removed = diff_stats.scan(/(\d+) deletions?/).flatten.first || '0' else files_changed = '0' lines_added = '0' lines_removed = '0' end elsif File.exist?('.hg') branch_result = execute_vcs_command_with_timeout('hg branch', 5) branch = branch_result[:success] ? branch_result[:stdout].strip : 'default' branch = 'default' if branch.empty? diff_result = execute_vcs_command_with_timeout('hg diff --stat', 5) if diff_result[:success] files_changed = diff_result[:stdout].lines.count.to_s else files_changed = '0' end lines_added = '0' lines_removed = '0' else branch = 'unknown' files_changed = '0' lines_added = '0' lines_removed = '0' end rescue branch = 'unknown' files_changed = '0' lines_added = '0' lines_removed = '0' end { branch: branch, files_changed: files_changed, lines_added: lines_added, lines_removed: lines_removed } end |
#extract_missing_tests(test_coverage_text) ⇒ Object
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/n2b/github_client.rb', line 132 def extract_missing_tests(test_coverage_text) missing_tests = [] test_coverage_text.scan(/(?:missing|need|add|require).*?test.*?(?:\.|$)/i) do |match| missing_tests << { 'description' => match.strip } end if missing_tests.empty? && test_coverage_text.include?('%') if coverage_match = test_coverage_text.match(/(\d+)%/) coverage = coverage_match[1].to_i if coverage < 80 missing_tests << { 'description' => "Increase test coverage from #{coverage}% to target 80%+" } end end end missing_tests end |
#extract_requirements_status(requirements_text) ⇒ Object
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'lib/n2b/github_client.rb', line 148 def extract_requirements_status(requirements_text) requirements = [] requirements_text.split("\n").each do |line| line = line.strip next if line.empty? if match = line.match(/(✅|⚠️|❌|🔍)?\s*(PARTIALLY\s+IMPLEMENTED|NOT\s+IMPLEMENTED|IMPLEMENTED|UNCLEAR)?:?\s*(.+)/i) status_emoji, status_text, description = match.captures status = case when status_text&.include?('PARTIALLY') 'PARTIALLY_IMPLEMENTED' when status_text&.include?('NOT') 'NOT_IMPLEMENTED' when status_emoji == '✅' || (status_text&.include?('IMPLEMENTED') && !status_text&.include?('NOT') && !status_text&.include?('PARTIALLY')) 'IMPLEMENTED' when status_emoji == '⚠️' 'PARTIALLY_IMPLEMENTED' when status_emoji == '❌' 'NOT_IMPLEMENTED' else 'UNCLEAR' end requirements << { 'status' => status, 'description' => description.strip } end end requirements end |
#fetch_issue(issue_input) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/n2b/github_client.rb', line 19 def fetch_issue(issue_input) repo, number = parse_issue_input(issue_input) begin issue_data = make_api_request('GET', "/repos/#{repo}/issues/#{number}") comments = make_api_request('GET', "/repos/#{repo}/issues/#{number}/comments") format_issue_for_requirements(repo, issue_data, comments) rescue GitHubApiError => e puts "⚠️ Failed to fetch from GitHub API: #{e.}" fetch_dummy_issue_data(repo, number) end end |
#generate_templated_comment(comment_data) ⇒ Object
43 44 45 46 47 48 49 |
# File 'lib/n2b/github_client.rb', line 43 def generate_templated_comment(comment_data) template_data = prepare_template_data(comment_data) template_path = resolve_template_path('github_comment', @config) template_content = File.read(template_path) engine = N2B::TemplateEngine.new(template_content, template_data) engine.render end |
#get_config(reconfigure: false, advanced_flow: false) ⇒ Object
274 275 276 277 278 |
# File 'lib/n2b/github_client.rb', line 274 def get_config(reconfigure: false, advanced_flow: false) # Return the config that was passed during initialization # This is used for template resolution and other configuration needs @config end |
#prepare_template_data(comment_data) ⇒ Object
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 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 |
# File 'lib/n2b/github_client.rb', line 51 def prepare_template_data(comment_data) errors = comment_data[:issues] || comment_data['issues'] || [] critical_errors = [] important_errors = [] errors.each do |error| severity = classify_error_severity(error) file_ref = extract_file_reference(error) item = { 'file_reference' => file_ref, 'description' => clean_error_description(error) } case severity when 'CRITICAL' critical_errors << item else important_errors << item end end improvements = (comment_data[:improvements] || comment_data['improvements'] || []).map do |imp| { 'file_reference' => extract_file_reference(imp), 'description' => clean_error_description(imp) } end missing_tests = extract_missing_tests(comment_data[:test_coverage] || comment_data['test_coverage'] || '') requirements = extract_requirements_status(comment_data[:requirements_evaluation] || comment_data['requirements_evaluation'] || '') git_info = extract_git_info { 'implementation_summary' => comment_data[:implementation_summary] || comment_data['implementation_summary'] || 'Code analysis completed', 'critical_errors' => critical_errors, 'important_errors' => important_errors, 'improvements' => improvements, 'missing_tests' => missing_tests, 'requirements' => requirements, 'timestamp' => Time.now.strftime('%Y-%m-%d %H:%M UTC'), 'branch_name' => git_info[:branch], 'files_changed' => git_info[:files_changed], 'lines_added' => git_info[:lines_added], 'lines_removed' => git_info[:lines_removed], 'critical_errors_empty' => critical_errors.empty?, 'important_errors_empty' => important_errors.empty?, 'improvements_empty' => improvements.empty?, 'missing_tests_empty' => missing_tests.empty? } end |
#resolve_template_path(template_key, config) ⇒ Object
268 269 270 271 272 |
# File 'lib/n2b/github_client.rb', line 268 def resolve_template_path(template_key, config) user_path = config.dig('templates', template_key) if config.is_a?(Hash) return user_path if user_path && File.exist?(user_path) File.(File.join(__dir__, 'templates', "#{template_key}.txt")) end |
#test_connection ⇒ Object
280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
# File 'lib/n2b/github_client.rb', line 280 def test_connection puts "🧪 Testing GitHub API connection..." begin user = make_api_request('GET', '/user') puts "✅ Authentication successful as #{user['login']}" repo = @github_config['repo'] repo_data = make_api_request('GET', "/repos/#{repo}") puts "✅ Access to repository #{repo_data['full_name']}" true rescue => e puts "❌ GitHub connection test failed: #{e.}" false end end |
#update_issue(issue_input, comment_data) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/n2b/github_client.rb', line 31 def update_issue(issue_input, comment_data) repo, number = parse_issue_input(issue_input) body_text = comment_data.is_a?(String) ? comment_data : generate_templated_comment(comment_data) body = { 'body' => body_text } make_api_request('POST', "/repos/#{repo}/issues/#{number}/comments", body) puts "✅ Successfully added comment to GitHub issue #{repo}##{number}" true rescue GitHubApiError => e puts "❌ Failed to update GitHub issue #{repo}##{number}: #{e.}" false end |