-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.go
More file actions
520 lines (451 loc) · 13.6 KB
/
app.go
File metadata and controls
520 lines (451 loc) · 13.6 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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
_ "modernc.org/sqlite"
"git-analytics/internal/config"
"git-analytics/internal/git"
"git-analytics/internal/indexer"
"git-analytics/internal/query"
"git-analytics/internal/store"
sqlitestore "git-analytics/internal/store/sqlite"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// App struct
type App struct {
ctx context.Context
repo git.Repository
store store.Store
db *sql.DB
configDir string
version string
}
// NewApp creates a new App application struct
func NewApp(version string) *App {
return &App{version: version}
}
// Version returns the application version string.
func (a *App) Version() string {
return a.version
}
// OpenURL opens the given URL in the user's default browser.
func (a *App) OpenURL(url string) {
runtime.BrowserOpenURL(a.ctx, url)
}
// UpdateInfo holds information about an available update.
type UpdateInfo struct {
Available bool `json:"available"`
Tag string `json:"tag"`
URL string `json:"url"`
}
// CheckForUpdate queries GitHub for the latest release and returns update
// info if a newer version is available. Returns Available=false on any error
// or if already up to date.
func (a *App) CheckForUpdate() UpdateInfo {
if a.version == "dev" {
return UpdateInfo{}
}
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", "https://api.github.com/repos/tbrittain/git-analytics/releases/latest", nil)
if err != nil {
return UpdateInfo{}
}
req.Header.Set("User-Agent", "git-analytics/"+a.version)
resp, err := client.Do(req)
if err != nil {
return UpdateInfo{}
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return UpdateInfo{}
}
var release struct {
TagName string `json:"tag_name"`
HTMLURL string `json:"html_url"`
}
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return UpdateInfo{}
}
if release.TagName == "" || release.TagName == a.version {
return UpdateInfo{}
}
return UpdateInfo{
Available: true,
Tag: release.TagName,
URL: release.HTMLURL,
}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
if dir, err := config.DefaultConfigDir(); err == nil {
a.configDir = dir
}
}
// shutdown is called when the app is closing.
func (a *App) shutdown(ctx context.Context) {
if a.repo != nil {
a.repo.Close()
}
if a.store != nil {
a.store.Close()
}
if a.db != nil {
a.db.Close()
}
}
// OpenRepository opens a git repository at the given path, initializes the
// analytics database, and runs the indexer.
func (a *App) OpenRepository(path string) error {
// Close any previously opened resources.
if a.repo != nil {
a.repo.Close()
a.repo = nil
}
if a.store != nil {
a.store.Close()
a.store = nil
}
if a.db != nil {
a.db.Close()
a.db = nil
}
repo, err := git.NativeOpen(path)
if err != nil {
return fmt.Errorf("opening repository: %w", err)
}
dbPath := filepath.Join(path, ".git-analytics.db")
db, err := sql.Open("sqlite", dbPath)
if err != nil {
repo.Close()
return fmt.Errorf("opening database: %w", err)
}
if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil {
repo.Close()
db.Close()
return fmt.Errorf("setting WAL mode: %w", err)
}
s := sqlitestore.NewFromDB(db)
if err := s.Init(); err != nil {
repo.Close()
db.Close()
return fmt.Errorf("initializing schema: %w", err)
}
if err := addToGitExclude(path, ".git-analytics.db"); err != nil {
repo.Close()
db.Close()
return fmt.Errorf("updating git exclude: %w", err)
}
a.repo = repo
a.store = s
a.db = db
idx := indexer.New(repo, s)
if err := idx.Index(); err != nil {
return fmt.Errorf("indexing: %w", err)
}
// Persist this repo in the recent list.
if a.configDir != "" {
cfg, _ := config.Load(a.configDir)
cfg.AddRecent(path, repo.RepoName())
_ = cfg.Save(a.configDir)
}
return nil
}
// RecentRepos returns the list of recently opened repositories.
func (a *App) RecentRepos() ([]config.RecentRepo, error) {
if a.configDir == "" {
return nil, fmt.Errorf("config directory unavailable")
}
cfg, err := config.Load(a.configDir)
if err != nil {
return nil, err
}
// Filter out repos whose paths no longer exist on disk.
valid := make([]config.RecentRepo, 0, len(cfg.RecentRepos))
for _, r := range cfg.RecentRepos {
if _, err := os.Stat(r.Path); err == nil {
valid = append(valid, r)
}
}
return valid, nil
}
// RemoveRecentRepo removes a repository from the recent list.
func (a *App) RemoveRecentRepo(path string) error {
if a.configDir == "" {
return fmt.Errorf("config directory unavailable")
}
cfg, err := config.Load(a.configDir)
if err != nil {
return err
}
cfg.RemoveRecent(path)
return cfg.Save(a.configDir)
}
// CommitHeatmap returns per-day commit counts between the given dates.
// Dates should be in "2006-01-02" format. An empty email returns counts for
// all authors.
func (a *App) CommitHeatmap(fromDate, toDate, email string) ([]query.HeatmapDay, error) {
if a.db == nil {
return nil, fmt.Errorf("no repository open")
}
from, err := time.Parse("2006-01-02", fromDate)
if err != nil {
return nil, fmt.Errorf("parsing from date: %w", err)
}
to, err := time.Parse("2006-01-02", toDate)
if err != nil {
return nil, fmt.Errorf("parsing to date: %w", err)
}
return query.CommitHeatmap(a.db, from, to, email)
}
// FileHotspots returns per-file churn (lines changed) and commit counts
// between the given dates. Dates should be in "2006-01-02" format.
// Files matching any of the excludeGlobs patterns are omitted.
func (a *App) FileHotspots(fromDate, toDate string, excludeGlobs []string) ([]query.FileHotspot, error) {
if a.db == nil {
return nil, fmt.Errorf("no repository open")
}
from, err := time.Parse("2006-01-02", fromDate)
if err != nil {
return nil, fmt.Errorf("parsing from date: %w", err)
}
to, err := time.Parse("2006-01-02", toDate)
if err != nil {
return nil, fmt.Errorf("parsing to date: %w", err)
}
return query.FileHotspots(a.db, from, to, excludeGlobs)
}
// Contributors returns per-author commit counts, additions, and deletions
// between the given dates. Dates should be in "2006-01-02" format.
// Files matching any of the excludeGlobs patterns are excluded from stats.
func (a *App) Contributors(fromDate, toDate string, excludeGlobs []string) ([]query.Contributor, error) {
if a.db == nil {
return nil, fmt.Errorf("no repository open")
}
from, err := time.Parse("2006-01-02", fromDate)
if err != nil {
return nil, fmt.Errorf("parsing from date: %w", err)
}
to, err := time.Parse("2006-01-02", toDate)
if err != nil {
return nil, fmt.Errorf("parsing to date: %w", err)
}
return query.Contributors(a.db, from, to, excludeGlobs)
}
// FileOwnerships returns per-file ownership analysis showing the dominant
// contributors between the given dates. Dates should be in "2006-01-02" format.
// Files matching any of the excludeGlobs patterns are omitted.
func (a *App) FileOwnerships(fromDate, toDate string, excludeGlobs []string) ([]query.FileOwnership, error) {
if a.db == nil {
return nil, fmt.Errorf("no repository open")
}
from, err := time.Parse("2006-01-02", fromDate)
if err != nil {
return nil, fmt.Errorf("parsing from date: %w", err)
}
to, err := time.Parse("2006-01-02", toDate)
if err != nil {
return nil, fmt.Errorf("parsing to date: %w", err)
}
return query.FileOwnerships(a.db, from, to, excludeGlobs)
}
// TemporalHotspots returns per-file churn weighted by recency (exponential
// decay) between the given dates. Dates should be in "2006-01-02" format.
// halfLifeDays controls how fast old changes decay. Files matching any of
// the excludeGlobs patterns are omitted.
func (a *App) TemporalHotspots(fromDate, toDate string, halfLifeDays float64, excludeGlobs []string) ([]query.TemporalHotspot, error) {
if a.db == nil {
return nil, fmt.Errorf("no repository open")
}
from, err := time.Parse("2006-01-02", fromDate)
if err != nil {
return nil, fmt.Errorf("parsing from date: %w", err)
}
to, err := time.Parse("2006-01-02", toDate)
if err != nil {
return nil, fmt.Errorf("parsing to date: %w", err)
}
return query.TemporalHotspots(a.db, from, to, halfLifeDays, excludeGlobs)
}
// CoChanges returns file pairs that frequently change together in commits
// between the given dates. Dates should be in "2006-01-02" format.
// Only pairs with at least minCount shared commits are returned, up to limit.
// Files matching any of the excludeGlobs patterns are omitted.
func (a *App) CoChanges(fromDate, toDate string, minCount int, limit int, excludeGlobs []string) ([]query.CoChangePair, error) {
if a.db == nil {
return nil, fmt.Errorf("no repository open")
}
from, err := time.Parse("2006-01-02", fromDate)
if err != nil {
return nil, fmt.Errorf("parsing from date: %w", err)
}
to, err := time.Parse("2006-01-02", toDate)
if err != nil {
return nil, fmt.Errorf("parsing to date: %w", err)
}
return query.CoChanges(a.db, from, to, minCount, limit, excludeGlobs)
}
// RepoInfo holds metadata about the currently opened repository.
type RepoInfo struct {
Name string `json:"name"`
Branch string `json:"branch"`
HeadHash string `json:"head_hash"`
LastAuthor string `json:"last_author"`
LastEmail string `json:"last_email"`
LastMessage string `json:"last_message"`
LastCommitAge string `json:"last_commit_age"`
}
// RepoInfo returns metadata about the currently opened repository.
func (a *App) RepoInfo() (*RepoInfo, error) {
if a.repo == nil || a.db == nil {
return nil, fmt.Errorf("no repository open")
}
hash, err := a.repo.HeadHash()
if err != nil {
return nil, fmt.Errorf("reading HEAD: %w", err)
}
info := &RepoInfo{
Name: a.repo.RepoName(),
Branch: a.repo.CurrentBranch(),
HeadHash: hash[:min(7, len(hash))],
}
var authorName, authorEmail, message, committedAt string
err = a.db.QueryRow(
`SELECT author_name, author_email, message, committed_at
FROM commits ORDER BY committed_at DESC LIMIT 1`,
).Scan(&authorName, &authorEmail, &message, &committedAt)
if err == sql.ErrNoRows {
return info, nil
}
if err != nil {
return nil, fmt.Errorf("querying last commit: %w", err)
}
info.LastAuthor = authorName
info.LastEmail = authorEmail
info.LastMessage = strings.TrimSpace(message)
t, err := time.Parse(time.RFC3339, committedAt)
if err != nil {
trimmed := committedAt
if idx := strings.LastIndex(trimmed, " "); idx > 0 {
trimmed = trimmed[:idx]
}
t, err = time.Parse("2006-01-02 15:04:05 -0700", trimmed)
if err != nil {
info.LastCommitAge = committedAt
return info, nil
}
}
info.LastCommitAge = relativeTime(t)
return info, nil
}
func relativeTime(t time.Time) string {
d := time.Since(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
m := int(d.Minutes())
if m == 1 {
return "1 minute ago"
}
return fmt.Sprintf("%d minutes ago", m)
case d < 24*time.Hour:
h := int(d.Hours())
if h == 1 {
return "1 hour ago"
}
return fmt.Sprintf("%d hours ago", h)
default:
days := int(d.Hours() / 24)
if days == 1 {
return "1 day ago"
}
return fmt.Sprintf("%d days ago", days)
}
}
// DashboardStats returns aggregate commit and file-change stats between the
// given dates. Dates should be in "2006-01-02" format.
// Files matching any of the excludeGlobs patterns are omitted from file-level metrics.
func (a *App) DashboardStats(fromDate, toDate string, excludeGlobs []string) (*query.DashboardStats, error) {
if a.db == nil {
return nil, fmt.Errorf("no repository open")
}
from, err := time.Parse("2006-01-02", fromDate)
if err != nil {
return nil, fmt.Errorf("parsing from date: %w", err)
}
to, err := time.Parse("2006-01-02", toDate)
if err != nil {
return nil, fmt.Errorf("parsing to date: %w", err)
}
return query.GetDashboardStats(a.db, from, to, excludeGlobs)
}
// CommitsByHour returns per-hour commit counts between the given dates.
// Dates should be in "2006-01-02" format.
func (a *App) CommitsByHour(fromDate, toDate string) ([]query.HourBucket, error) {
if a.db == nil {
return nil, fmt.Errorf("no repository open")
}
from, err := time.Parse("2006-01-02", fromDate)
if err != nil {
return nil, fmt.Errorf("parsing from date: %w", err)
}
to, err := time.Parse("2006-01-02", toDate)
if err != nil {
return nil, fmt.Errorf("parsing to date: %w", err)
}
return query.CommitsByHour(a.db, from, to)
}
// addToGitExclude adds a pattern to .git/info/exclude if it's not already present.
func addToGitExclude(repoPath, pattern string) error {
excludePath := filepath.Join(repoPath, ".git", "info", "exclude")
existing, err := os.ReadFile(excludePath)
if err != nil && !os.IsNotExist(err) {
return err
}
// Check if pattern is already in the file.
lines := string(existing)
for _, line := range splitLines(lines) {
if line == pattern {
return nil
}
}
// Ensure we start on a new line.
suffix := "\n"
if len(existing) > 0 && existing[len(existing)-1] != '\n' {
suffix = "\n" + suffix
}
f, err := os.OpenFile(excludePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(suffix + pattern + "\n")
return err
}
func splitLines(s string) []string {
var lines []string
start := 0
for i := 0; i < len(s); i++ {
if s[i] == '\n' {
line := s[start:i]
if len(line) > 0 && line[len(line)-1] == '\r' {
line = line[:len(line)-1]
}
lines = append(lines, line)
start = i + 1
}
}
if start < len(s) {
lines = append(lines, s[start:])
}
return lines
}