1
1
package main
2
2
3
3
import (
4
+ "encoding/csv"
4
5
"fmt"
6
+ "io"
5
7
"log"
8
+ "os"
6
9
7
- "github.com/clems4ever/go-graphkb/importer"
8
- "github.com/clems4ever/go-graphkb/internal/sources"
10
+ "github.com/clems4ever/go-graphkb/graphkb"
9
11
"github.com/spf13/cobra"
10
12
"github.com/spf13/viper"
11
13
)
12
14
15
+ type CSVSource struct {
16
+ dataPath string
17
+ }
18
+
19
+ func NewCSVSource () * CSVSource {
20
+ csvSource := new (CSVSource )
21
+ csvSource .dataPath = viper .GetString ("path" )
22
+
23
+ if csvSource .dataPath == "" {
24
+ log .Fatal (fmt .Errorf ("Unable to detect CSV file path in configuration. Check patch configuration is provided" ))
25
+ }
26
+
27
+ return csvSource
28
+ }
29
+
30
+ func (cs * CSVSource ) Start (importer * graphkb.GraphImporter ) error {
31
+ file , err := os .Open (cs .dataPath )
32
+ if err != nil {
33
+ return err
34
+ }
35
+ defer file .Close ()
36
+
37
+ r := csv .NewReader (file )
38
+
39
+ previousGraph , err := importer .ReadCurrentGraph ()
40
+ if err != nil {
41
+ return fmt .Errorf ("Unable to read previous graph: %v" , err )
42
+ }
43
+
44
+ tx := importer .CreateTransaction (previousGraph )
45
+
46
+ header := true
47
+
48
+ for {
49
+ record , err := r .Read ()
50
+ if err == io .EOF {
51
+ break
52
+ }
53
+ if err != nil {
54
+ return fmt .Errorf ("Unable to read data in CSV file: %v" , err )
55
+ }
56
+
57
+ // Skip header line
58
+ if header {
59
+ header = false
60
+ continue
61
+ }
62
+
63
+ relationType := graphkb.RelationType {
64
+ FromType : graphkb .AssetType (record [0 ]),
65
+ ToType : graphkb .AssetType (record [3 ]),
66
+ Type : graphkb .RelationKeyType (record [2 ]),
67
+ }
68
+
69
+ tx .Relate (record [1 ], relationType , record [4 ])
70
+ }
71
+
72
+ _ , err = tx .Commit ()
73
+ fmt .Println ("CSV data has been sent successfully" )
74
+ return err
75
+ }
76
+
77
+ func (cs * CSVSource ) Stop () error {
78
+ return nil
79
+ }
80
+
13
81
// ConfigPath string
14
82
var ConfigPath string
15
83
@@ -30,7 +98,7 @@ func main() {
30
98
rootCmd := & cobra.Command {
31
99
Use : "source-csv [opts]" ,
32
100
Run : func (cmd * cobra.Command , args []string ) {
33
- if err := importer .Start (sources . NewCSVSource (), nil ); err != nil {
101
+ if err := graphkb .Start (NewCSVSource (), nil ); err != nil {
34
102
log .Fatal (err )
35
103
}
36
104
},
0 commit comments