go_sandbox/internal/chrono/chrono.go
2024-11-02 14:07:18 +03:00

93 lines
2.2 KiB
Go

package chrono
import (
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"time"
)
type ChronoEntry struct {
Date, Time, Action string
}
type ParsedChronoEntry struct {
StartTime time.Time
Action string
Duration string
}
func Chrono() {
// Return path of an executable
exPath, err := os.Executable()
if err != nil {
panic(err)
}
exDir := filepath.Dir(exPath)
fmt.Println(exDir)
// Return path of the current directory
path, err := os.Getwd()
if err != nil {
panic(err)
}
// Join paths
textFilePath := filepath.Join(path, "chrono.txt")
// Read file with chrono data
readFile, err := os.Open(textFilePath)
if err != nil {
panic(err)
}
defer readFile.Close()
fileScanner := bufio.NewScanner(readFile)
fileScanner.Split(bufio.ScanLines)
var fileLines []string
for fileScanner.Scan() {
fileLines = append(fileLines, fileScanner.Text())
}
// Prepare slice for data
parse_result := make([]ChronoEntry, 0)
result := make([]ParsedChronoEntry, 0)
r := regexp.MustCompile(
`(?P<date>\d{2}\s\w*\s\d{4})\s+at\s+(?P<time>\d{2}:\d{2}):\s+(?P<action>.*)`,
)
// Read lines from parsed data
for _, line := range fileLines {
// Find matches in line
m := r.FindStringSubmatch(line)
// Prepare dict for storing data
result := make(map[string]string)
// Parsing line and appending to result
for i, name := range r.SubexpNames() {
if i != 0 && name != "" {
result[name] = m[i]
}
}
chrono_entry := ChronoEntry{result["date"], result["time"], result["action"]}
parse_result = append(parse_result, chrono_entry)
}
for index, element := range parse_result {
layout := "02 Jan 2006-15:04"
timestamp := fmt.Sprintf("%s-%s", element.Date, element.Time)
t, err := time.Parse(layout, timestamp)
if err != nil {
panic(err)
}
if index == 0 {
k := ParsedChronoEntry{StartTime: t, Action: element.Action, Duration: "0"}
result = append(result, k)
continue
} else {
delta := t.Sub(result[index-1].StartTime)
result[index-1].Duration = delta.String()
if delta == time.Duration(0) {
delta = time.Duration(time.Minute)
}
k := ParsedChronoEntry{t, element.Action, delta.String()}
result = append(result, k)
}
}
fmt.Println(result)
}