summaryrefslogtreecommitdiff
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
parentd20ce579021f3dc087cbcb19a2e0cb2f9a4db113 (diff)
refactor function to be safer
-rw-r--r--internal/entry/entry.go5
-rw-r--r--internal/timestamp/timestamp.go16
-rw-r--r--internal/timestamp/timestamp_test.go12
3 files changed, 22 insertions, 11 deletions
diff --git a/internal/entry/entry.go b/internal/entry/entry.go
index 7ad2b2c..9f1eadf 100644
--- a/internal/entry/entry.go
+++ b/internal/entry/entry.go
@@ -101,7 +101,10 @@ func (e *Entry) MarkPosted() error {
if e.State == Posted {
return errors.New("entry is already posted")
}
- newPath := timestamp.UpdateInFilename(strings.TrimSuffix(e.Path, ".queued")+".posted", -2)
+ newPath, err := timestamp.UpdateInFilename(strings.TrimSuffix(e.Path, ".queued")+".posted", -2)
+ if err != nil {
+ return err
+ }
if err := os.Rename(e.Path, newPath); err != nil {
return err
}
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)