From 0ad3bbbfc1f2c126d0c9c7282958b5839192b49e Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Fri, 18 Oct 2024 22:08:50 +0300 Subject: refactor function to be safer --- internal/timestamp/timestamp.go | 16 ++++++++++------ internal/timestamp/timestamp_test.go | 12 ++++++++---- 2 files changed, 18 insertions(+), 10 deletions(-) (limited to 'internal/timestamp') diff --git a/internal/timestamp/timestamp.go b/internal/timestamp/timestamp.go index fb1fe50..7adfc80 100644 --- a/internal/timestamp/timestamp.go +++ b/internal/timestamp/timestamp.go @@ -1,6 +1,7 @@ package timestamp import ( + "fmt" "strings" "time" ) @@ -28,15 +29,18 @@ func OldestValidTime() time.Time { // The time this code was written a:round, actually. oldestValidTime, err := Parse("20240912-102800") if err != nil { - // Never expected - panic(err) + panic(err) // Never expected } return oldestValidTime } -// TODO: Maybe make this safer? -func UpdateInFilename(filename string, rIndex int) string { +func UpdateInFilename(filename string, rIndex int) (string, error) { parts := strings.Split(filename, ".") - parts[len(parts)+rIndex] = Now() - return strings.Join(parts, ".") + ind := len(parts) + rIndex + if ind < 0 || ind >= len(parts) { + return "", fmt.Errorf("unable to update timestamp in %s, invalid index %d: %v", + filename, ind, parts) + } + parts[ind] = Now() + return strings.Join(parts, "."), nil } diff --git a/internal/timestamp/timestamp_test.go b/internal/timestamp/timestamp_test.go index 499d7d5..d408480 100644 --- a/internal/timestamp/timestamp_test.go +++ b/internal/timestamp/timestamp_test.go @@ -9,12 +9,16 @@ func TestUpdateInFilename(t *testing.T) { t.Parallel() var ( - filePath = "gosdir/db/platforms/mastodon/1728240487.txt.20241009-232530.queued" - nowTime = NowTime() - updatedFilePath = UpdateInFilename(filePath, -2) - parts = strings.Split(updatedFilePath, ".") + filePath = "gosdir/db/platforms/mastodon/1728240487.txt.20241009-232530.queued" + nowTime = NowTime() ) + updatedFilePath, err := UpdateInFilename(filePath, -2) + if err != nil { + t.Error(err) + } + parts := strings.Split(updatedFilePath, ".") + updatedTime, err := Parse(parts[len(parts)-2]) if err != nil { t.Error(err) -- cgit v1.2.3