Class: GitCommitsAnalyzer
- Inherits:
-
Object
- Object
- GitCommitsAnalyzer
- Defined in:
- lib/git-commits-analyzer.rb
Overview
Public: parse git logs for language and commit metadata.
Examples:
git_parser = GitCommitsAnalyzer.new(logger: logger, author: )
Instance Attribute Summary collapse
-
#commit_days ⇒ Object
readonly
Public: Returns the tally of commits broken down by day.
-
#commit_hours ⇒ Object
readonly
Public: Returns the tally of commits broken down by hour of the day.
-
#commit_weekdays_hours ⇒ Object
readonly
Public: Returns the tally of commits broken down by weekday and hour.
-
#commits_by_month ⇒ Object
readonly
Public: Returns a hash of commit numbers broken down by month.
-
#commits_total ⇒ Object
readonly
Public: Returns the total number of commits belonging to the author specified.
-
#lines_by_language ⇒ Object
readonly
Public: Returns the number of lines added/removed broken down by language.
-
#lines_by_month ⇒ Object
readonly
Public: Returns the lines added/changed by month.
Class Method Summary collapse
-
.determine_language(filename:, sha:, git_repo:) ⇒ Object
Public: Determine the type of a file at the given revision of a repo.
-
.is_library(filename:) ⇒ Object
Public: Determine if the file is a common library that shouldn’t get counted towards contributions.
Instance Method Summary collapse
-
#get_month_scale ⇒ Object
Public: Get a range of months from the earliest commit to the latest.
-
#initialize(logger:, author:) ⇒ GitCommitsAnalyzer
constructor
Public: Initialize new GitParser object.
-
#parse_repo(repo:) ⇒ Object
Public: Parse the git logs for a repo.
-
#to_json(pretty: true) ⇒ Object
Public: Generate a JSON representation of the parsed data.
Constructor Details
#initialize(logger:, author:) ⇒ GitCommitsAnalyzer
Public: Initialize new GitParser object.
logger - A logger object to display git errors/warnings. author - The email of the git author for whom we should compile the metadata.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/git-commits-analyzer.rb', line 44 def initialize(logger:, author:) @logger = logger = @commits_by_month = {} @commits_by_month.default = 0 @commits_total = 0 @lines_by_language = {} @commit_hours = 0.upto(23).map{ |x| [x, 0] }.to_h @commit_days = {} @commit_days.default = 0 @commit_weekdays_hours = {} ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].each do |weekday| @commit_weekdays_hours[weekday] = {} 0.upto(23).each do |hour| @commit_weekdays_hours[weekday][hour] = 0 end end @lines_by_month = {} end |
Instance Attribute Details
#commit_days ⇒ Object (readonly)
Public: Returns the tally of commits broken down by day.
31 32 33 |
# File 'lib/git-commits-analyzer.rb', line 31 def commit_days @commit_days end |
#commit_hours ⇒ Object (readonly)
Public: Returns the tally of commits broken down by hour of the day.
28 29 30 |
# File 'lib/git-commits-analyzer.rb', line 28 def commit_hours @commit_hours end |
#commit_weekdays_hours ⇒ Object (readonly)
Public: Returns the tally of commits broken down by weekday and hour.
34 35 36 |
# File 'lib/git-commits-analyzer.rb', line 34 def commit_weekdays_hours @commit_weekdays_hours end |
#commits_by_month ⇒ Object (readonly)
Public: Returns a hash of commit numbers broken down by month.
18 19 20 |
# File 'lib/git-commits-analyzer.rb', line 18 def commits_by_month @commits_by_month end |
#commits_total ⇒ Object (readonly)
Public: Returns the total number of commits belonging to the author specified.
22 23 24 |
# File 'lib/git-commits-analyzer.rb', line 22 def commits_total @commits_total end |
#lines_by_language ⇒ Object (readonly)
Public: Returns the number of lines added/removed broken down by language.
25 26 27 |
# File 'lib/git-commits-analyzer.rb', line 25 def lines_by_language @lines_by_language end |
#lines_by_month ⇒ Object (readonly)
Public: Returns the lines added/changed by month.
37 38 39 |
# File 'lib/git-commits-analyzer.rb', line 37 def lines_by_month @lines_by_month end |
Class Method Details
.determine_language(filename:, sha:, git_repo:) ⇒ Object
Public: Determine the type of a file at the given revision of a repo.
filename - The name of the file to analyze. sha - The commit ID. git_repo - A git repo object corresponding to the underlying repo.
Returns a string corresponding to the language of the file.
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/git-commits-analyzer.rb', line 102 def self.determine_language(filename:, sha:, git_repo:) return nil if filename == 'LICENSE' # First try to match on known extensions. case filename when /\.go$/i return 'Go' when /\.(pl|pm|t|cgi|pod|run)$/i return 'Perl' when /\.(?:rb|gemspec)$/ return 'Ruby' when /(?:\/|^)Rakefile$/ return 'Ruby' when /\.md$/ return 'Markdown' when /\.json$/ return 'JSON' when /\.(yml|yaml)$/ return 'YAML' when /\.?(perlcriticrc|githooksrc|ini|editorconfig|gitconfig)$/ return 'INI' when /\.css$/ return 'CSS' when /\.(tt2|html)$/ return 'HTML' when /\.sql$/ return 'SQL' when /\.py$/ return 'Python' when /\.js$/ return 'JavaScript' when /\.c$/ return 'C' when /\.sh$/ return 'bash' when /(bash|bash_\w+)$/ return 'bash' when /\.?(SKIP|gitignore|txt|csv|vim|gitmodules|gitattributes|jshintrc|gperf|vimrc|psqlrc|inputrc|screenrc|curlrc|wgetrc|selected_editor|dmrc|netrc)$/ return 'Text' when /(?:\/|^)(?:LICENSE|LICENSE-\w+)$/ return nil when /\.(?:0|1|VimballRecord)$/ return nil when /^vim\/doc\/tags$/ return nil when /(?:\/|^)(?:README|MANIFEST|Changes|Gemfile|Gemfile.lock|CHANGELOG)$/ return 'Text' end # Next, retrieve the file content and infer from that. begin content = git_repo.show(sha, filename) rescue pp "#{$!}" end return nil if content == nil || content == '' first_line = content.split(/\n/)[0] || '' case first_line when /perl$/ return 'Perl' when /ruby$/ return 'Ruby' when /^\#!\/usr\/bin\/bash$/ return 'Ruby' end # Fall back on the extension in last resort. extension = /\.([^\.]+)$/.match(filename) return filename if extension.nil? return nil if extension[0] == 'lock' return extension[0] end |
.is_library(filename:) ⇒ Object
Public: Determine if the file is a common library that shouldn’t get counted towards contributions.
filename - The name of the file to analyze.
Returns a boolean indicating if the file is a common library.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/git-commits-analyzer.rb', line 71 def self.is_library(filename:) case filename when /jquery-ui-\d+\.\d+\.\d+\.custom(?:\.min)?\.js$/ return true when /jquery-\d+\.\d+\.\d+(?:\.min)?\.js$/ return true when /jquery\.datepick(?:\.min)?\.js$/ return true when /chart\.min\.js$/ return true when /jquery\.js$/ return true when /jquery-loader\.js$/ return true when /qunit\.js$/ return true when /d3\.v3(?:\.min)?\.js$/ return true else return false end end |
Instance Method Details
#get_month_scale ⇒ Object
Public: Get a range of months from the earliest commit to the latest.
Returns an array of “YYYY-MM” strings.
274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
# File 'lib/git-commits-analyzer.rb', line 274 def get_month_scale() month_scale = [] commits_start = @commits_by_month.keys.sort.first.split('-').map { |x| x.to_i } commits_end = @commits_by_month.keys.sort.last.split('-').map { |x| x.to_i } commits_start[0].upto(commits_end[0]) do |year| 1.upto(12) do |month| next if month < commits_start[1] && year == commits_start[0] next if month > commits_end[1] && year == commits_end[0] month_scale << [year, month] end end return month_scale end |
#parse_repo(repo:) ⇒ Object
Public: Parse the git logs for a repo.
repo - A git repo object corresponding to the underlying repo.
This method adds the metadata extracted for this repo to the instance variables collecting commit metadata.
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 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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
# File 'lib/git-commits-analyzer.rb', line 183 def parse_repo(repo:) # Support both standard and bare/mirror git repositories. git_repo = if File.directory?(File.join(repo, '.git')) then Git.open(repo, log: @logger) else Git.(repo, log: @logger) end # Note: override the default of 30 for count(), nil gives the whole git log # history. git_repo.log(count = nil).each do |commit| # Only include the authors specified on the command line. next if !.include?(commit..email) # Parse commit date and update the corresponding stats. commit_datetime = DateTime.parse(commit..date.to_s) commit_hour = commit_datetime.hour @commit_hours[commit_hour] += 1 commit_day = commit_datetime.strftime('%Y-%m-%d') @commit_days[commit_day] += 1 commit_weekday = commit_datetime.strftime('%a') @commit_weekdays_hours[commit_weekday][commit_hour] += 1 # Note: months are zero-padded to allow easy sorting, even if it's more # work for formatting later on. commit_month = commit.date.strftime("%Y-%m") # Parse diff and analyze patches to detect language. diff = git_repo.show(commit.sha) diff.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '') file_properties = git_repo.ls_tree(['-r', commit.sha]) languages_in_commit = {} patches = GitDiffParser.parse(diff) patches.each do |patch| # Skip submodules. next if file_properties['commit'].has_key?(patch.file); # Skip symlinks. next if file_properties['blob'].has_key?(patch.file) && (file_properties['blob'][patch.file][:mode] == '120000') # Skip libraries. next if self.class.is_library(filename: patch.file) body = patch.instance_variable_get :@body language = self.class.determine_language(filename: patch.file, sha: commit.sha, git_repo: git_repo) next if language.nil? @lines_by_language[language] ||= { 'added' => 0, 'deleted' => 0, 'commits' => 0, } languages_in_commit[language] = true @lines_by_month[commit_month] ||= { 'added' => 0, 'deleted' => 0, } body.split(/\n/).each do |content| if (/^[+-]/.match(content) && !/^[+-]\s+$/.match(content)) if (/^\+/.match(content)) @lines_by_language[language]['added'] += 1 @lines_by_month[commit_month]['added'] += 1 elsif (/^\-/.match(content)) @lines_by_language[language]['deleted'] += 1 @lines_by_month[commit_month]['deleted'] += 1 end end end end languages_in_commit.keys.each do |language| @lines_by_language[language]['commits'] += 1 end # Add to stats for monthly commit count. @commits_by_month[commit_month] += 1 # Add to stats for total commits count. @commits_total += 1 end end |
#to_json(pretty: true) ⇒ Object
Public: Generate a JSON representation of the parsed data.
Returns: a JSON string.
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 |
# File 'lib/git-commits-analyzer.rb', line 293 def to_json(pretty: true) formatted_commits_by_month = [] formatted_lines_by_month = [] month_names = Date::ABBR_MONTHNAMES self.get_month_scale.each do |frame| display_key = month_names[frame[1]] + '-' + frame[0].to_s data_key = sprintf('%s-%02d', frame[0], frame[1]) count = @commits_by_month[data_key] formatted_commits_by_month << { month: display_key, commits: count.to_i, } month_added_lines = 0 month_deleted_lines = 0 if @lines_by_month.key?(data_key) month_added_lines = @lines_by_month[data_key]['added'].to_i month_deleted_lines = @lines_by_month[data_key]['deleted'].to_i end formatted_lines_by_month << { month: display_key, added: month_added_lines, deleted: month_deleted_lines, } end data = { commits_total: @commits_total, commits_by_month: formatted_commits_by_month, commits_by_hour: @commit_hours, commits_by_day: @commit_days, commit_by_weekday_hour: @commit_weekdays_hours, lines_by_language: @lines_by_language, lines_by_month: formatted_lines_by_month, } if pretty JSON.pretty_generate(data) else JSON.generate(data) end end |