Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions cmd/dive/cli/internal/command/adapter/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package adapter
import (
"context"
"fmt"
"os"

"github.com/spf13/afero"
"github.com/wagoodman/dive/cmd/dive/cli/internal/command/export"
"github.com/wagoodman/dive/dive/image"
"github.com/wagoodman/dive/internal/bus"
"github.com/wagoodman/dive/internal/bus/event/payload"
"github.com/wagoodman/dive/internal/log"
"os"
)

type Exporter interface {
Expand Down Expand Up @@ -49,7 +50,7 @@ func (e *jsonExporter) ExportTo(ctx context.Context, analysis *image.Analysis, p
mon.SetCompleted()
}

file, err := e.filesystem.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)
file, err := e.filesystem.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("cannot open export file: %w", err)
}
Expand Down
33 changes: 33 additions & 0 deletions cmd/dive/cli/internal/command/adapter/exporter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package adapter

import (
"context"
"encoding/json"
"strings"
"testing"

"github.com/spf13/afero"
"github.com/wagoodman/dive/dive/image"
)

func TestJSONExporterTruncatesExistingFile(t *testing.T) {
fs := afero.NewMemMapFs()
const path = "dive.json"

if err := afero.WriteFile(fs, path, []byte(strings.Repeat("x", 4096)), 0o644); err != nil {
t.Fatalf("failed to seed export file: %v", err)
}

analysis := &image.Analysis{Image: "example:latest"}
if err := NewExporter(fs).ExportTo(context.Background(), analysis, path); err != nil {
t.Fatalf("failed to export analysis: %v", err)
}

contents, err := afero.ReadFile(fs, path)
if err != nil {
t.Fatalf("failed to read export file: %v", err)
}
if !json.Valid(contents) {
t.Fatalf("export file contains trailing data: %q", contents)
}
}