diff --git a/app/bot/sample_updater.go b/app/bot/sample_updater.go index b986b2f6..bf7191be 100644 --- a/app/bot/sample_updater.go +++ b/app/bot/sample_updater.go @@ -30,6 +30,14 @@ func (s *SampleUpdater) Reader() (io.ReadCloser, error) { // Append a message to the file, preventing duplicates func (s *SampleUpdater) Append(msg string) error { + // if file does not exist, create it + if _, err := os.Stat(s.fileName); os.IsNotExist(err) { + if _, err = os.Create(s.fileName); err != nil { + return fmt.Errorf("failed to create %s: %w", s.fileName, err) + } + } + + // check if the message is already in the file fh, err := os.Open(s.fileName) if err != nil { return fmt.Errorf("failed to open %s: %w", s.fileName, err) @@ -44,6 +52,7 @@ func (s *SampleUpdater) Append(msg string) error { } } + // append the message to the file fh, err = os.OpenFile(s.fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644) //nolint:gosec // keep it readable by all if err != nil { return fmt.Errorf("failed to open %s: %w", s.fileName, err) diff --git a/app/bot/sample_updater_test.go b/app/bot/sample_updater_test.go index f1c641b3..a82ea4cd 100644 --- a/app/bot/sample_updater_test.go +++ b/app/bot/sample_updater_test.go @@ -3,6 +3,7 @@ package bot import ( "io" "os" + "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -72,6 +73,24 @@ func TestSampleUpdater(t *testing.T) { assert.Equal(t, "Test message second line third line\n", string(content)) }) + t.Run("no file", func(t *testing.T) { + dir := os.TempDir() + file := filepath.Join(dir, "non-existent-samples.txt") + defer os.Remove(file) + + updater := NewSampleUpdater(file) + err := updater.Append("Test message") + assert.NoError(t, err) + + reader, err := updater.Reader() + require.NoError(t, err) + defer reader.Close() + + content, err := io.ReadAll(reader) + assert.NoError(t, err) + assert.Equal(t, "Test message\n", string(content)) + }) + t.Run("unhappy path", func(t *testing.T) { updater := NewSampleUpdater("/tmp/non-existent/samples.txt") err := updater.Append("Test message")