summaryrefslogtreecommitdiff
path: root/internal/timestamp
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2024-10-18 22:08:50 +0300
committerPaul Buetow <paul@buetow.org>2024-10-18 22:08:50 +0300
commit0ad3bbbfc1f2c126d0c9c7282958b5839192b49e (patch)
treed180c8f73b8aad74f9583e36dbf4489c485f33d8 /internal/timestamp
parentd20ce579021f3dc087cbcb19a2e0cb2f9a4db113 (diff)
refactor function to be safer
Diffstat (limited to 'internal/timestamp')
-rw-r--r--internal/timestamp/timestamp.go16
-rw-r--r--internal/timestamp/timestamp_test.go12
2 files changed, 18 insertions, 10 deletions
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)