From 72cc77ef77589d94d1e98ffde428deed00f0a069 Mon Sep 17 00:00:00 2001 From: amorozov Date: Thu, 20 Jun 2024 15:06:24 +0300 Subject: [PATCH] feature: added FS utils --- pkg/io/files/file_open_helper.go | 15 +++++++++++++++ pkg/io/files/parent_file_creator.go | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 pkg/io/files/file_open_helper.go create mode 100644 pkg/io/files/parent_file_creator.go diff --git a/pkg/io/files/file_open_helper.go b/pkg/io/files/file_open_helper.go new file mode 100644 index 0000000..8bd95d4 --- /dev/null +++ b/pkg/io/files/file_open_helper.go @@ -0,0 +1,15 @@ +package files + +import ( + "os" +) + +func OpenFileForWriting(fileLocation string) (*os.File, error) { + err := MkdirParent(fileLocation) + + if err != nil { + return nil, err + } + + return os.Create(fileLocation) +} diff --git a/pkg/io/files/parent_file_creator.go b/pkg/io/files/parent_file_creator.go new file mode 100644 index 0000000..835863e --- /dev/null +++ b/pkg/io/files/parent_file_creator.go @@ -0,0 +1,21 @@ +package files + +import ( + "os" + "strings" +) + +func MkdirParent(fileLocation string) error { + fileLocation = strings.ReplaceAll(fileLocation, "\\", "/") + indexOfSlash := strings.LastIndex(fileLocation, "/") + if indexOfSlash > 0 { + parentDirLocation := fileLocation[:indexOfSlash] + parentDirCreationErr := os.MkdirAll(parentDirLocation, os.ModeDir) + + if parentDirCreationErr != nil { + return parentDirCreationErr + } + } + + return nil +}