summaryrefslogtreecommitdiff
path: root/internal/showcase/code_extractor.go
blob: e8ba0d3527b4e59b668c1dd53aebe7be5d3d409e (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
package showcase

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"path/filepath"
	"strings"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

// extractCodeSnippet extracts a random code snippet from the repository
func extractCodeSnippet(repoPath string, languages []LanguageStats) (string, string, error) {
	if len(languages) == 0 {
		return "", "", fmt.Errorf("no programming languages found")
	}

	// Get the primary language (highest percentage)
	primaryLang := languages[0].Name
	
	// Define file extensions for each language
	langExtensions := map[string][]string{
		"Go":           {".go"},
		"Python":       {".py"},
		"JavaScript":   {".js"},
		"TypeScript":   {".ts"},
		"Java":         {".java"},
		"C":            {".c", ".h"},
		"C++":          {".cpp", ".cc", ".cxx", ".hpp"},
		"C/C++":        {".h"},
		"C#":           {".cs"},
		"Ruby":         {".rb"},
		"PHP":          {".php"},
		"Swift":        {".swift"},
		"Kotlin":       {".kt"},
		"Rust":         {".rs"},
		"Shell":        {".sh", ".bash"},
		"Perl":         {".pl", ".pm"},
		"Haskell":      {".hs"},
		"Lua":          {".lua"},
		"HTML":         {".html", ".htm"},
		"CSS":          {".css"},
		"SQL":          {".sql"},
		"Make":         {"Makefile", "makefile", "GNUmakefile"},
		"HCL":          {".tf", ".tfvars", ".hcl"},
	}

	// Get file extensions for the primary language
	extensions, ok := langExtensions[primaryLang]
	if !ok {
		// Try other languages if primary doesn't have extensions defined
		for _, lang := range languages {
			if exts, exists := langExtensions[lang.Name]; exists {
				extensions = exts
				primaryLang = lang.Name
				break
			}
		}
		if len(extensions) == 0 {
			return "", "", fmt.Errorf("no known file extensions for languages")
		}
	}

	// Find all files matching the extensions
	var codeFiles []string
	err := filepath.Walk(repoPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return nil
		}

		// Skip directories
		if info.IsDir() {
			name := info.Name()
			// Skip hidden directories and common non-code directories
			if strings.HasPrefix(name, ".") && name != "." || 
			   name == "node_modules" || 
			   name == "vendor" || 
			   name == "target" || 
			   name == "dist" || 
			   name == "build" || 
			   name == "__pycache__" {
				return filepath.SkipDir
			}
			return nil
		}

		// Skip files that are too large
		if info.Size() > 1*1024*1024 { // 1MB
			return nil
		}

		// Check if file matches extensions
		basename := filepath.Base(path)
		ext := filepath.Ext(path)
		
		for _, validExt := range extensions {
			if validExt == basename || (strings.HasPrefix(validExt, ".") && ext == validExt) {
				// Skip test files and generated files
				if !strings.Contains(basename, "_test") && 
				   !strings.Contains(basename, ".test.") &&
				   !strings.Contains(basename, ".min.") &&
				   !strings.Contains(path, "/test/") &&
				   !strings.Contains(path, "/tests/") {
					codeFiles = append(codeFiles, path)
				}
				break
			}
		}

		return nil
	})

	if err != nil {
		return "", "", err
	}

	if len(codeFiles) == 0 {
		return "", "", fmt.Errorf("no code files found")
	}

	// Select a random file
	selectedFile := codeFiles[rand.Intn(len(codeFiles))]
	
	// Read the file and extract a snippet (~10 lines but complete functions)
	snippet, err := extractSnippetFromFile(selectedFile, 10, 15)
	if err != nil {
		return "", "", err
	}

	// Get relative path for display
	relPath, _ := filepath.Rel(repoPath, selectedFile)
	
	return snippet, fmt.Sprintf("%s from `%s`", primaryLang, relPath), nil
}

// extractSnippetFromFile extracts a code snippet from a file
func extractSnippetFromFile(filePath string, minLines, maxLines int) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// Read all lines
	var lines []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		return "", err
	}

	totalLines := len(lines)
	if totalLines == 0 {
		return "", fmt.Errorf("file is empty")
	}

	// Try to find the smallest complete function
	bestFunction := findSmallestCompleteFunction(lines)
	if bestFunction != "" {
		return bestFunction, nil
	}

	// If no complete function found, try to find a complete function/method
	functionStart, functionEnd := findCompleteFunctionOrMethod(lines, minLines, maxLines*2) // Allow larger functions
	if functionStart >= 0 && functionEnd >= 0 {
		return strings.Join(lines[functionStart:functionEnd+1], "\n"), nil
	}

	// Fallback to finding an interesting start with at least minLines
	interestingStart := findInterestingStart(lines, minLines)
	if interestingStart >= 0 {
		endLine := interestingStart + minLines
		if endLine > totalLines {
			endLine = totalLines
		}
		return strings.Join(lines[interestingStart:endLine], "\n"), nil
	}

	// Last resort: return first minLines (skip imports if possible)
	skipLines := 0
	for i, line := range lines {
		trimmed := strings.TrimSpace(line)
		if trimmed != "" && !strings.HasPrefix(trimmed, "import") && 
		   !strings.HasPrefix(trimmed, "package") && !strings.HasPrefix(trimmed, "using") &&
		   !strings.HasPrefix(trimmed, "#include") && !strings.HasPrefix(trimmed, "from") {
			skipLines = i
			break
		}
	}

	endLine := skipLines + minLines
	if endLine > totalLines {
		endLine = totalLines
	}

	return strings.Join(lines[skipLines:endLine], "\n"), nil
}

