fix: mkdir when creat file

pull/121/head
ᴍᴏᴏɴD4ʀᴋ 3 years ago
parent a6efcff6ea
commit 899793d293
  1. 17
      internal/outputter/outputter.go
  2. 22
      internal/outputter/outputter_test.go

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