Debian Codegraph @

contrib/git-stats-graph.py

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: MIT
3 # Copyright (c) 2023 Bence Ferdinandy <[email protected]>
4
5 """
6 Create graphs about development statistics of releases.
7 """
8
9 from datetime import date
10 from subprocess import check_output
11
12 from matplotlib import pyplot as plt
13
14
15 def git(*args):
16 return check_output(["git"] + list(args)).decode("utf-8").strip()
17
18
19 def stats():
20 """
21 Returns statistics from the git repo:
22
23 tags: sorted list of minor version tags (assumes semver)
24 The first element is the hash of the first commit, last element is HEAD. All
25 the other return values are one shorter as, there's no statistics returned for
26 the first commit.
27 counts: number of commits (between this and the previous release)
28 dates: dates of the releases
29 files: number of files changed (between this and the previous release)
30 inserts: number of lines inserted (between this and the previous release)
31 deletions: number of lines deleted (between this and the previous release)
32 """
33
34 tags = git("tag").split("\n")
35 tags = [t for t in tags if t.split(".")[-1] == "0"] # drop patch versions
36 tags = sorted(tags, key=lambda x: [int(t) for t in x.split(".")])
37 first_commit = git("rev-list", "--max-parents=0", "HEAD")
38 tags = [first_commit] + tags + ["HEAD"]
39 counts = []
40 dates = []
41 files = []
42 inserts = []
43 deletions = []
44 for i, t in enumerate(tags[:-1]):
45 counts.append(int(git("rev-list", f"{t}..{tags[i+1]}", "--count")))
46 dates.append(
47 date.fromisoformat(
48 git("show", "-s", "--format=%cs", tags[i + 1]).split("\n")[-1]
49 )
50 )
51 statline = git("diff", "--stat", t, tags[i + 1]).split("\n")[-1]
52 fnum, _, _, ins, _, dels, _ = statline.split()
53 files.append(int(fnum))
54 inserts.append(int(ins))
55 deletions.append(int(dels))
56 return tags, counts, dates, files, inserts, deletions
57
58
59 def main(output):
60 tags, counts, dates, files, inserts, deletions = stats()
61
62 fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 11))
63 fig.suptitle("aerc release statistics", fontweight="bold")
64 # commit counts subplot
65 ax1.plot(dates, counts, "o-")
66
67 # alternate placement of text above and below for readability
68 text_y = []
69 for i, t in enumerate(tags[1:]):
70 downpad = 25 if len(t) == 5 else 30
71 p = counts[i] + (-1) ** (i + 1) * 10 - (i + 1) % 2 * downpad
72 if p < 5:
73 p = counts[i] + 10
74 text_y.append(p)
75 for i, t in enumerate(tags[1:]):
76 ax1.text(
77 dates[i],
78 text_y[i],
79 t,
80 horizontalalignment="center",
81 rotation="vertical",
82 )
83 ax1.set_ylabel("# of commits")
84 ax1.set_ylim(bottom=0)
85 ax1.set_title("commits per release")
86
87 # lines added/deleted subplot
88 #
89 ax2.plot(dates, inserts, "o-", label="insertions(+)", color="green")
90 ax2.plot(dates, deletions, "o-.", label="deletions(-)", color="red")
91 ax2.set_ylabel("# of lines")
92 ax2.legend(loc="upper left")
93 ax2.set_ylim(top=max(max(inserts), max(deletions)) + 2000)
94 for i, t in enumerate(tags[1:]):
95 ax2.text(
96 dates[i],
97 max(inserts[i], deletions[i]) + 500,
98 t,
99 horizontalalignment="center",
100 rotation="vertical",
101 )
102 ax2.set_xlabel("date")
103 ax2.set_title("insertion/deletions per release")
104 plt.tight_layout()
105 plt.savefig(output, dpi=300)
106
107
108 if __name__ == "__main__":
109 import argparse
110
111 parser = argparse.ArgumentParser(description=__doc__)
112 parser.add_argument(
113 "-o",
114 "--output",
115 default="aerc-release-stats.png",
116 help="""
117 Path to output image (defaults to 'aerc-release-stats.png',
118 respects file extensions via matplotlib)
119 """,
120 )
121 args = parser.parse_args()
122 main(args.output)