// findSmallestCompleteFunction finds the smallest complete function in the file
func findSmallestCompleteFunction(lines []string) string {
	type functionInfo struct {
		start int
		end   int
		size  int
	}
	
	var functions []functionInfo
	
	// Keywords that typically start functions/methods
	functionKeywords := []string{
		"func ", "function ", "def ", "public ", "private ", "protected ",
		"static ", "async ", "procedure ", "sub ", "method ",
	}
	
	// Find all complete functions
	for i := 0; i < len(lines); i++ {
		line := strings.TrimSpace(lines[i])
		
		// Check if this line starts a function
		isFunction := false
		for _, keyword := range functionKeywords {
			if strings.Contains(line, keyword) && !strings.HasPrefix(line, "//") && !strings.HasPrefix(line, "#") {
				isFunction = true
				break
			}
		}
		
		if !isFunction {
			continue
		}
		
		// Try to find the end of this function
		functionEnd := findFunctionEnd(lines, i)
		if functionEnd > i {
			size := functionEnd - i + 1
			// Only consider functions between 5 and 50 lines
			if size >= 5 && size <= 50 {
				functions = append(functions, functionInfo{
					start: i,
					end:   functionEnd,
					size:  size,
				})
			}
		}
	}
	
	// Find the smallest function
	if len(functions) > 0 {
		smallest := functions[0]
		for _, f := range functions[1:] {
			if f.size < smallest.size {
				smallest = f
			}
		}
		return strings.Join(lines[smallest.start:smallest.end+1], "\n")
	}
	
	return ""
}

// findFunctionEnd finds the end of a function starting at the given line
func findFunctionEnd(lines []string, start int) int {
	if start >= len(lines) {
		return -1
	}
	
	// For brace-based languages
	braceCount := 0
	inFunction := false
	
	// For Python - track initial indentation
	isPython := strings.Contains(lines[start], "def ") || strings.Contains(lines[start], "class ")
	var initialIndent int
	if isPython && start < len(lines)-1 {
		// Get indentation of first line after def
		for i := start + 1; i < len(lines); i++ {
			if strings.TrimSpace(lines[i]) != "" {
				initialIndent = len(lines[i]) - len(strings.TrimLeft(lines[i], " \t"))
				break
			}
		}
	}
	
	for i := start; i < len(lines); i++ {
		line := lines[i]
		trimmed := strings.TrimSpace(line)
		
		// Handle Python indentation
		if isPython && i > start {
			if trimmed == "" {
				continue
			}
			currentIndent := len(line) - len(strings.TrimLeft(line, " \t"))
			if currentIndent < initialIndent {
				return i - 1
			}
		}
		
		// Handle brace-based languages
		for _, ch := range line {
			if ch == '{' {
				braceCount++
				inFunction = true
			} else if ch == '}' {
				braceCount--
				if braceCount == 0 && inFunction {
					return i
				}
			}
		}
	}
	
	// If we're in Python and reached the end, return the last line
	if isPython {
		return len(lines) - 1
	}
	
	return -1
}

// findCompleteFunctionOrMethod finds a complete function or method within size constraints
func findCompleteFunctionOrMethod(lines []string, minLines, maxLines int) (int, int) {
	// Keywords that typically start functions/methods
	functionKeywords := []string{
		"func ", "function ", "def ", "public ", "private ", "protected ",
		"static ", "async ", "procedure ", "sub ", "method ",
	}
	
	// Try to find a function that fits within our size constraints
	for i := 0; i < len(lines); i++ {
		line := strings.TrimSpace(lines[i])
		
		// Check if this line starts a function
		isFunction := false
		for _, keyword := range functionKeywords {
			if strings.Contains(line, keyword) && !strings.HasPrefix(line, "//") && !strings.HasPrefix(line, "#") {
				isFunction = true
				break
			}
		}
		
		if !isFunction {
			continue
		}
		
		// Try to find the end of this function
		functionEnd := findFunctionEnd(lines, i)
		if functionEnd > i {
			functionLength := functionEnd - i + 1
			if functionLength >= minLines && functionLength <= maxLines {
				return i, functionEnd
			}
		}
	}
	
	return -1, -1
}

// findInterestingStart tries to find a good starting point for the snippet
func findInterestingStart(lines []string, snippetSize int) int {
	// Look for function/class definitions
	keywords := []string{
		"func ", "function ", "def ", "class ", "public class",
		"interface ", "struct ", "type ", "const ", "var ",
		"procedure ", "sub ", "method ",
	}

	for i := 0; i < len(lines)-snippetSize; i++ {
		line := strings.TrimSpace(lines[i])
		// Skip empty lines and comments
		if line == "" || strings.HasPrefix(line, "//") || strings.HasPrefix(line, "#") ||
		   strings.HasPrefix(line, "/*") || strings.HasPrefix(line, "*") {
			continue
		}

		// Check for interesting keywords
		for _, keyword := range keywords {
			if strings.Contains(line, keyword) {
				// Found something interesting, start here
				return i
			}
		}
	}

	// No interesting start found
	return -1
}