github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/file/folder.go (about) 1 // Copyright 2021 The TrueBlocks Authors. All rights reserved. 2 // Use of this source code is governed by a license that can 3 // be found in the LICENSE file. 4 5 package file 6 7 import ( 8 "fmt" 9 "io" 10 "os" 11 "path/filepath" 12 "strings" 13 ) 14 15 func IsFolderEmpty(folder string) (bool, error) { 16 f, err := os.OpenFile(folder, os.O_RDONLY, 0) 17 if err != nil { 18 return false, err 19 } 20 defer f.Close() 21 _, err = f.Readdirnames(1) 22 if err == io.EOF { 23 return true, nil 24 } 25 return false, err // Either not empty or error, suits both cases 26 } 27 28 // CleanFolder removes any files that may be partial or incomplete 29 func CleanFolder(chain, rootFolder string, subFolders []string) error { 30 for _, f := range subFolders { 31 folder := filepath.Join(rootFolder, f) 32 // We want to remove whatever is there... 33 err := os.RemoveAll(folder) 34 if err != nil { 35 return err 36 } 37 // ...but put it back 38 _ = EstablishFolder(folder) 39 } 40 41 return nil 42 } 43 44 // IsValidFolderName checks if the folder name is valid and does not exist in the current directory. 45 func IsValidFolderName(folderName string) (bool, error) { 46 // Check for invalid characters (example for a simple Unix-like rule) 47 // You might need a more specific check depending on your OS requirements. 48 if strings.ContainsAny(folderName, "/<>:\"\\|?*") { 49 return false, fmt.Errorf("folder name contains invalid characters") 50 } 51 52 // Check if folder exists 53 if _, err := os.Stat(folderName); err == nil { 54 return false, fmt.Errorf("folder already exists") 55 } else if !os.IsNotExist(err) { 56 return false, err // some other error occurred when checking the folder 57 } 58 59 return true, nil 60 }