fix: mkdir when creat file

pull/125/head
ᴍᴏᴏɴD4ʀᴋ 3 years ago
parent 4551931c89
commit 580ff78ad3
  1. 17
      internal/outputter/outputter.go
  2. 22
      internal/outputter/outputter_test.go

@ -28,14 +28,7 @@ func NewOutPutter(flag string) *outPutter {
return o
}
func (o *outPutter) MakeDir(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
return os.Mkdir(dir, 0777)
}
return nil
}
func (o *outPutter) Write(data browingdata.Source, writer *os.File) error {
func (o *outPutter) Write(data browingdata.Source, writer io.Writer) error {
switch o.json {
case true:
encoder := jsoniter.NewEncoder(writer)
@ -48,17 +41,15 @@ func (o *outPutter) Write(data browingdata.Source, writer *os.File) error {
writer.Comma = ','
return gocsv.NewSafeCSVWriter(writer)
})
return gocsv.MarshalFile(data, writer)
return gocsv.Marshal(data, writer)
}
}
func (o *outPutter) CreateFile(dirname, filename string) (*os.File, error) {
func (o *outPutter) CreateFile(dir, filename string) (*os.File, error) {
if filename == "" {
return nil, errors.New("empty filename")
}
dir := filepath.Dir(filename)
if dir != "" {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, 0777)
@ -70,7 +61,7 @@ func (o *outPutter) CreateFile(dirname, filename string) (*os.File, error) {
var file *os.File
var err error
p := filepath.Join(dirname, filename)
p := filepath.Join(dir, filename)
file, err = os.OpenFile(p, os.O_TRUNC|os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return nil, err

@ -0,0 +1,22 @@
package outputter
import (
"os"
"testing"
)
func TestNewOutPutter(t *testing.T) {
out := NewOutPutter("json")
if out == nil {
t.Error("NewOutPutter() returned nil")
}
f, err := out.CreateFile("results", "test.json")
if err != nil {
t.Error("CreateFile() returned an error", err)
}
defer os.RemoveAll("results")
err = out.Write(nil, f)
if err != nil {
t.Error("Write() returned an error", err)
}
}
Loading…
Cancel
Save