gitalytics 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'gitalytics/cli_text'
4
+
5
+ module Gitalytics
6
+ # The plain-text summary printed by default: repository totals, the period
7
+ # covered and a table of the top authors. Colors are used only when writing
8
+ # to a terminal and NO_COLOR is not set.
9
+ class CliReport
10
+ DEFAULT_TOP = 10
11
+ DEFAULT_WIDTH = 80
12
+ MIN_WIDTH = 60
13
+ MAX_WIDTH = 120
14
+ include CliText
15
+
16
+ def self.color?(io, env = ENV)
17
+ return false if env.key?('NO_COLOR') && !env['NO_COLOR'].empty?
18
+ return false if env['TERM'] == 'dumb'
19
+
20
+ io.respond_to?(:tty?) && io.tty?
21
+ end
22
+
23
+ def self.width_for(io)
24
+ cols = io.winsize[1] if io.respond_to?(:winsize) && io.tty?
25
+ cols = ENV['COLUMNS'].to_i if cols.to_i.zero?
26
+ cols.to_i.zero? ? DEFAULT_WIDTH : cols
27
+ rescue StandardError
28
+ DEFAULT_WIDTH
29
+ end
30
+
31
+ def initialize(report, color: false, width: DEFAULT_WIDTH, top: DEFAULT_TOP)
32
+ @report = report
33
+ @color = color
34
+ @width = width.to_i.clamp(MIN_WIDTH, MAX_WIDTH)
35
+ @top = top.to_i.positive? ? top.to_i : report.users.size
36
+ end
37
+
38
+ def render
39
+ return "No commits found.\n" if @report.empty?
40
+
41
+ (header + [''] + overview + [''] + authors_table).join("\n") << "\n"
42
+ end
43
+
44
+ private
45
+
46
+ attr_reader :report
47
+
48
+ # ---- Sections -----------------------------------------------------------
49
+
50
+ def header
51
+ r = report
52
+ title = "#{paint(r.repo_name, :bold)} #{r.plural(r.commits.size, 'commit')} by " \
53
+ "#{r.plural(r.users.size, 'author')}"
54
+ period = "#{r.fmt_date(r.first_commit.date)} to #{r.fmt_date(r.last_commit.date)} " \
55
+ "(#{r.plural(r.span_days, 'day')})"
56
+ [title, paint(period, :dim)]
57
+ end
58
+
59
+ def overview
60
+ r = report
61
+ busiest_date, busiest = r.busiest_day
62
+ left = [
63
+ ['Lines', "#{paint("+#{r.num(r.total_insertions)}", :green)} #{paint("-#{r.num(r.total_deletions)}", :red)}"],
64
+ ['Files touched', r.num(r.files_touched)],
65
+ ['Active days', "#{r.num(r.active_days)} of #{r.num(r.span_days)}"]
66
+ ]
67
+ right = [
68
+ ['Longest streak', r.plural(r.longest_streak, 'day')],
69
+ ['Busiest day', "#{r.fmt_date(busiest_date)} (#{r.plural(busiest.size, 'commit')})"],
70
+ ['Commits/day', format('%.1f', r.commits.size.to_f / r.active_days)]
71
+ ]
72
+ two_columns(left, right)
73
+ end
74
+
75
+ # Two label/value columns side by side, or one stacked list when narrow.
76
+ def two_columns(left, right)
77
+ left_cells = label_list(left)
78
+ right_cells = label_list(right)
79
+ col = widest(left_cells) + 4
80
+ return label_list(left + right).map { |c| " #{c}" } if 2 + col + widest(right_cells) > @width
81
+
82
+ left_cells.zip(right_cells).map { |l, r| " #{pad(l, col)}#{r}" }
83
+ end
84
+
85
+ def widest(cells)
86
+ cells.map { |c| visible_length(c) }.max
87
+ end
88
+
89
+ def label_list(pairs)
90
+ lw = pairs.map { |l, _| l.length }.max
91
+ pairs.map { |label, value| "#{paint(label.ljust(lw), :dim)} #{value}" }
92
+ end
93
+
94
+ def authors_table
95
+ cols = columns
96
+ lines = [paint(" #{cols.map { |c| align(c[:title], c) }.join(' ')}".rstrip, :bold)]
97
+ shown_users.each_index do |i|
98
+ lines << " #{cols.map { |c| align(c[:cells][i], c) }.join(' ')}".rstrip
99
+ end
100
+ rest = report.users.size - shown_users.size
101
+ return lines unless rest.positive?
102
+
103
+ lines << paint(" ... and #{report.plural(rest, 'more author')} (use --top 0 to list everyone)", :dim)
104
+ end
105
+
106
+ # ---- Author table columns ---------------------------------------------
107
+
108
+ def columns
109
+ cols = [
110
+ col('Author', :left) { |u| u.name.to_s },
111
+ col('Commits', :right) { |u| report.num(u.commits.size) },
112
+ col('Share', :right) { |u| format('%.1f%%', report.share(u)) },
113
+ col('', :left, priority: 4) { |u| paint(bar(report.share(u)), :cyan) },
114
+ col('Added', :right, priority: 3) { |u| paint("+#{report.num(u.total_insertions)}", :green) },
115
+ col('Deleted', :right, priority: 3) { |u| paint("-#{report.num(u.total_deletions)}", :red) },
116
+ col('Days', :right, priority: 1) { |u| report.num(u.working_days) },
117
+ col('Last commit', :left, priority: 2) { |u| u.last_commit.date.to_s }
118
+ ]
119
+ fit(cols)
120
+ end
121
+
122
+ def col(title, side, priority: 9, &value)
123
+ { title: title, side: side, priority: priority, value: value }
124
+ end
125
+
126
+ def shown_users
127
+ @shown_users ||= report.users.first(@top)
128
+ end
129
+
130
+ # Size every column to its content, then drop the least important ones
131
+ # until the author name has room.
132
+ def fit(cols)
133
+ cols.each { |c| measure(c) }
134
+ author = cols.first
135
+ name_needed = author[:width].clamp(6, 28)
136
+ loop do
137
+ lowest = cols.map { |c| c[:priority] }.select { |p| p < 9 }.min
138
+ break if name_room(cols) >= name_needed || lowest.nil?
139
+
140
+ cols.reject! { |c| c[:priority] == lowest }
141
+ end
142
+ author[:width] = name_room(cols).clamp(6, name_needed)
143
+ cols
144
+ end
145
+
146
+ def name_room(cols)
147
+ @width - 2 - cols.drop(1).sum { |c| c[:width] + 2 }
148
+ end
149
+
150
+ def measure(column)
151
+ column[:cells] = shown_users.map { |u| column[:value].call(u) }
152
+ column[:width] = column[:cells].map { |t| visible_length(t) }.push(column[:title].length).max
153
+ end
154
+
155
+ def align(text, column)
156
+ text = truncate(text, column[:width])
157
+ column[:side] == :right ? pad(text, column[:width], left: true) : pad(text, column[:width])
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gitalytics
4
+ # Width-aware text helpers for the terminal summary. Expects @color.
5
+ module CliText
6
+ BAR_WIDTH = 10
7
+ BLOCKS = [' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'].freeze
8
+ STYLES = { bold: 1, dim: 2, green: 32, red: 31, cyan: 36 }.freeze
9
+
10
+ private
11
+
12
+ def bar(percent)
13
+ eighths = (percent / 100.0 * BAR_WIDTH * 8).round
14
+ eighths = 1 if eighths.zero? && percent.positive?
15
+ full, part = eighths.divmod(8)
16
+ (('█' * full) + (part.positive? ? BLOCKS[part] : '')).ljust(BAR_WIDTH)
17
+ end
18
+
19
+ def truncate(text, width)
20
+ return text if visible_length(text) <= width
21
+
22
+ "#{text[0, width - 1]}…"
23
+ end
24
+
25
+ def pad(text, width, left: false)
26
+ spaces = ' ' * [width - visible_length(text), 0].max
27
+ left ? spaces + text : text + spaces
28
+ end
29
+
30
+ def visible_length(text)
31
+ text.gsub(/\e\[[\d;]*m/, '').length
32
+ end
33
+
34
+ def paint(text, style)
35
+ return text unless @color
36
+
37
+ "\e[#{STYLES.fetch(style)}m#{text}\e[0m"
38
+ end
39
+ end
40
+ end
@@ -1,22 +1,22 @@
1
- class Commit
1
+ # frozen_string_literal: true
2
2
 
3
- attr_accessor :hash, :author, :date, :subject, :summary
3
+ class Commit
4
+ attr_accessor :sha, :author, :author_name, :author_email, :date, :time, :subject, :summary
4
5
 
5
- def initialize(hash)
6
- self.hash = hash
6
+ def initialize(sha)
7
+ self.sha = sha
7
8
  self.summary = []
8
9
  end
9
10
 
10
11
  def insertions
11
- summary.inject(0) { |total, current| total + current[:insertions] }
12
+ summary.sum { |s| s[:insertions] }
12
13
  end
13
14
 
14
15
  def deletions
15
- summary.inject(0) { |total, current| total + current[:deletions] }
16
+ summary.sum { |s| s[:deletions] }
16
17
  end
17
18
 
18
19
  def files_committed
19
- summary.map{ |s| s[:filename] }
20
+ summary.map { |s| s[:filename] }
20
21
  end
21
-
22
22
  end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gitalytics
4
+ # Raised when `git log` fails (not a repository, git missing, ...).
5
+ class GitError < StandardError; end
6
+ end
@@ -1,81 +1,140 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'gitalytics/commit'
4
+ require 'gitalytics/git_error'
2
5
  require 'gitalytics/user'
3
6
  require 'date'
4
-
7
+ require 'open3'
8
+ require 'time'
9
+
10
+ # Runs `git log` and turns its output into Commit and User objects.
11
+ #
12
+ # The log is requested with `-z` and ASCII control characters as separators,
13
+ # so author names, subjects and file names (spaces, quotes, non-ASCII, `=>`)
14
+ # never collide with the format. Records are parsed as they stream in, so big
15
+ # histories are never held in memory as a single string.
5
16
  module GitLog
6
-
7
17
  module_function
8
18
 
9
- def parse_git_log(group_by)
10
- users, commits = [], []
11
-
12
- log = get_log
13
- blocks = get_blocks(log)
14
-
15
- blocks.each do |(hash, block_string)|
16
- commits << parse_block(hash, block_string, users, group_by)
19
+ RECORD_SEP = "\x1e"
20
+ FIELD_SEP = "\x1f"
21
+ # Author fields use %aN/%aE so .mailmap is respected; %aI is strict ISO 8601.
22
+ PRETTY = "--pretty=format:#{RECORD_SEP}%H#{FIELD_SEP}%aI#{FIELD_SEP}%aN#{FIELD_SEP}%aE#{FIELD_SEP}%s".freeze
23
+ EMPTY_REPO = /does not have any commits yet|bad default revision 'HEAD'/
24
+
25
+ def parse_git_log(group_by = 'name', since: nil, until_date: nil, no_merges: false)
26
+ cmd = git_log_command(since: since, until_date: until_date, no_merges: no_merges)
27
+ Open3.popen3(*cmd) do |stdin, stdout, stderr, wait|
28
+ stdin.close
29
+ errors = Thread.new { stderr.read }
30
+ data = parse(stdout.each_line(RECORD_SEP), group_by)
31
+ status = wait.value
32
+ check_status!(status, errors.value)
33
+ data
17
34
  end
18
-
19
- {users: users, commits: commits}
35
+ rescue Errno::ENOENT
36
+ raise Gitalytics::GitError, 'git executable not found in PATH'
20
37
  end
21
38
 
22
- def get_log
23
- `git log --numstat --pretty='%H %ai %an <%ae> %s'`
39
+ def git_log_command(since: nil, until_date: nil, no_merges: false)
40
+ cmd = ['git', '-c', 'core.quotePath=false', 'log', '--numstat', '-z', PRETTY]
41
+ cmd << '--no-merges' if no_merges
42
+ cmd << "--since=#{since}" if since
43
+ cmd << "--until=#{until_date}" if until_date
44
+ cmd
24
45
  end
25
46
 
26
- def get_blocks(log_string)
27
- commits = log_string.scan(/^([a-f0-9]{40})/).map(&:first)
28
- blocks = log_string.split(/^[a-f0-9]{40}/).map(&:strip)
29
- blocks.shift # get rid of first empty string
47
+ def check_status!(status, error_output)
48
+ return if status.success?
49
+ return if error_output.match?(EMPTY_REPO)
30
50
 
31
- commits.zip(blocks)
51
+ message = error_output.strip.sub(/\Afatal:\s*/, '')
52
+ raise Gitalytics::GitError, message.empty? ? "git log exited with status #{status.exitstatus}" : message
32
53
  end
33
54
 
34
- def parse_block(hash, block_string, users, group_by)
35
- commit = Commit.new(hash)
36
-
37
- block_string.encode!('UTF-8', 'UTF8-MAC') if defined?(Encoding::UTF8_MAC)
38
-
39
- regex = /^(?<date>.{25}) (?<name>.*?) \<(?<email>.*?)> (?<subject>.*?)$/
40
- data = block_string.match(regex)
41
- commit.subject = data[:subject]
42
- commit.date = Date.parse(data[:date])
55
+ # Parses an enumerable of raw records (as produced by `git_log_command`).
56
+ # Returns { users: [User], commits: [Commit] }, commits newest first.
57
+ def parse(records, group_by = 'name')
58
+ users = {}
59
+ commits = []
60
+ renames = {}
61
+
62
+ records.each do |record|
63
+ record = clean(record.chomp(RECORD_SEP))
64
+ next if record.empty?
65
+
66
+ commit = parse_record(record, renames)
67
+ next unless commit
68
+
69
+ key = user_key(commit, group_by)
70
+ user = users[key] ||= User.new(commit.author_name, commit.author_email)
71
+ commit.author = user
72
+ user.commits << commit
73
+ commits << commit
74
+ end
43
75
 
44
- get_commit_author(data, commit, users, group_by)
45
- get_commit_summary(block_string, commit)
76
+ { users: users.values, commits: commits }
77
+ end
46
78
 
79
+ # A record is "<header>\n<numstat entries>" where every numstat entry ends in
80
+ # NUL. A commit without file changes (e.g. a merge) is "<header>\0".
81
+ def parse_record(record, renames)
82
+ header, stats = record.split(/[\n\0]/, 2)
83
+ sha, date, name, email, subject = header.split(FIELD_SEP, 5)
84
+ return unless sha && date
85
+
86
+ commit = Commit.new(sha)
87
+ commit.author_name = name.to_s
88
+ commit.author_email = email.to_s
89
+ commit.subject = subject.to_s
90
+ commit.time = Time.iso8601(date)
91
+ commit.date = commit.time.to_date
92
+ parse_numstat(stats.to_s, commit, renames)
47
93
  commit
48
94
  end
49
95
 
50
- def get_commit_summary(block_string, commit)
51
- block_string.scan(/^(?<insertions>\d+)\s+(?<deletions>\d+)\s+(?<filename>.*)$/).each do |summary|
96
+ # Entries look like "12\t3\tpath" or, for renames and copies,
97
+ # "12\t3\t" followed by two more NUL-terminated fields (old and new path).
98
+ # Binary files report "-" instead of line counts.
99
+ #
100
+ # git log lists newest commits first, so when a rename shows up every older
101
+ # entry for the old path belongs to the same file: `renames` maps old paths
102
+ # to the file's current name, keeping per-file stats together.
103
+ def parse_numstat(stats, commit, renames)
104
+ fields = stats.split("\0")
105
+ until fields.empty?
106
+ insertions, deletions, path = fields.shift.split("\t", 3)
107
+ next unless deletions
108
+
109
+ path = read_rename(fields, renames) if path.to_s.empty?
110
+ next unless path
111
+
52
112
  commit.summary << {
53
- insertions: summary[0].to_i,
54
- deletions: summary[1].to_i,
55
- filename: summary[2],
113
+ insertions: insertions.to_i,
114
+ deletions: deletions.to_i,
115
+ filename: renames.fetch(path, path),
116
+ binary: insertions == '-'
56
117
  }
57
118
  end
58
119
  end
59
120
 
60
- def get_commit_author(data, commit, users, group_by)
61
- user = get_user(data[:name], data[:email], users, group_by)
62
-
63
- commit.author = user
64
- user.commits << commit
121
+ # Consumes the old/new path pair of a rename entry and returns the new path.
122
+ def read_rename(fields, renames)
123
+ old_path = fields.shift
124
+ new_path = fields.shift
125
+ renames[old_path] = renames.fetch(new_path, new_path) if old_path && new_path && old_path != new_path
126
+ new_path
65
127
  end
66
128
 
67
- def get_user(name, email, users, group_by)
68
- if group_by == 'name'
69
- users.each do |user|
70
- return user if user.name == name
71
- end
72
- elsif group_by == 'email'
73
- users.each do |user|
74
- return user if user.email == email
75
- end
76
- end
77
- users << new_user = User.new(name, email)
78
- new_user
129
+ def user_key(commit, group_by)
130
+ group_by == 'email' ? commit.author_email.downcase : commit.author_name
79
131
  end
80
132
 
133
+ # git emits whatever bytes are stored in the commit; older repositories
134
+ # often contain Latin-1 names and messages. Never let that crash parsing.
135
+ def clean(string)
136
+ string = string.dup.force_encoding(Encoding::UTF_8)
137
+ string = string.scrub('?') unless string.valid_encoding?
138
+ string.ascii_only? ? string : string.unicode_normalize(:nfc)
139
+ end
81
140
  end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Gitalytics
6
+ # Machine-readable summary of the same data the HTML report shows.
7
+ class JsonReport
8
+ def initialize(report)
9
+ @report = report
10
+ end
11
+
12
+ def to_h
13
+ r = @report
14
+ return { repository: r.repo_name, commits: 0, authors: [] } if r.empty?
15
+
16
+ {
17
+ repository: r.repo_name,
18
+ generated_at: r.generated_at.iso8601,
19
+ first_commit: r.first_commit.time.iso8601,
20
+ last_commit: r.last_commit.time.iso8601,
21
+ commits: r.commits.size,
22
+ insertions: r.total_insertions,
23
+ deletions: r.total_deletions,
24
+ files_touched: r.files_touched,
25
+ active_days: r.active_days,
26
+ longest_streak: r.longest_streak,
27
+ authors: r.users.map { |u| author(u) },
28
+ weekdays: %w[mon tue wed thu fri sat sun].zip(r.weekday_totals).to_h,
29
+ top_files: r.top_files.map { |name, stats| { path: name, **stats } },
30
+ top_directories: r.top_directories.map { |dir, lines| { path: dir, lines: lines } }
31
+ }
32
+ end
33
+
34
+ def render
35
+ JSON.pretty_generate(to_h)
36
+ end
37
+
38
+ private
39
+
40
+ def author(user)
41
+ {
42
+ name: user.name,
43
+ email: user.email,
44
+ commits: user.commits.size,
45
+ share: @report.share(user).round(2),
46
+ insertions: user.total_insertions,
47
+ deletions: user.total_deletions,
48
+ active_days: user.working_days,
49
+ first_commit: user.first_commit.time.iso8601,
50
+ last_commit: user.last_commit.time.iso8601
51
+ }
52
+ end
53
+ end
54
+ end