1 // Package apputil provides utility functions for file and directory operations.
2 package apputil
3 4 import (
5 "os"
6 "path/filepath"
7 8 "next.orly.dev/pkg/lol/chk"
9 )
10 11 // EnsureDir checks if a file could be written to a path and creates the
12 // necessary directories if they don't exist. It ensures that all parent
13 // directories in the path are created with the appropriate permissions.
14 //
15 // # Parameters
16 //
17 // - fileName: The full path to the file for which directories need to be
18 // created.
19 //
20 // Expected behavior:
21 //
22 // - Extracts the directory path from the fileName.
23 //
24 // - Checks if the directory exists.
25 //
26 // - If the directory doesn't exist, creates it and all parent directories.
27 func EnsureDir(fileName string) (merr error) {
28 dirName := filepath.Dir(fileName)
29 if _, err := os.Stat(dirName); chk.E(err) {
30 merr = os.MkdirAll(dirName, os.ModePerm)
31 if chk.E(merr) {
32 return
33 }
34 return
35 }
36 return
37 }
38 39 // FileExists reports whether the named file or directory exists.
40 //
41 // # Parameters
42 //
43 // - filePath: The full path to the file or directory to check.
44 //
45 // Returns:
46 //
47 // - bool: true if the file or directory exists, false otherwise.
48 //
49 // Behavior:
50 //
51 // - Uses os.Stat to check if the file or directory exists.
52 //
53 // - Returns true if the file exists and can be accessed.
54 //
55 // - Returns false if the file doesn't exist or cannot be accessed due to
56 // permissions.
57 func FileExists(filePath string) bool {
58 _, e := os.Stat(filePath)
59 return e == nil
60 }
61