Skip to content

Commit

Permalink
fix: avoid writing onto existing file when using magick
Browse files Browse the repository at this point in the history
  • Loading branch information
davidramiro committed Aug 26, 2024
1 parent c5b2a81 commit 7fa01b7
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 15 deletions.
5 changes: 4 additions & 1 deletion .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ archives:
- files:
- config.sample.toml
- README.md
format_overrides:
- goos: windows
format: zip
checksum:
name_template: 'checksums.txt'
snapshot:
Expand All @@ -23,4 +26,4 @@ changelog:
filters:
exclude:
- '^docs:'
- '^test:'
- '^test:'
20 changes: 16 additions & 4 deletions internal/adapters/converter/magick.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"hsbot/internal/adapters/file"
"os/exec"
"path/filepath"
"strings"
)

const MaxPower = 100
Expand Down Expand Up @@ -41,20 +42,31 @@ func NewMagickConverter() (*MagickConverter, error) {
}

func (m *MagickConverter) Scale(ctx context.Context, imageURL string, power float32) ([]byte, error) {
f, err := file.Download(ctx, imageURL)
f, err := file.DownloadFile(ctx, imageURL)
if err != nil {
return nil, err
}

path, err := file.SaveTemp(f, filepath.Ext(imageURL))
extension := filepath.Ext(imageURL)
path, err := file.SaveTempFile(f, extension)
if err != nil {
return nil, err
}

size := MaxPower - (power / PowerFactor)
outFile := fmt.Sprintf("%sliq%s", strings.TrimSuffix(path, extension), extension)
dimensions := fmt.Sprintf("%d%%x%d%%", int(size), int(size))

args := append(m.magickBinary, path, "-liquid-rescale", dimensions, path)
defer file.RemoveTempFile(path)
defer file.RemoveTempFile(outFile)

args := append(m.magickBinary, path, "-liquid-rescale", dimensions, outFile)

log.Debug().Strs("args", args).
Str("dimensions", dimensions).
Str("outFile", outFile).
Str("path", path).
Msg("scaling image")

cmd := exec.Command(args[0], args[1:]...)
out, err := cmd.Output()
Expand All @@ -65,5 +77,5 @@ func (m *MagickConverter) Scale(ctx context.Context, imageURL string, power floa

log.Debug().Msg("magick commands finished")

return file.GetTemp(path)
return file.GetTempFile(outFile)
}
17 changes: 8 additions & 9 deletions internal/adapters/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/rs/zerolog/log"
)

func Download(ctx context.Context, path string) ([]byte, error) {
func DownloadFile(ctx context.Context, path string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, path, nil)
if err != nil {
log.Error().Err(err).Str("path", path).Msg("")
Expand All @@ -38,7 +38,7 @@ func Download(ctx context.Context, path string) ([]byte, error) {
return buf, nil
}

func SaveTemp(data []byte, extension string) (string, error) {
func SaveTempFile(data []byte, extension string) (string, error) {
id, err := uuid.NewV4()
if err != nil {
return "", err
Expand All @@ -51,33 +51,32 @@ func SaveTemp(data []byte, extension string) (string, error) {
f, err := os.Create(path)
if err != nil {
log.Error().Err(err).Msg("could not create temp file")
return "", err
return "", fmt.Errorf("error creating temp file %w", err)
}

defer f.Close()

if _, err := f.Write(data); err != nil {
return "", err
log.Error().Err(err).Msg("could not write temp file")
return "", fmt.Errorf("error writing temp file %w", err)
}

log.Debug().Str("path", f.Name()).Msg("created file")

return f.Name(), nil
}

func GetTemp(path string) ([]byte, error) {
func GetTempFile(path string) ([]byte, error) {
buf, err := os.ReadFile(path)
if err != nil {
log.Error().Err(err).Msg("")
return nil, err
return nil, fmt.Errorf("error retrieving temp file %w", err)
}

defer removeTempFile(path)

return buf, nil
}

func removeTempFile(path string) {
func RemoveTempFile(path string) {
err := os.Remove(path)
if err != nil {
log.Warn().Str("path", path).Err(err).Msg("could not clean up temp file")
Expand Down
48 changes: 48 additions & 0 deletions internal/adapters/file/file_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package file

import (
"context"
"github.com/stretchr/testify/assert"
"os"
"testing"
)

func TestDownloadFile(t *testing.T) {
res, err := DownloadFile(context.Background(), "https://kore.cc/test.txt")
assert.NoError(t, err)

assert.Equal(t, []byte("test\n"), res)
}

func TestSaveTemp(t *testing.T) {
res, err := DownloadFile(context.Background(), "https://kore.cc/test.txt")
assert.NoError(t, err)

path, err := SaveTempFile(res, "txt")
assert.NoError(t, err)

defer RemoveTempFile(path)

stat, err := os.Stat(path)
assert.NoError(t, err)

assert.Equal(t, int64(5), stat.Size())
}

func TestGetTemp(t *testing.T) {
res, err := DownloadFile(context.Background(), "https://kore.cc/test.txt")
assert.NoError(t, err)

path, err := SaveTempFile(res, "txt")
assert.NoError(t, err)
defer RemoveTempFile(path)

stat, err := os.Stat(path)

assert.NoError(t, err)
assert.Equal(t, int64(5), stat.Size())

file, err := GetTempFile(path)
assert.NoError(t, err)
assert.Equal(t, []byte("test\n"), file)
}
2 changes: 1 addition & 1 deletion internal/adapters/generator/claude.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (c *ClaudeGenerator) GenerateFromPrompt(ctx context.Context, prompts []doma

func createUserMessage(ctx context.Context, prompt domain.Prompt) (anthropic.Message, error) {
if prompt.ImageURL != "" {
f, err := file.Download(ctx, prompt.ImageURL)
f, err := file.DownloadFile(ctx, prompt.ImageURL)
if err != nil {
return anthropic.Message{}, fmt.Errorf("error downloading image: %w", err)
}
Expand Down

0 comments on commit 7fa01b7

Please sign in to comment.