-
Notifications
You must be signed in to change notification settings - Fork 0
/
filesystem.go
244 lines (199 loc) · 6.43 KB
/
filesystem.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
// Defining a new public type 'Filesystem'
type Filesystem int
// Defining a global varaiable for Filesystem
var filesystem Filesystem
// ********** Public Filesystem methods **********
// Check if the file (or directory) exists at the given path.
func (f *Filesystem) Exists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
// Check if a file with the given name exists in the given directory.
func (f *Filesystem) ExistsRecursive(fileName string, directory string) (bool, error) {
var exists bool
err := filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err // return any error encountered
}
// Check if the current file matches the fileName
if filepath.Base(path) == fileName {
exists = true
return filepath.SkipDir // Stop walking as we've found the file
}
return nil
})
if err != nil {
return false, err // return any error encountered during walking
}
return exists, nil
}
// Create a file or directory based on the given path and content.
func (f *Filesystem) Create(path string, content string) error {
// Check if the path exists using checkPath
if f.Exists(path) {
errorMessage := path + " already exists"
return errors.New(errorMessage)
}
// Determine if the path is for a file or directory and create accordingly
if filepath.Ext(path) != "" {
return f.createFile(path, content)
}
return f.createDirectory(path)
}
// Return the content of the file at the given path.
func (f *Filesystem) Read(path string) (string, error) {
// Check if the path exists
if !f.Exists(path) {
warningMessage := path + " doesn't exist"
logger.Warn(warningMessage)
return "", errors.New(warningMessage)
}
// Read the file
content, err := os.ReadFile(path)
if err != nil {
return "", err
}
return string(content), nil
}
// Remove a file or directory at the given path.
func (f *Filesystem) Delete(path string) error {
// Check if the path exists
if !f.Exists(path) {
warningMessage := path + " doesn't exist"
logger.Warn(warningMessage)
return errors.New(warningMessage)
}
// Delete the file or directory
return os.RemoveAll(path)
}
// Check if the given path is a directory.
func (f *Filesystem) IsDir(path string) (bool, error) {
cwd, err := os.Getwd()
if err != nil {
return false, err
}
absPath := filepath.Join(cwd, path)
fileInfo, err := os.Stat(absPath)
if err != nil {
return false, err
}
return fileInfo.IsDir(), nil
}
// Basic YAML format parser that reads the content & returns a map of the data.
// We use this instead of loading the YAML modules to keep the size down
func (f *Filesystem) ParseYml(content string) (map[string]string, error) {
// Check for empty content
if content == "" {
return nil, errors.New("parsing failed: empty yaml content")
}
scanner := bufio.NewScanner(strings.NewReader(content))
ymlMap := make(map[string]string)
for scanner.Scan() {
line := scanner.Text()
parts := strings.SplitN(line, ":", 2)
if len(parts) != 2 {
// Log a warning for invalid lines
logger.Warn("Invalid YAML line:", line)
continue // Skip invalid lines
}
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
ymlMap[key] = value
}
if err := scanner.Err(); err != nil {
return nil, err
}
// Check for empty parsed map, indicating potential parsing issues
if len(ymlMap) == 0 {
return nil, errors.New("parsing failed: invalid yaml structure")
}
return ymlMap, nil
}
// Get information about the file at the given path.
func (f *Filesystem) GetFileInfo(rootDir string, path string) (relPath string, dir string, firstSubdir string, fileName string, extension string, err error) {
// Check if the rootDir is a directory
isRootDirDir, err := f.IsDir(rootDir)
if err != nil {
return "", "", "", "", "", fmt.Errorf("error checking rootDir: %s, error: %v", rootDir, err)
}
if !isRootDirDir {
return "", "", "", "", "", fmt.Errorf("rootDir is not a directory: %s", rootDir)
}
// Check if the path exists using the Filesystem's Exists method
if !f.Exists(path) {
return "", "", "", "", "", fmt.Errorf("path does not exist: %s", path)
}
// Ensure the path is not a directory using IsDir
isPathDir, err := f.IsDir(path)
if err != nil {
return "", "", "", "", "", fmt.Errorf("error checking path: %s, error: %v", path, err)
}
if isPathDir {
return "", "", "", "", "", fmt.Errorf("path is a directory: %s", path)
}
// Get the relative path from the root directory using filepath.Rel
relPath, err = filepath.Rel(rootDir, path)
if err != nil {
return "", "", "", "", "", fmt.Errorf("error getting relative path: %s, error: %v", path, err)
}
// Extract the directory using filepath.Dir
dir = filepath.Dir(relPath)
// If is is the current directory, set it to an empty string
if dir == "." {
dir = ""
}
// Split the relative path into components based on the file separator
components := strings.Split(relPath, string(filepath.Separator))
// Extract the first subdirectory (if it exists)
if len(components) > 1 {
firstSubdir = components[0]
} else {
firstSubdir = ""
}
// Get the filename from the relative path using filepath.Base
fullfileName := filepath.Base(relPath)
// Get the file extension using filepath.Ext and remove the leading dot
extension = filepath.Ext(fullfileName)
if extension != "" {
extension = extension[1:]
}
// Get the filename without the extension
fileName = strings.TrimSuffix(fullfileName, "."+extension)
return relPath, dir, firstSubdir, fileName, extension, nil
}
// ********** Private Filesystem methods **********
// Creates a file with the given path and writes content to it.
// It ensures that the parent directories exist before creating the file.
func (f *Filesystem) createFile(path string, content string) error {
// Get the parent directory of the path
parentDir := filepath.Dir(path)
// Check if the parent directory exists, create it if not
if !f.Exists(parentDir) {
if err := f.createDirectory(parentDir); err != nil {
return err
}
}
// Create the file
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
// Write content to the file
_, err = file.WriteString(content)
return err
}
// Creates a directory at the given path.
// It is recursive and can create the entire parent directory structure if needed.
func (f *Filesystem) createDirectory(path string) error {
return os.MkdirAll(path, 0755)
}