-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathall_code.go
69 lines (60 loc) · 1.61 KB
/
all_code.go
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
package main
import (
"context"
"database/sql"
"fmt"
"os"
"path/filepath"
"strings"
)
type CodeLine struct {
Package string `json:"package"`
File string `json:"file"`
LineNumber int `json:"line_number"`
Content string `json:"content"`
}
// collectCodeLines collects all lines of code from Go files
func collectCodeLines(pkgDir string) ([]CodeLine, error) {
var results []CodeLine
err := filepath.Walk(pkgDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(info.Name(), ".go") {
packageName := filepath.Dir(path)
fileName := filepath.Base(path)
data, err := os.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(data), "\n")
for i, line := range lines {
results = append(results, CodeLine{
Package: packageName,
File: fileName,
LineNumber: i + 1,
Content: line,
})
}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to extract lines of code: %w", err)
}
return results, nil
}
func populateCode(ctx context.Context, db *sql.DB, pkgDir string) error {
allCode, err := collectCodeLines(pkgDir)
if err != nil {
return fmt.Errorf("failed to collect coverage results: %w", err)
}
for _, result := range allCode {
insertSQL := `INSERT INTO all_code (package, file, line_number, content) VALUES (?, ?, ?, ?);`
_, err := db.ExecContext(ctx, insertSQL, result.Package, result.File, result.LineNumber, result.Content)
if err != nil {
return fmt.Errorf("failed to insert code lines: %w", err)
}
}
return nil
}