/
exporter.go
73 lines (59 loc) · 1.48 KB
/
exporter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package exec
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/pyroscope-io/pyroscope/pkg/structs/flamebearer"
"github.com/sirupsen/logrus"
)
type Exporter struct {
logger *logrus.Logger
outputDir string
}
func NewExporter(logger *logrus.Logger, outputDir string) *Exporter {
return &Exporter{
logger: logger,
outputDir: outputDir,
}
}
// Export exports each FlamebearerProfile into a JSON file
func (w *Exporter) Export(items map[string]flamebearer.FlamebearerProfile) error {
// Only create the dir when there are items
// So that we don't pollute with an empty dir
if len(items) > 0 {
if err := ensureDirExists(w.outputDir); err != nil {
return err
}
}
for k, v := range items {
filename := filepath.Join(w.outputDir, fmt.Sprintf("%s.json", k))
// Use JSON since that's what we are exporting
if err := w.Write(filename, v); err != nil {
return err
}
logrus.Infof("created %s", filename)
}
return nil
}
// Write writes a flamebearer in json format to its dataDir
func (*Exporter) Write(path string, flame flamebearer.FlamebearerProfile) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
if err := json.NewEncoder(f).Encode(flame); err != nil {
return err
}
return f.Close()
}
func ensureDirExists(dir string) error {
if dir == "" {
return nil
}
if err := os.MkdirAll(dir, os.ModeDir|os.ModePerm); err != nil {
return fmt.Errorf("could not create directory '%s': %w", dir, err)
}
return nil
}