-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
380 lines (328 loc) · 14 KB
/
Copy pathmain.go
File metadata and controls
380 lines (328 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
101
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
175
176
177
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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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
package main
import (
"fmt"
"os"
"os/exec"
"runtime"
"sort"
"strings"
"time"
"github.com/spf13/pflag"
"git-metrics/pkg/display/sections"
"git-metrics/pkg/git"
"git-metrics/pkg/models"
"git-metrics/pkg/progress"
"git-metrics/pkg/requirements"
"git-metrics/pkg/utils"
)
var debug bool
const (
UnknownValue = "Unknown"
)
func main() {
startTime := time.Now()
// Define flags with pflag for better help formatting
repositoryPath := pflag.StringP("repository", "r", ".", "Path to git repository")
showVersion := pflag.Bool("version", false, "Display version information and exit")
pflag.BoolVar(&debug, "debug", false, "Enable debug output")
noProgress := pflag.Bool("no-progress", false, "Disable progress indicators")
showHelp := pflag.BoolP("help", "h", false, "Display this help message")
pflag.Parse()
// Show help and exit if help flag is set
if *showHelp {
pflag.Usage()
os.Exit(0)
}
// Show version and exit if version flag is set
if *showVersion {
fmt.Printf("git-metrics version %s\n", utils.GetGitMetricsVersion())
os.Exit(0)
}
// Set progress visibility based on --no-progress flag and output destination
// Automatically disable progress when output is piped to a file or redirected
progress.ShowProgress = !*noProgress && utils.IsTerminal(os.Stdout)
if !requirements.CheckRequirements() {
fmt.Println("\nRequirements not met. Please install listed dependencies above.")
os.Exit(9)
}
// Get Git directory and change to repository directory
gitDir, err := git.GetGitDirectory(*repositoryPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
if err := os.Chdir(*repositoryPath); err != nil {
fmt.Fprintf(os.Stderr, "Error: could not change to repository directory: %v\n", err)
os.Exit(1)
}
sections.DisplayRunInformation()
fmt.Println("\nREPOSITORY #############################################################################################################")
fmt.Println()
// Get Git directory last modified time
lastModified := UnknownValue
if info, err := os.Stat(gitDir); err == nil {
lastModified = info.ModTime().Format("Mon, 02 Jan 2006 15:04 MST")
}
fmt.Printf("Git directory %s\n", gitDir)
// Remote URL - only show if there is one
remoteOutput, err := git.RunGitCommand(debug, "remote", "get-url", "origin")
remote := ""
if err == nil && len(strings.TrimSpace(string(remoteOutput))) > 0 {
if progress.ShowProgress {
fmt.Printf("Remote ... fetching\n")
}
remote = strings.TrimSpace(string(remoteOutput))
if progress.ShowProgress {
fmt.Printf("\033[1A\033[2KRemote %s\n", remote)
} else {
fmt.Printf("Remote %s\n", remote)
}
}
// Get fetch time and show last modified only if there's no recent fetch
recentFetch := git.GetLastFetchTime(gitDir)
if recentFetch == "" {
fmt.Printf("Last modified %s\n", lastModified)
}
if recentFetch != "" {
fmt.Printf("Most recent fetch %s\n", recentFetch)
}
// Most recent commit
if progress.ShowProgress {
fmt.Printf("Most recent commit ... fetching\n")
}
lastHashOutput, err := git.RunGitCommand(debug, "rev-parse", "--short", "HEAD")
lastCommit := UnknownValue
if err == nil {
lastHash := strings.TrimSpace(string(lastHashOutput))
dateCommand := exec.Command("git", "show", "-s", "--format=%cD", lastHash)
commandOutput, err := dateCommand.Output()
if err == nil {
lastDate, _ := time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", strings.TrimSpace(string(commandOutput)))
lastCommit = fmt.Sprintf("%s (%s)", lastDate.Format("Mon, 02 Jan 2006"), lastHash)
}
}
if progress.ShowProgress {
fmt.Printf("\033[1A\033[2KMost recent commit %s\n", lastCommit)
} else {
fmt.Printf("Most recent commit %s\n", lastCommit)
}
// First commit and age
if progress.ShowProgress {
fmt.Printf("First commit ... fetching\n")
}
firstOutput, err := git.RunGitCommand(debug, "rev-list", "--max-parents=0", "HEAD", "--format=%cD")
firstCommit := UnknownValue
ageString := UnknownValue
var firstCommitTime time.Time
if err == nil {
lines := strings.Split(strings.TrimSpace(string(firstOutput)), "\n")
type commit struct {
hash string
date time.Time
}
var commits []commit
for i := 0; i < len(lines); i += 2 {
if i+1 >= len(lines) {
break
}
hash := strings.TrimPrefix(lines[i], "commit ")[:6]
if date, err := time.Parse("Mon, 2 Jan 2006 15:04:05 -0700", strings.TrimSpace(lines[i+1])); err == nil {
commits = append(commits, commit{hash: hash, date: date})
}
}
if len(commits) > 0 {
sort.Slice(commits, func(i, j int) bool {
return commits[i].date.Before(commits[j].date)
})
first := commits[0]
firstCommitTime = first.date
firstCommit = fmt.Sprintf("%s (%s)", first.date.Format("Mon, 02 Jan 2006"), first.hash)
now := time.Now()
years, months, days := utils.CalculateYearsMonthsDays(first.date, now)
var parts []string
if years > 0 {
parts = append(parts, fmt.Sprintf("%d years", years))
}
if months > 0 {
parts = append(parts, fmt.Sprintf("%d months", months))
}
if days > 0 {
parts = append(parts, fmt.Sprintf("%d days", days))
}
ageString = strings.Join(parts, " ")
}
}
if progress.ShowProgress {
fmt.Printf("\033[1A\033[2KFirst commit %s\n", firstCommit)
} else {
fmt.Printf("First commit %s\n", firstCommit)
}
// If there are no commits, exit early
if firstCommit == UnknownValue {
fmt.Println("\n\nNo commits found in the repository.")
os.Exit(2)
}
fmt.Printf("Age %s\n", ageString)
// Display the section header before data collection
fmt.Println()
fmt.Println("HISTORIC & ESTIMATED GROWTH ############################################################################################")
fmt.Println()
// Print table headers before data collection (Year widened to 6 for ^* marker)
fmt.Println("Year Commits Δ % ○ Object size Δ % ○ On-disk size Δ % ○")
fmt.Println("------------------------------------------------------------------------------------------------------------------------")
// Calculate growth stats and totals
var previous models.GrowthStatistics
var totalStatistics models.GrowthStatistics
yearlyStatistics := make(map[int]models.GrowthStatistics)
// Start calculation with progress indicator (no newline before progress)
var beforePrevious models.GrowthStatistics
for year := firstCommitTime.Year(); year <= time.Now().Year(); year++ {
progress.StartProgress(year, previous, beforePrevious, startTime) // Start progress updates
if cumulativeStatistics, err := git.GetGrowthStats(year, previous, debug); err == nil {
totalStatistics = cumulativeStatistics
beforePrevious = previous
previous = cumulativeStatistics
yearlyStatistics[year] = cumulativeStatistics
progress.SetCurrentProgressStatistics(cumulativeStatistics, beforePrevious)
}
}
progress.StopProgress() // Stop and clear progress line
// Start section spinner while computing author data and growth statistics
progress.StartSectionSpinner()
// Compute cumulative unique authors per year for historic growth
cumulativeAuthorsByYear, totalAuthors, authorsErr := git.GetCumulativeUniqueAuthorsByYear()
if authorsErr == nil {
// Inject authors into yearly statistics
for year, stats := range yearlyStatistics {
if authorsCount, ok := cumulativeAuthorsByYear[year]; ok {
stats.Authors = authorsCount
yearlyStatistics[year] = stats
}
}
}
// Save repository information with totals (including authors)
repositoryInformation := models.RepositoryInformation{
Remote: remote,
LastCommit: lastCommit,
FirstCommit: firstCommit,
Age: ageString,
FirstDate: firstCommitTime,
TotalCommits: totalStatistics.Commits,
TotalAuthors: totalAuthors,
TotalTrees: totalStatistics.Trees,
TotalBlobs: totalStatistics.Blobs,
CompressedSize: totalStatistics.Compressed,
UncompressedSize: totalStatistics.Uncompressed,
}
// Calculate and store delta, percentage, and delta percentage values
currentYear := time.Now().Year()
var previousCumulative models.GrowthStatistics
var previousDelta models.GrowthStatistics
// Process each year to calculate and store all derived values
for year := repositoryInformation.FirstDate.Year(); year <= currentYear; year++ {
if cumulative, ok := yearlyStatistics[year]; ok {
// Calculate delta values (year-over-year changes)
cumulative.AuthorsDelta = cumulative.Authors - previousCumulative.Authors
cumulative.CommitsDelta = cumulative.Commits - previousCumulative.Commits
cumulative.TreesDelta = cumulative.Trees - previousCumulative.Trees
cumulative.BlobsDelta = cumulative.Blobs - previousCumulative.Blobs
cumulative.CompressedDelta = cumulative.Compressed - previousCumulative.Compressed
cumulative.UncompressedDelta = cumulative.Uncompressed - previousCumulative.Uncompressed
// Calculate percentage of total
if repositoryInformation.TotalAuthors > 0 {
cumulative.AuthorsPercent = float64(cumulative.AuthorsDelta) / float64(repositoryInformation.TotalAuthors) * 100
}
if repositoryInformation.TotalCommits > 0 {
cumulative.CommitsPercent = float64(cumulative.CommitsDelta) / float64(repositoryInformation.TotalCommits) * 100
}
if repositoryInformation.TotalTrees > 0 {
cumulative.TreesPercent = float64(cumulative.TreesDelta) / float64(repositoryInformation.TotalTrees) * 100
}
if repositoryInformation.TotalBlobs > 0 {
cumulative.BlobsPercent = float64(cumulative.BlobsDelta) / float64(repositoryInformation.TotalBlobs) * 100
}
if repositoryInformation.CompressedSize > 0 {
cumulative.CompressedPercent = float64(cumulative.CompressedDelta) / float64(repositoryInformation.CompressedSize) * 100
}
if repositoryInformation.UncompressedSize > 0 {
cumulative.UncompressedPercent = float64(cumulative.UncompressedDelta) / float64(repositoryInformation.UncompressedSize) * 100
}
// Calculate delta percentage changes (Δ%)
if previousDelta.Year != 0 { // Skip first year
if previousDelta.AuthorsDelta > 0 {
cumulative.AuthorsDeltaPercent = float64(cumulative.AuthorsDelta-previousDelta.AuthorsDelta) / float64(previousDelta.AuthorsDelta) * 100
}
if previousDelta.CommitsDelta > 0 {
cumulative.CommitsDeltaPercent = float64(cumulative.CommitsDelta-previousDelta.CommitsDelta) / float64(previousDelta.CommitsDelta) * 100
}
if previousDelta.TreesDelta > 0 {
cumulative.TreesDeltaPercent = float64(cumulative.TreesDelta-previousDelta.TreesDelta) / float64(previousDelta.TreesDelta) * 100
}
if previousDelta.BlobsDelta > 0 {
cumulative.BlobsDeltaPercent = float64(cumulative.BlobsDelta-previousDelta.BlobsDelta) / float64(previousDelta.BlobsDelta) * 100
}
if previousDelta.CompressedDelta > 0 {
cumulative.CompressedDeltaPercent = float64(cumulative.CompressedDelta-previousDelta.CompressedDelta) / float64(previousDelta.CompressedDelta) * 100
}
if previousDelta.UncompressedDelta > 0 {
cumulative.UncompressedDeltaPercent = float64(cumulative.UncompressedDelta-previousDelta.UncompressedDelta) / float64(previousDelta.UncompressedDelta) * 100
}
}
// Store the updated statistics back in the map
yearlyStatistics[year] = cumulative
// Update for next iteration
previousCumulative = cumulative
previousDelta = cumulative
}
}
// Display unified historic and estimated growth using the new function
progress.StopSectionSpinner()
sections.DisplayUnifiedGrowth(yearlyStatistics, repositoryInformation, firstCommitTime, recentFetch, lastModified)
// 1. Largest file extensions
sections.PrintTopFileExtensions(previous.LargestFiles, repositoryInformation.TotalBlobs, repositoryInformation.CompressedSize)
// 2. Largest file extensions on-disk size growth
sections.PrintFileExtensionGrowth(yearlyStatistics)
// Prepare largest files data once for sections 3 & 4
largestFiles := totalStatistics.LargestFiles
sort.Slice(largestFiles, func(i, j int) bool {
if largestFiles[i].CompressedSize != largestFiles[j].CompressedSize {
return largestFiles[i].CompressedSize > largestFiles[j].CompressedSize
}
return largestFiles[i].Path < largestFiles[j].Path
})
var totalFilesCompressedSize int64
for _, file := range largestFiles {
totalFilesCompressedSize += file.CompressedSize
}
if len(largestFiles) > 10 {
largestFiles = largestFiles[:10]
}
// 3. Largest directories
sections.PrintLargestDirectories(totalStatistics.LargestFiles, repositoryInformation.TotalBlobs, repositoryInformation.CompressedSize)
// 4. Largest files
sections.PrintLargestFiles(largestFiles, totalFilesCompressedSize, repositoryInformation.TotalBlobs, len(previous.LargestFiles))
// 5. Rate of changes analysis
progress.StartSectionSpinner()
ratesByYear, branchName, rateError := git.GetRateOfChanges()
progress.StopSectionSpinner()
if rateError == nil && len(ratesByYear) > 0 {
sections.PrintRateOfChangesSectionTitle()
sections.DisplayRateOfChanges(ratesByYear, branchName)
}
// 6 & 7. Authors and committers with most commits
progress.StartSectionSpinner()
topAuthorsByYear, totalAuthorsByYear, totalCommitsByYear, topCommittersByYear, totalCommittersByYear, allTimeAuthors, allTimeCommitters, contributorsError := git.GetTopCommitAuthors(3)
progress.StopSectionSpinner()
if contributorsError == nil && len(topAuthorsByYear) > 0 {
sections.PrintAuthorsSectionTitle()
sections.DisplayAuthorsSection(topAuthorsByYear, totalAuthorsByYear, totalCommitsByYear, allTimeAuthors)
sections.PrintCommittersSectionTitle()
sections.DisplayCommittersSection(topCommittersByYear, totalCommittersByYear, totalCommitsByYear, allTimeCommitters)
}
// Get memory statistics for final output
var memoryStatistics runtime.MemStats
runtime.ReadMemStats(&memoryStatistics)
fmt.Printf("\nFinished in %s with a memory footprint of %s.\n",
utils.FormatDuration(time.Since(startTime)),
strings.TrimSpace(utils.FormatSize(int64(memoryStatistics.Sys))))
}