From 899793d2931038ed3985de00e15fd81fc58ded15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=B4=8D=E1=B4=8F=E1=B4=8F=C9=B4D4=CA=80=E1=B4=8B?= Date: Sun, 10 Apr 2022 18:34:38 +0800 Subject: [PATCH] fix: mkdir when creat file --- internal/outputter/outputter.go | 17 ++++------------- internal/outputter/outputter_test.go | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 13 deletions(-) create mode 100644 internal/outputter/outputter_test.go diff --git a/internal/outputter/outputter.go b/internal/outputter/outputter.go index dc45498..ece26f0 100644 --- a/internal/outputter/outputter.go +++ b/internal/outputter/outputter.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 diff --git a/internal/outputter/outputter_test.go b/internal/outputter/outputter_test.go new file mode 100644 index 0000000..ed37e85 --- /dev/null +++ b/internal/outputter/outputter_test.go @@ -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) + } +}