-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.go
More file actions
325 lines (285 loc) · 8.09 KB
/
file.go
File metadata and controls
325 lines (285 loc) · 8.09 KB
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package filechick
import (
"bufio"
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"github.com/spf13/afero"
"github.com/spf13/viper"
)
var Afero = afero.Afero{Fs: afero.NewOsFs()}
// CreateEmptyFile creates an empty file.
// Returns the file pointer and an error if any.
func CreateEmptyFile(fileName string) (*os.File, error) {
file, err := os.Create(fileName)
if err != nil {
return nil, err
}
return file, nil
}
// DeleteFile deletes the specified file.
// Returns an error if the operation fails.
func DeleteFile(file string) error {
err := os.RemoveAll(file)
if err != nil {
return fmt.Errorf("error deleting file: %w", err)
}
return nil
}
// SaveHtml saves HTML content from a URL to a specified file.
// Returns an error if the operation fails.
func SaveHtml(url string, fileName string) error {
// Validate URL
if _, err := regexp.Compile(url); err != nil { // Changed from http.ParseRequestURI to regexp.Compile
return fmt.Errorf("invalid URL: %w", err)
}
// Create the file
file := CreateFile(fileName) // Changed to only assign the file
if file == nil {
return fmt.Errorf("error creating file") // Updated error handling
}
defer file.Close()
// Get HTML content
ctx := context.Background() // Create a context
res, reqErr := CustomRequest(ctx, url, &http.Client{}) // Updated to include context and http.Client
if reqErr != nil {
return fmt.Errorf("error getting HTML from URL: %w", reqErr)
}
// Write to file
if _, fileErr := file.WriteString(res); fileErr != nil {
return fmt.Errorf("error writing to file: %w", fileErr)
}
return nil
}
// CreateFile creates a file.
// Returns the file pointer and an error if any.
func CreateFile(fileName string) *os.File {
file, err := os.Create(fileName)
if err != nil {
fmt.Println("Error creating file", err)
return nil
}
return file
}
// LoadHtml loads HTML content from a file to a string.
// Returns the HTML content as a string and an error if any.
func LoadHtml(file string) (string, error) {
// Open the file
f, err := os.Open(file)
if err != nil {
return "", fmt.Errorf("error opening file: %w", err)
}
defer f.Close()
// Read the file
bytes, err2 := io.ReadAll(f)
if err2 != nil {
return "", fmt.Errorf("error reading file: %w", err2)
}
// Turn result into a string
return string(bytes), nil
}
// NewDir creates a new directory.
// Returns an error if the operation fails.
func NewDir(dir string) error {
// If directory doesn't exist, create it
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.Mkdir(dir, 0755)
if err != nil {
return fmt.Errorf("error creating directory: %w", err)
}
} else if err != nil {
return fmt.Errorf("error creating directory: %w", err)
}
return nil
}
// ExitIfExists exits the program if the file already exists.
func ExitIfExists(dir string) {
if _, err := os.Stat(dir); !os.IsNotExist(err) {
fmt.Println("Filechick detected that you already have this file downloaded. Exiting...")
os.Exit(0)
}
}
// SaveImage saves an image from a URL to a file.
// Returns an error if the operation fails.
func SaveImage(url string, filename string) error {
// Get the image
results, err := http.Get(url)
if err != nil {
return fmt.Errorf("error getting image: %w", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
fmt.Println("Error closing body:", err)
}
}(results.Body)
// Create an empty file
emptyFile, err := CreateEmptyFile(filename)
if err != nil {
return fmt.Errorf("error creating file: %w", err)
}
defer emptyFile.Close()
// Copy the image to the file
_, copyErr := io.Copy(emptyFile, results.Body)
if copyErr != nil {
return fmt.Errorf("error copying file: %w", copyErr)
}
return nil
}
// TitleToDirName converts a title to a directory name.
// Returns the directory name as a string.
func TitleToDirName(title string) string {
reg := regexp.MustCompile(`[^a-zA-Z\d]+`) // Changed to raw string
return reg.ReplaceAllString(title, "")
}
// RemoveIfExists removes a file if it exists.
// Returns an error if the operation fails.
func RemoveIfExists(path string) error {
exists, err := Afero.Exists(path)
if err != nil {
return fmt.Errorf("error checking file existence: %w", err)
}
if exists {
err = Afero.Remove(path)
if err != nil {
return fmt.Errorf("error removing file: %w", err)
}
}
return nil
}
// GetFileNames returns a slice of strings containing all the file names in a directory.
// Returns an error if the operation fails.
func GetFileNames(dir string) ([]string, error) {
files, err := Afero.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("error reading directory: %w", err)
}
var fileNames []string
for _, file := range files {
fileNames = append(fileNames, file.Name())
}
return fileNames, nil
}
// FileOrDirExists checks if a file or directory exists.
// Returns true if the file or directory exists, false otherwise.
func FileOrDirExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// CopyFile copies a file from the source to the destination.
// Returns an error if the operation fails.
func CopyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return fmt.Errorf("error opening source file: %w", err)
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return fmt.Errorf("error creating destination file: %w", err)
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return fmt.Errorf("error copying file: %w", err)
}
return out.Close()
}
// ReadFileLineByLine reads a file line by line.
// Returns a slice of strings containing the file lines and an error if any.
func ReadFileLineByLine(filePath string) ([]string, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("error opening file: %w", err)
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error scanning file: %w", err)
}
return lines, nil
}
// VippyEnv gets an environment variable value using viper.
// Returns the value as a string.
func VippyEnv(key string) string {
// Use viper to get the value from the environment variable
vippy := viper.New()
vippy.SetConfigName(".env")
vippy.SetConfigType("env")
vippy.AddConfigPath(".")
vippy.AllowEmptyEnv(false)
vippy.AutomaticEnv()
err := vippy.ReadInConfig()
if err != nil {
log.Fatal("Error reading env file: ", err)
}
return vippy.GetString(key)
}
// RenameFile renames a file from oldName to newName.
// Returns an error if the operation fails.
func RenameFile(oldName string, newName string) error {
err := os.Rename(oldName, newName)
if err != nil {
return fmt.Errorf("error renaming file: %w", err)
}
return nil
}
// MoveFile moves a file from src to dst.
// Returns an error if the operation fails.
func MoveFile(src string, dst string) error {
err := os.Rename(src, dst)
if err != nil {
return fmt.Errorf("error moving file: %w", err)
}
return nil
}
// CopyDirectory copies all files from srcDir to dstDir.
// Returns an error if the operation fails.
func CopyDirectory(srcDir string, dstDir string) error {
entries, err := os.ReadDir(srcDir)
if err != nil {
return fmt.Errorf("error reading source directory: %w", err)
}
for _, entry := range entries {
srcPath := filepath.Join(srcDir, entry.Name())
dstPath := filepath.Join(dstDir, entry.Name())
if entry.IsDir() {
err = os.MkdirAll(dstPath, os.ModePerm)
if err != nil {
return fmt.Errorf("error creating directory: %w", err)
}
err = CopyDirectory(srcPath, dstPath)
if err != nil {
return err
}
} else {
err = CopyFile(srcPath, dstPath)
if err != nil {
return err
}
}
}
return nil
}
// ListFiles lists all files in the specified directory.
// Returns a slice of file names and an error if any.
func ListFiles(dir string) ([]string, error) {
files, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("error reading directory: %w", err)
}
var fileNames []string
for _, file := range files {
fileNames = append(fileNames, file.Name())
}
return fileNames, nil
}