summaryrefslogtreecommitdiff
path: root/internal/showcase/metadata.go
blob: 798b8fe99df31af8f527f2e111e6ce458018aae2 (plain)
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
package showcase

import (
	"fmt"
	"math"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

const unreleasedScorePenalty = 0.75

// LanguageStats holds statistics for a programming language
type LanguageStats struct {
	Name       string
	Lines      int
	Percentage float64
}

// RepoMetadata holds metadata about a repository
type RepoMetadata struct {
	Languages       []LanguageStats // Programming languages with usage statistics
	Documentation   []LanguageStats // Documentation/text files with usage statistics
	CommitCount     int
	LinesOfCode     int // Lines of code (excluding documentation)
	LinesOfDocs     int // Lines of documentation
	FirstCommitDate string
	LastCommitDate  string
	License         string
	AvgCommitAge    float64 // Average age of last 42 commits in days
	TagCount        int     // Total number of git tags in the repository
	Score           float64 // Project score combining recent activity, reduced LOC weight, tag count, and release status
	LatestTag       string  // Latest version tag (empty if no tags)
	LatestTagDate   string  // Date of the latest tag (empty if no tags)
	HasReleases     bool    // Whether the project has any releases/tags
}

// extractRepoMetadata extracts metadata from a repository
func extractRepoMetadata(repoPath string) (*RepoMetadata, error) {
	metadata := &RepoMetadata{}

	// Get programming languages and documentation by analyzing file extensions
	languages, documentation, err := detectLanguages(repoPath)
	if err != nil {
		fmt.Printf("Warning: Failed to detect languages: %v\n", err)
	}
	metadata.Languages = languages
	metadata.Documentation = documentation

	// Get commit count
	commitCount, err := getCommitCount(repoPath)
	if err != nil {
		fmt.Printf("Warning: Failed to get commit count: %v\n", err)
	}
	metadata.CommitCount = commitCount

	// Calculate lines of code and documentation from language stats
	loc := 0
	for _, lang := range metadata.Languages {
		loc += lang.Lines
	}
	metadata.LinesOfCode = loc

	locDocs := 0
	for _, doc := range metadata.Documentation {
		locDocs += doc.Lines
	}
	metadata.LinesOfDocs = locDocs

	// Get first and last commit dates
	firstDate, err := getFirstCommitDate(repoPath)
	if err != nil {
		fmt.Printf("Warning: Failed to get first commit date: %v\n", err)
	}
	metadata.FirstCommitDate = firstDate

	lastDate, err := getLastCommitDate(repoPath)
	if err != nil {
		fmt.Printf("Warning: Failed to get last commit date: %v\n", err)
	}
	metadata.LastCommitDate = lastDate

	// Check for license file
	license := detectLicense(repoPath)
	metadata.License = license

	// Get average age of last 42 commits (42 is the answer!)
	avgAge, err := getAverageCommitAge(repoPath, 42)
	if err != nil {
		fmt.Printf("Warning: Failed to get average commit age: %v\n", err)
	}
	metadata.AvgCommitAge = avgAge

	// Get tag metadata before calculating score so tags can influence ranking.
	latestTag, latestTagDate, hasReleases, tagCount, err := getLatestTag(repoPath)
	if err != nil {
		fmt.Printf("Warning: Failed to get latest tag: %v\n", err)
	}
	metadata.LatestTag = latestTag
	metadata.LatestTagDate = latestTagDate
	metadata.HasReleases = hasReleases
	metadata.TagCount = tagCount

	// Calculate score with recent activity as the strongest signal,
	// a smaller LOC contribution than before, a modest tag bonus,
	// and a penalty for projects without a release yet.
	metadata.Score = calculateRepoScore(metadata.LinesOfCode, metadata.AvgCommitAge, metadata.TagCount, metadata.HasReleases)

	return metadata, nil
}

func calculateRepoScore(linesOfCode int, avgCommitAge float64, tagCount int, hasReleases bool) float64 {
	sizeComponent := 0.0
	if linesOfCode > 0 {
		sizeComponent = math.Sqrt(math.Log10(float64(linesOfCode)+1.0)) * 250.0
	}

	tagComponent := 0.0
	if tagCount > 0 {
		tagComponent = math.Log1p(float64(tagCount)) * 40.0
	}

	score := (sizeComponent + tagComponent) / (avgCommitAge + 1.0)
	if !hasReleases {
		score *= unreleasedScorePenalty
	}

	return score
}

// getCommitCount returns the total number of commits
func getCommitCount(repoPath string) (int, error) {
	cmd := exec.Command("git", "-C", repoPath, "rev-list", "--all", "--count")
	output, err := cmd.Output()
	if err != nil {
		return 0, err
	}

	count, err := strconv.Atoi(strings.TrimSpace(string(output)))
	if err != nil {
		return 0, err
	}

	return count, nil
}

// countLinesOfCode counts lines of code (excluding binary files and common non-code files)
func countLinesOfCode(repoPath string) (int, error) {
	// Use git ls-files to get tracked files, then count lines
	// Exclude binary files and common non-code files
	cmd := exec.Command("bash", "-c", fmt.Sprintf(
		`cd "%s" && git ls-files | grep -E '\.(go|py|js|ts|java|c|cpp|h|hpp|cs|rb|php|swift|kt|rs|scala|r|sh|bash|zsh|pl|lua|vim|el|clj|hs|ml|ex|exs|dart|jl|nim|v|zig|html|css|scss|sass|json|xml|yaml|yml|toml|ini|conf|cfg)$' | xargs wc -l 2>/dev/null | tail -n 1 | awk '{print $1}'`,
		repoPath,
	))

	output, err := cmd.Output()
	if err != nil {
		// Fallback: try a simpler approach
		cmd = exec.Command("bash", "-c", fmt.Sprintf(
			`find "%s" -type f -name "*.go" -o -name "*.py" -o -name "*.js" -o -name "*.java" -o -name "*.c" -o -name "*.cpp" -o -name "*.rs" | xargs wc -l 2>/dev/null | tail -n 1 | awk '{print $1}'`,
			repoPath,
		))
		output, err = cmd.Output()
		if err != nil {
			return 0, err
		}
	}

	loc, err := strconv.Atoi(strings.TrimSpace(string(output)))
	if err != nil {
		return 0, err
	}

	return loc, nil
}

// getFirstCommitDate returns the date of the first commit
func getFirstCommitDate(repoPath string) (string, error) {
	cmd := exec.Command("git", "-C", repoPath, "log", "--reverse", "--pretty=format:%ai", "--date=short")
	output, err := cmd.Output()
	if err != nil {
		return "", err
	}

	lines := strings.Split(string(output), "\n")
	if len(lines) > 0 && lines[0] != "" {
		// Extract just the date part (YYYY-MM-DD)
		parts := strings.Fields(lines[0])
		if len(parts) > 0 {
			return parts[0], nil
		}
	}

	return "", fmt.Errorf("no commits found")
}

// getLastCommitDate returns the date of the last commit
func getLastCommitDate(repoPath string) (string, error) {
	cmd := exec.Command("git", "-C", repoPath, "log", "-1", "--pretty=format:%ai", "--date=short")
	output, err := cmd.Output()
	if err != nil {
		return "", err
	}

	// Extract just the date part (YYYY-MM-DD)
	parts := strings.Fields(string(output))
	if len(parts) > 0 {
		return parts[0], nil
	}

	return "", fmt.Errorf("no commits found")
}

// detectLicense checks for common license files
func detectLicense(repoPath string) string {
	licenseFiles := []string{
		"LICENSE",
		"LICENSE.txt",
		"LICENSE.md",
		"license",
		"license.txt",
		"license.md",
		"COPYING",
		"COPYING.txt",
		"COPYRIGHT",
		"COPYRIGHT.txt",
	}

	for _, filename := range licenseFiles {
		path := filepath.Join(repoPath, filename)
		if info, err := os.Stat(path); err == nil && !info.IsDir() {
			// Try to detect license type by reading the file
			content, err := os.ReadFile(path)
			if err == nil {
				contentStr := string(content)
				switch {
				case strings.Contains(contentStr, "MIT License"):
					return "MIT"
				case strings.Contains(contentStr, "Apache License") && strings.Contains(contentStr, "Version 2.0"):
					return "Apache-2.0"
				case strings.Contains(contentStr, "GNU GENERAL PUBLIC LICENSE") && strings.Contains(contentStr, "Version 3"):
					return "GPL-3.0"
				case strings.Contains(contentStr, "GNU GENERAL PUBLIC LICENSE") && strings.Contains(contentStr, "Version 2"):
					return "GPL-2.0"
				case strings.Contains(contentStr, "BSD 3-Clause License"):
					return "BSD-3-Clause"
				case strings.Contains(contentStr, "BSD 2-Clause License"):
					return "BSD-2-Clause"
				case strings.Contains(contentStr, "Mozilla Public License Version 2.0"):
					return "MPL-2.0"
				case strings.Contains(contentStr, "ISC License"):
					return "ISC"
				case strings.Contains(contentStr, "GNU LESSER GENERAL PUBLIC LICENSE"):
					return "LGPL"
				case strings.Contains(contentStr, "The Unlicense"):
					return "Unlicense"
				case strings.Contains(contentStr, "CC0"):
					return "CC0"
				default:
					return "Custom License"
				}
			}
			return "License file found"
		}
	}

	return "No license found"
}

// getAverageCommitAge calculates the average age of the last N commits in days
func getAverageCommitAge(repoPath string, commitCount int) (float64, error) {
	// Get the last N commit dates
	cmd := exec.Command("git", "-C", repoPath, "log", fmt.Sprintf("-%d", commitCount), "--pretty=format:%at")
	output, err := cmd.Output()
	if err != nil {
		return 0, err
	}

	lines := strings.Split(strings.TrimSpace(string(output)), "\n")
	if len(lines) == 0 || lines[0] == "" {
		return 0, fmt.Errorf("no commits found")
	}

	// Calculate average age
	now := float64(time.Now().Unix())
	var totalAge float64
	validCommits := 0

	for _, line := range lines {
		if line == "" {
			continue
		}

		timestamp, err := strconv.ParseInt(line, 10, 64)
		if err != nil {
			continue
		}

		age := (now - float64(timestamp)) / 86400 // Convert to days
		totalAge += age
		validCommits++
	}

	if validCommits == 0 {
		return 0, fmt.Errorf("no valid commits found")
	}

	return totalAge / float64(validCommits), nil
}

// getLatestTag returns the latest version-like tag, its date, whether the repo has releases, and total tag count.
func getLatestTag(repoPath string) (string, string, bool, int, error) {
	// First try to get tags sorted by version
	cmd := exec.Command("git", "-C", repoPath, "tag", "-l", "--sort=-version:refname")
	output, err := cmd.Output()
	if err != nil {
		// Fallback to describe
		cmd = exec.Command("git", "-C", repoPath, "describe", "--tags", "--abbrev=0")
		output, err = cmd.Output()
		if err != nil {
			// No tags at all
			return "", "", false, 0, nil
		}
	}

	tags := strings.Split(strings.TrimSpace(string(output)), "\n")
	if len(tags) == 0 || tags[0] == "" {
		return "", "", false, 0, nil
	}

	tagCount := 0
	for _, tag := range tags {
		if strings.TrimSpace(tag) != "" {
			tagCount++
		}
	}

	// Find the first tag that looks like a version number
	latestTag := ""
	for _, tag := range tags {
		if isVersionTag(tag) {
			latestTag = tag
			break
		}
	}

	if latestTag == "" {
		// No version-like tags found
		return "", "", false, tagCount, nil
	}

	// Get the date of the latest tag
	cmd = exec.Command("git", "-C", repoPath, "log", "-1", "--format=%ai", latestTag)
	dateOutput, err := cmd.Output()
	if err != nil {
		// Tag exists but couldn't get date
		return latestTag, "", true, tagCount, nil
	}

	// Extract just the date part (YYYY-MM-DD)
	parts := strings.Fields(string(dateOutput))
	tagDate := ""
	if len(parts) > 0 {
		tagDate = parts[0]
	}

	// Return the latest tag and its date
	return latestTag, tagDate, true, tagCount, nil
}

// isVersionTag checks if a tag looks like a version number
func isVersionTag(tag string) bool {
	// Remove 'v' prefix if present
	versionStr := strings.TrimPrefix(tag, "v")

	// Check if the remaining string contains at least one digit and one dot
	hasDigit := false
	hasDot := false

	for _, ch := range versionStr {
		if ch >= '0' && ch <= '9' {
			hasDigit = true
		} else if ch == '.' {
			hasDot = true
		} else if ch != '-' && ch != '+' && ch != '_' &&
			(ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') {
			// Allow alphanumeric characters and common separators
			// but anything else makes it not a version
			return false
		}
	}

	// Must have at least one digit, and either:
	// - have a dot (e.g., 1.0, 0.1.2)
	// - be just digits (e.g., 2, 2024)
	// - start with a digit (e.g., 1-beta)
	if hasDigit && len(versionStr) > 0 {
		firstChar := versionStr[0]
		if firstChar >= '0' && firstChar <= '9' {
			return true
		}
	}

	return hasDigit && hasDot
}