Skip to content

Commit 4ec9ad3

Browse files
committed
Add code snippet retrieval
1 parent 07b1708 commit 4ec9ad3

File tree

1 file changed

+51
-3
lines changed

1 file changed

+51
-3
lines changed

main.go

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import (
99
"strings"
1010

1111
e "github.com/Authentura/codectrl-go-logger/error"
12-
"github.com/Authentura/codectrl-go-logger/hashbag"
12+
h "github.com/Authentura/codectrl-go-logger/hashbag"
1313

1414
b "github.com/Authentura/codectrl-go-protobufs/data/backtrace_data"
1515
l "github.com/Authentura/codectrl-go-protobufs/data/log"
@@ -21,7 +21,7 @@ import (
2121
type createLogParams struct {
2222
surround uint32
2323
functionName string
24-
functionNameOccurences hashbag.HashBag[string]
24+
functionNameOccurences h.HashBag[string]
2525
}
2626

2727
func createLog(message string, params ...createLogParams) (*l.Log, error) {
@@ -39,6 +39,8 @@ func createLog(message string, params ...createLogParams) (*l.Log, error) {
3939
}
4040
}
4141

42+
parameters := params[0]
43+
4244
log := l.Log{
4345
Uuid: "",
4446
Stack: []*b.BacktraceData{},
@@ -68,6 +70,13 @@ func createLog(message string, params ...createLogParams) (*l.Log, error) {
6870
if last != nil {
6971
log.LineNumber = last.GetLineNumber()
7072
log.FileName = last.GetFilePath()
73+
snippet, err := getCodeSnippet(last.FilePath, &log, parameters.surround, "", nil)
74+
75+
if err != nil {
76+
return nil, errors.Wrap(err, 0)
77+
}
78+
79+
log.CodeSnippet = *snippet
7180
}
7281

7382
return &log, nil
@@ -286,4 +295,43 @@ func getCode(filePath string, lineNumber uint32) (*string, error) {
286295
return &line, nil
287296
}
288297

289-
// TODO: Add code snippet retrieval function
298+
// TODO: Account for batch logging
299+
300+
func getCodeSnippet(filePath string, log *l.Log, surround uint32, functionName string, functionNameOccurences *h.HashBag[string]) (*map[uint32]string, error) {
301+
file, err := os.Open(filePath)
302+
lineNumber := int(log.LineNumber)
303+
offsetLine := lineNumber - int(surround)
304+
305+
if offsetLine < 0 {
306+
offsetLine = 0
307+
}
308+
309+
if err != nil {
310+
return nil, errors.Wrap(err, 0)
311+
}
312+
313+
defer file.Close()
314+
315+
contentBytes, err := io.ReadAll(file)
316+
317+
if err != nil {
318+
return nil, errors.Wrap(err, 0)
319+
}
320+
321+
content := string(contentBytes)
322+
lines := strings.Split(content, "\n")
323+
324+
snippet := map[uint32]string{}
325+
326+
for index, line := range lines {
327+
if index < offsetLine {
328+
continue
329+
} else if index > lineNumber+int(surround) {
330+
break
331+
}
332+
333+
snippet[uint32(index+1)] = line
334+
}
335+
336+
return &snippet, nil
337+
}

0 commit comments

Comments
 (0)