Class: GithubRepoStatistics
- Inherits:
-
Object
- Object
- GithubRepoStatistics
- Defined in:
- lib/github_repo_statistics.rb,
lib/github_repo_statistics/version.rb,
lib/github_repo_statistics/github_repo_statistics.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- VERSION =
'2.3.26'
Instance Method Summary collapse
- #analyze_changed_files(uniq_code_files_with_changes:, start_date:, end_date:, branch: DEFAULT_BRANCH) ⇒ Object
- #calculate_percentile(arr, percentile) ⇒ Object
- #contribution_message ⇒ Object
- #count_big_files(directory_path, size: BIG_FILE_SIZE) ⇒ Object
- #count_hotspot_lines(files) ⇒ Object
- #count_lines_of_code(file) ⇒ Object
- #files_with_changes(directory_path:, start_date:, end_date:, branch: DEFAULT_BRANCH) ⇒ Object
- #filter_existing_code_files(files, start_date, end_date) ⇒ Object
- #filter_files(file_team_map:, size: BIG_FILE_SIZE) ⇒ Object
- #find_owner(file:) ⇒ Object
- #find_owners(file_path, codeowners) ⇒ Object
- #git_commit_count(file:, start_date:, end_date:, branch: DEFAULT_BRANCH) ⇒ Object
- #git_commit_info(file:, start_date:, end_date:, branch: DEFAULT_BRANCH) ⇒ Object
- #git_files(directory_path:) ⇒ Object
- #handle_codeowners(file_team_map:) ⇒ Object
- #hotspot_check(files:, branch:) ⇒ Object
-
#initialize(directory_path:, duration_in_days:, begin_time:, debug: nil, steps: 1) ⇒ GithubRepoStatistics
constructor
A new instance of GithubRepoStatistics.
- #new_changes?(file:) ⇒ Boolean
- #read_codeowners_file ⇒ Object
- #true?(obj) ⇒ Boolean
Constructor Details
#initialize(directory_path:, duration_in_days:, begin_time:, debug: nil, steps: 1) ⇒ GithubRepoStatistics
Returns a new instance of GithubRepoStatistics.
8 9 10 11 12 13 14 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 8 def initialize(directory_path:, duration_in_days:, begin_time:, debug: nil, steps: 1) @directory_path = directory_path @duration_in_days = duration_in_days @begin_time = begin_time @debug = debug @steps = steps end |
Instance Method Details
#analyze_changed_files(uniq_code_files_with_changes:, start_date:, end_date:, branch: DEFAULT_BRANCH) ⇒ Object
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 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 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 202 def analyze_changed_files(uniq_code_files_with_changes:, start_date:, end_date:, branch: DEFAULT_BRANCH) all_teams = [] cross_teams_count = 0 single_ownership_teams_count = 0 files_changed_by_many_teams = 0 total_changes = 0 file_team_map = {} uniq_code_files_with_changes.each do |file| filename = File.basename(file) commit_count = git_commit_count(file:, start_date:, end_date:, branch:).to_i git_log = git_commit_info(file:, start_date:, end_date:, branch:).split("\n") if EXCLUDED_PRS excluded_prs = EXCLUDED_PRS.split(',') git_log = git_log.reject { |c| excluded_prs.any? { |pr| c.include?(pr) } } end if EXCLUDED_CONTRIBUTOR_NAMES excluded_contributor_names = EXCLUDED_CONTRIBUTOR_NAMES.split(',') git_log = git_log.reject { |c| excluded_contributor_names.any? { |cr| c.include?(cr) } } end prs = git_log.map do |pr| match = pr.match(/#(\d+)/) match[0] if match end.uniq teams = git_log.map do |team| team.match(/#{TEAM_REGEX}/)[0].upcase end.reject { |e| EXCLUSIONS&.include?(e) } teams = calculate_percentile(teams, PERCENTILE.to_i) total_changes += commit_count all_teams << teams if teams.count > 1 files_changed_by_many_teams += 1 file_team_map.merge!(file.to_s => [teams, prs, commit_count]) cross_teams_count += teams.count else single_ownership_teams_count += 1 end puts "\n#{filename} [#{commit_count}]:#{teams}\n" if @debug end [all_teams, cross_teams_count, single_ownership_teams_count, files_changed_by_many_teams, total_changes, file_team_map] end |
#calculate_percentile(arr, percentile) ⇒ Object
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 253 def calculate_percentile(arr, percentile) # Count occurrences of each unique element counts = arr.each_with_object(Hash.new(0)) { |item, hash| hash[item] += 1 } # Sort elements by their counts in descending order sorted_counts = counts.sort_by { |_k, v| -v }.to_h # Calculate the cut-off for the percentile total_count = arr.size cutoff = total_count * (percentile / 100.0) # Select elements that meet the percentile criteria selected_elements = [] cumulative_count = 0 sorted_counts.each do |item, count| cumulative_count += count selected_elements << item break if cumulative_count >= cutoff end selected_elements end |
#contribution_message ⇒ Object
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 286 def duration_in_days = @duration_in_days.to_i start_date = @begin_time.to_time.to_i - duration_in_days * 86_400 end_date = @begin_time.to_time.to_i git_ls = git_files(directory_path: @directory_path) file_count = filter_existing_code_files(git_ls.split, start_date, end_date).count all_files_with_changes = files_with_changes(directory_path: @directory_path, start_date:, end_date:).split.sort code_files_with_changes = filter_existing_code_files(all_files_with_changes, start_date, end_date) uniq_code_files_with_changes = code_files_with_changes.uniq all_teams, cross_teams_count, single_ownership_teams_count, files_changed_by_many_teams, total_changes, file_team_map = analyze_changed_files( uniq_code_files_with_changes:, start_date:, end_date: ) occurrences = all_teams.flatten.compact.tally sorted_occurrences = occurrences.sort_by { |element, count| [-count, element] } contributors = Hash[sorted_occurrences] churn_count = file_team_map.values.map(&:last).sum hotspot_changes_percentage = ((churn_count.to_f / total_changes) * 100).round(2) # Filter files based on extension, existence and size filtered_files = filter_files(file_team_map:) filtered_top_touched_files = filtered_files.sort_by { |element, count| [-count.last, element] } files_with_single_contributor_percentage = (100 - ((files_changed_by_many_teams.to_f / file_count) * 100)).round(2) hotspot_lines = count_hotspot_lines(filtered_files.keys) big_files_count = count_big_files(@directory_path) # ENV['BQ_CREDENTIALS'] = `cat /Users/serghei.moret/.config/gcloud/application_default_credentials.json` if ENV['BQ_CREDENTIALS'] require 'google/cloud/bigquery' require 'json' creds = JSON.parse(ENV['BQ_CREDENTIALS']) bigquery = Google::Cloud::Bigquery.new( project_id: 'hellofresh-android', credentials: creds ) dataset = bigquery.dataset 'github_data' files_with_multiple_contributor = file_team_map.count big_files_with_multiple_contributors = filtered_top_touched_files.count total_files_changed = uniq_code_files_with_changes.count platform = if @directory_path == 'HelloFresh/HelloFresh/' 'ios' elsif @directory_path == 'features/legacy/' 'android' end query = <<~SQL INSERT INTO modularization (date, platform, single_contributor_percentage, files_changed_by_many_teams, file_count, cross_teams_count, single_ownership_teams_count, hotspot_changes_percentage, churn_count, total_changes, files_with_multiple_contributor, big_files_with_multiple_contributors, total_files_changed, hotspot_lines, big_files_count) VALUES ('#{@begin_time}', '#{platform}', #{files_with_single_contributor_percentage}, #{files_changed_by_many_teams}, #{file_count}, #{cross_teams_count}, #{single_ownership_teams_count}, #{hotspot_changes_percentage}, #{churn_count}, #{total_changes}, #{files_with_multiple_contributor}, #{big_files_with_multiple_contributors}, #{total_files_changed}, #{hotspot_lines}, #{big_files_count}); SQL dataset.query(query) # delete_query = <<~SQL # DELETE FROM modularization # WHERE CONCAT(DATE(date), ' ', TIME(date)) NOT IN ( # SELECT CONCAT(DATE(date), ' ', TIME(date)) # FROM modularization AS m1 # WHERE TIME(date) = ( # SELECT MAX(TIME(date)) # FROM modularization AS m2 # WHERE DATE(m1.date) = DATE(m2.date) # ) # ); # SQL # dataset.query(delete_query) end puts '' puts "*Timeframe:* #{(@begin_time - duration_in_days).strftime('%Y-%m-%d')} to #{@begin_time.strftime('%Y-%m-%d')}" puts " *Code files with a single contributor:* #{files_with_single_contributor_percentage}%" puts " *Existing files changed by many teams:* #{files_changed_by_many_teams}" puts " *Current existing #{CODE_EXTENSIONS} files:* #{file_count}" puts ' *Cross-Squad Dependency:*' puts " *Contributions by multiple squads to the same files:* #{cross_teams_count}" puts " *Contributions by single squads contributing to single files:* #{single_ownership_teams_count}" puts " *Hotspot Code Changes:* #{hotspot_changes_percentage}%" puts " *Churn count(commits to files by multiple teams):* #{churn_count}" puts " *Total amount of commits:* #{total_changes}" puts " *Total lines of hotspot code:* #{hotspot_lines}" puts " *#{CODE_EXTENSIONS} files with multiple contributors:* #{file_team_map.count}" puts " *#{CODE_EXTENSIONS} files exceeding #{BIG_FILE_SIZE} lines with multiple contributors:* #{filtered_top_touched_files.count}" puts " *Total amount of commits to #{CODE_EXTENSIONS} files:* #{total_changes}" puts " *Total #{CODE_EXTENSIONS} files changed:* #{uniq_code_files_with_changes.count}" puts " *Current total number of code files longer than #{BIG_FILE_SIZE} lines:* #{big_files_count}" puts " *Current total of #{CODE_EXTENSIONS} files in the folder:* #{file_count}" puts " *Contributors:* #{contributors}" if HOTSPOT hotspot_output = [] filter_files(file_team_map:, size: 0).each do |line| file = line.first contributors = line.last.first lines_of_code = count_lines_of_code(file) commits = line.last.last owner = find_owner(file:) prs = line.last[1] new_change = new_changes?(file:) hotspot_output << [file.gsub(@directory_path, ''), new_change, contributors, lines_of_code, commits, owner, prs] end hotspot_output.sort_by! { |row| -row[3] } if FILE_OUTPUT CSV.open('hotspot.csv', 'w') do |csv| csv << ['File', 'Updated in the past week', 'Contributors', 'Lines', 'Commits', 'Owner', 'PRs'] hotspot_output.each do |row| csv << row end end else puts "\n *Hotspot files(#{filtered_top_touched_files.count}):*\n" hotspot_output.each do |row| puts " #{row[0]} Contributors: #{row[1]} Updated in the past week: #{row[2]} Lines: #{row[3]} Commits: #{row[4]} Owner: #{row[5]} PRs: #{row[6]}" end end end handle_codeowners(file_team_map:) if CODEOWNERS @steps -= 1 return unless @steps.positive? system("git checkout `git rev-list -1 --before='#{(@begin_time - duration_in_days).strftime('%B %d %Y')}' HEAD`", %i[out err] => File::NULL) @begin_time -= duration_in_days end |
#count_big_files(directory_path, size: BIG_FILE_SIZE) ⇒ Object
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 108 def count_big_files(directory_path, size: BIG_FILE_SIZE) size = size.to_i # Get a list of all files in the specified directory files = Dir.glob(File.join(directory_path, '**', '*')).select { |file| File.file?(file) } code_files = files.select do |f| extension = File.extname(f) valid_extensions = CODE_EXTENSIONS valid_extensions.include?(extension) end # Initialize a counter for files that meet the criteria count = 0 # Iterate through each file and check the line count code_files.each do |file| lines_count = File.foreach(file).reject { |line| line.match(%r{^\s*(//|/\*.*\*/|\s*$)}) }.count count += 1 if lines_count > size end count end |
#count_hotspot_lines(files) ⇒ Object
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 131 def count_hotspot_lines(files) code_files = files.select do |f| extension = File.extname(f) valid_extensions = CODE_EXTENSIONS valid_extensions.include?(extension) end count = 0 code_files.each do |file| lines_count = File.foreach(file).reject { |line| line.match(%r{^\s*(//|/\*.*\*/|\s*$)}) }.count count += lines_count end count end |
#count_lines_of_code(file) ⇒ Object
149 150 151 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 149 def count_lines_of_code(file) File.foreach(file).reject { |line| line.match(%r{^\s*(//|/\*.*\*/|\s*$)}) }.count end |
#files_with_changes(directory_path:, start_date:, end_date:, branch: DEFAULT_BRANCH) ⇒ Object
186 187 188 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 186 def files_with_changes(directory_path:, start_date:, end_date:, branch: DEFAULT_BRANCH) `git log origin/#{branch} --name-only --pretty=format:"" --since="#{start_date}" --until="#{end_date}" "#{directory_path}"` end |
#filter_existing_code_files(files, start_date, end_date) ⇒ Object
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 179 180 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 153 def filter_existing_code_files(files, start_date, end_date) files.select do |f| next unless File.exist?(f) git_log = git_commit_info(file: f, start_date:, end_date:).split("\n") teams = git_log.map do |team| team.match(/#{TEAM_REGEX}/)[0].upcase end.reject { |e| EXCLUSIONS&.include?(e) } if TEAM_TO_FOCUS && CODEOWNER_TO_FOCUS next if !teams.include?(TEAM_TO_FOCUS) && !find_owner(file: f).include?(CODEOWNER_TO_FOCUS) elsif TEAM_TO_FOCUS next unless teams.include?(TEAM_TO_FOCUS) elsif CODEOWNER_TO_FOCUS next unless find_owner(file: f).include?(CODEOWNER_TO_FOCUS) end if EXCLUDED_FILES excluded_patterns = EXCLUDED_FILES.split(',') next if excluded_patterns.any? { |pattern| f.include?(pattern) } end extension = File.extname(f) valid_extensions = CODE_EXTENSIONS valid_extensions.include?(extension) end end |
#filter_files(file_team_map:, size: BIG_FILE_SIZE) ⇒ Object
277 278 279 280 281 282 283 284 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 277 def filter_files(file_team_map:, size: BIG_FILE_SIZE) file_team_map.select do |file_path| next unless File.exist?(file_path) # Check if the file size is more than BIG_FILE_SIZE lines (excluding empty and commented lines) File.foreach(file_path).reject { |line| line.match(%r{^\s*(//|/\*.*\*/|\s*$)}) }.count > size.to_i end end |
#find_owner(file:) ⇒ Object
103 104 105 106 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 103 def find_owner(file:) codeowners = read_codeowners_file find_owners(file, codeowners) end |
#find_owners(file_path, codeowners) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 35 def find_owners(file_path, codeowners) matching_patterns = codeowners.keys.select do |pattern| pattern_regex = Regexp.new("^#{Regexp.escape(pattern.sub(%r{^/+}, '').chomp('/')).gsub('\*', '.*').gsub('**', '.*?')}") file_path =~ pattern_regex end return ['unknown'] if matching_patterns.empty? # Sort patterns by length in descending order sorted_patterns = matching_patterns.sort_by(&:length).reverse # Find the most specific matching pattern best_match = sorted_patterns.find do |pattern| pattern_regex = Regexp.new("^#{Regexp.escape(pattern.sub(%r{^/+}, '').chomp('/')).gsub('\*', '.*').gsub('**', '.*?')}") file_path =~ pattern_regex end codeowners[best_match].split(' ') end |
#git_commit_count(file:, start_date:, end_date:, branch: DEFAULT_BRANCH) ⇒ Object
190 191 192 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 190 def git_commit_count(file:, start_date:, end_date:, branch: DEFAULT_BRANCH) `git log origin/#{branch} --since="#{start_date}" --until="#{end_date}" --follow -- "#{file}" | grep -c '^commit'` end |
#git_commit_info(file:, start_date:, end_date:, branch: DEFAULT_BRANCH) ⇒ Object
194 195 196 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 194 def git_commit_info(file:, start_date:, end_date:, branch: DEFAULT_BRANCH) `git log origin/#{branch} --pretty=format:"%s : %an" --since="#{start_date}" --until="#{end_date}" -- "#{file}"` end |
#git_files(directory_path:) ⇒ Object
182 183 184 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 182 def git_files(directory_path:) `git ls-tree -r --name-only $(git rev-list -1 HEAD) -- "#{directory_path}"` end |
#handle_codeowners(file_team_map:) ⇒ Object
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 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 57 def handle_codeowners(file_team_map:) output = "\n *Code ownership data:*\n" codeowners = read_codeowners_file owners_data = Hash.new do |hash, key| hash[key] = { directories: Hash.new do |h, k| h[k] = { files: [] } end, churn_count: 0 } end file_team_map.each do |file, count| owners = find_owners(file, codeowners) owners.each do |owner| owners_data[owner][:churn_count] += count.last dir_path = File.dirname(file) owners_data[owner][:directories][dir_path][:files] << { name: File.basename(file), count: } end end # Sort owners_data by total count in descending order sorted_owners_data = owners_data.sort_by { |_, data| -data[:churn_count] } converted_team_map = file_team_map.transform_keys { |key| File.basename(key) } sorted_owners_data.each do |owner, data| output += "\n #{owner.split('/').last}:\n Total Count: #{data[:churn_count]}\n" data[:directories].each do |dir, dir_data| output += " Directory: #{dir}\n Top files:\n" dir_data[:files].each do |file_data| next if converted_team_map[File.basename(file_data[:name])].nil? contributors = converted_team_map[file_data[:name]]&.first&.empty? ? ['Excluded contributor'] : converted_team_map[file_data[:name]].first output += " #{File.basename(file_data[:name])} - #{file_data[:count].last} #{contributors}}\n" end end end if FILE_OUTPUT File.open('codeowners.txt', 'w') do |f| f.puts output end else puts output end end |
#hotspot_check(files:, branch:) ⇒ Object
421 422 423 424 425 426 427 428 429 430 431 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 421 def hotspot_check(files:, branch:) duration_in_days = @duration_in_days.to_i start_date = @begin_time.to_time.to_i - duration_in_days * 86_400 end_date = @begin_time.to_time.to_i resulting_files = analyze_changed_files( uniq_code_files_with_changes: files, start_date:, end_date:, branch: ).last resulting_files.filter { |f| resulting_files[f].first.count > 1 }.keys end |
#new_changes?(file:) ⇒ Boolean
198 199 200 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 198 def new_changes?(file:) git_commit_info(file:, start_date: DateTime.now - 7, end_date: DateTime.now) != '' end |
#read_codeowners_file ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 20 def read_codeowners_file raise "CODEOWNERS file does not exist under #{CODEOWNERS_PATH}" unless File.exist?(CODEOWNERS_PATH) codeowners = {} File.readlines(CODEOWNERS_PATH).each do |line| next if line.strip.empty? || line.start_with?('#') # Skip comments and empty lines parts = line.split(/\s+/) directory_pattern = parts[0] owner = parts[1..].map { |o| o.start_with?('@') ? o[1..] : o }.join(' ') # Remove leading '@' from team names codeowners[directory_pattern] = owner end codeowners end |
#true?(obj) ⇒ Boolean
16 17 18 |
# File 'lib/github_repo_statistics/github_repo_statistics.rb', line 16 def true?(obj) obj.to_s.downcase == 'true' end |