From 854023ed16389ac9ddb661a89dd2c12e34146d61 Mon Sep 17 00:00:00 2001 From: Ivan Styazhkin Date: Tue, 27 Aug 2024 07:45:29 -0700 Subject: [PATCH] Create all directories before creating a new file (#511) Summary: From the golang 1.23 os/file.go ``` // Flags to OpenFile wrapping those of the underlying system. Not all // flags may be implemented on a given system. const ( // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified. O_RDONLY int = syscall.O_RDONLY // open the file read-only. O_WRONLY int = syscall.O_WRONLY // open the file write-only. O_RDWR int = syscall.O_RDWR // open the file read-write. // The remaining values may be or'ed in to control behavior. O_APPEND int = syscall.O_APPEND // append data to the file when writing. O_CREATE int = syscall.O_CREAT // create a new file if none exists. O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist. O_SYNC int = syscall.O_SYNC // open for synchronous I/O. O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened. ) ``` Which makes me think that we might want to call MkdirAll function before creating a file Pull Request resolved: https://github.com/facebookincubator/TTPForge/pull/511 Resolves https://github.com/facebookincubator/TTPForge/issues/506 Differential Revision: D61658174 fbshipit-source-id: b0352f44335f19773854170df787292676cf5a8e --- pkg/blocks/createfile.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pkg/blocks/createfile.go b/pkg/blocks/createfile.go index fbd6b726..aec1a3f0 100755 --- a/pkg/blocks/createfile.go +++ b/pkg/blocks/createfile.go @@ -22,6 +22,7 @@ package blocks import ( "fmt" "os" + "path/filepath" "github.com/facebookincubator/ttpforge/pkg/fileutils" "github.com/facebookincubator/ttpforge/pkg/logging" @@ -94,6 +95,17 @@ func (s *CreateFileStep) Execute(_ TTPExecutionContext) (*ActResult, error) { mode = 0666 } + dir := filepath.Dir(pathToCreate) + exists, err = afero.Exists(fsys, dir) + if err != nil { + return nil, err + } + if !exists { + if err = fsys.MkdirAll(dir, os.ModePerm); err != nil { + return nil, err + } + } + // actually write the file f, err := fsys.OpenFile(pathToCreate, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(mode)) if err != nil {