-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
597 lines (487 loc) · 14 KB
/
file.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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
package g
import (
"bufio"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"github.com/enetx/g/internal/filelock"
)
// NewFile returns a new File instance with the given name.
func NewFile(name String) *File { return &File{name: name} }
// Lines returns a new iterator instance that can be used to read the file
// line by line.
//
// Example usage:
//
// // Open a new file with the specified name "text.txt"
// g.NewFile("text.txt").
// Lines(). // Read the file line by line
// Unwrap(). // Unwrap the Result type to get the underlying iterator
// Skip(3). // Skip the first 3 lines
// Exclude(f.Zero). // Exclude lines that are empty or contain only whitespaces
// Dedup(). // Remove consecutive duplicate lines
// Map(g.String.Upper). // Convert each line to uppercase
// ForEach( // For each line, print it
// func(s g.String) {
// s.Print()
// })
//
// // Output:
// // UPPERCASED_LINE4
// // UPPERCASED_LINE5
// // UPPERCASED_LINE6
func (f *File) Lines() Result[SeqSlice[String]] {
if f.file == nil {
if r := f.Open(); r.IsErr() {
return Err[SeqSlice[String]](r.Err())
}
}
return Ok(SeqSlice[String](func(yield func(String) bool) {
defer f.Close()
scanner := bufio.NewScanner(f.file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
if !yield(String(scanner.Text())) {
return
}
}
}))
}
// Chunks returns a new iterator instance that can be used to read the file
// in fixed-size chunks of the specified size in bytes.
//
// Parameters:
//
// - size (int): The size of each chunk in bytes.
//
// Example usage:
//
// // Open a new file with the specified name "text.txt"
// g.NewFile("text.txt").
// Chunks(100). // Read the file in chunks of 100 bytes
// Unwrap(). // Unwrap the Result type to get the underlying iterator
// Map(g.String.Upper). // Convert each chunk to uppercase
// ForEach( // For each chunk, print it
// func(s g.String) {
// s.Print()
// })
//
// // Output:
// // UPPERCASED_CHUNK1
// // UPPERCASED_CHUNK2
// // UPPERCASED_CHUNK3
func (f *File) Chunks(size Int) Result[SeqSlice[String]] {
if f.file == nil {
if r := f.Open(); r.IsErr() {
return Err[SeqSlice[String]](r.Err())
}
}
return Ok(SeqSlice[String](func(yield func(String) bool) {
defer f.Close()
buffer := make([]byte, size)
for {
n, err := f.file.Read(buffer)
if err != nil && err != io.EOF {
return
}
if n == 0 {
break
}
if !yield(String(buffer[:n])) {
return
}
}
}))
}
// Append appends the given content to the file, with the specified mode (optional).
// If no FileMode is provided, the default FileMode (0644) is used.
// Don't forget to close the file!
func (f *File) Append(content String, mode ...os.FileMode) Result[*File] {
if f.file == nil {
if r := f.createAll(); r.IsErr() {
return r
}
fmode := FileDefault
if len(mode) != 0 {
fmode = mode[0]
}
if r := f.OpenFile(os.O_APPEND|os.O_CREATE|os.O_WRONLY, fmode); r.IsErr() {
return r
}
}
if _, err := f.file.WriteString(content.Std()); err != nil {
return Err[*File](err)
}
return Ok(f)
}
// Chmod changes the mode of the file.
func (f *File) Chmod(mode os.FileMode) Result[*File] {
var err error
if f.file != nil {
err = f.file.Chmod(mode)
} else {
err = os.Chmod(f.name.Std(), mode)
}
if err != nil {
return Err[*File](err)
}
return Ok(f)
}
// Chown changes the owner of the file.
func (f *File) Chown(uid, gid int) Result[*File] {
var err error
if f.file != nil {
err = f.file.Chown(uid, gid)
} else {
err = os.Chown(f.name.Std(), uid, gid)
}
if err != nil {
return Err[*File](err)
}
return Ok(f)
}
// Seek sets the file offset for the next Read or Write operation. The offset
// is specified by the 'offset' parameter, and the 'whence' parameter determines
// the reference point for the offset.
//
// The 'offset' parameter specifies the new offset in bytes relative to the
// reference point determined by 'whence'. If 'whence' is set to io.SeekStart,
// io.SeekCurrent, or io.SeekEnd, the offset is relative to the start of the file,
// the current offset, or the end of the file, respectively.
//
// If the file is not open, this method will attempt to open it. If the open
// operation fails, an error is returned.
//
// If the Seek operation fails, the file is closed, and an error is returned.
//
// Example:
//
// file := g.NewFile("example.txt")
// result := file.Seek(100, io.SeekStart)
// if result.Err() != nil {
// log.Fatal(result.Err())
// }
//
// Parameters:
// - offset: The new offset in bytes.
// - whence: The reference point for the offset (io.SeekStart, io.SeekCurrent, or io.SeekEnd).
//
// Don't forget to close the file!
func (f *File) Seek(offset int64, whence int) Result[*File] {
if f.file == nil {
if r := f.Open(); r.IsErr() {
return r
}
}
if _, err := f.file.Seek(offset, whence); err != nil {
f.Close()
return Err[*File](err)
}
return Ok(f)
}
// Close closes the File and unlocks its underlying file, if it is not already closed.
func (f *File) Close() error {
if f.file == nil {
return &ErrFileClosed{f.name.Std()}
}
var err error
if f.guard {
err = filelock.Unlock(f.file)
}
if closeErr := f.file.Close(); closeErr != nil {
err = closeErr
}
f.file = nil
return err
}
// Copy copies the file to the specified destination, with the specified mode (optional).
// If no mode is provided, the default FileMode (0644) is used.
func (f *File) Copy(dest String, mode ...os.FileMode) Result[*File] {
if r := f.Open(); r.IsErr() {
return r
}
defer f.Close()
return NewFile(dest).WriteFromReader(f.file, mode...)
}
// Create is similar to os.Create, but it returns a write-locked file.
// Don't forget to close the file!
func (f *File) Create() Result[*File] {
return f.OpenFile(os.O_RDWR|os.O_CREATE|os.O_TRUNC, FileCreate)
}
// Dir returns the directory the file is in as an Dir instance.
func (f *File) Dir() Result[*Dir] {
dirPath := f.dirPath()
if dirPath.IsErr() {
return Err[*Dir](dirPath.Err())
}
return Ok(NewDir(dirPath.Ok()))
}
// Exist checks if the file exists.
func (f *File) Exist() bool {
if f.dirPath().IsOk() {
filePath := f.filePath()
if filePath.IsOk() {
_, err := os.Stat(filePath.Ok().Std())
return !os.IsNotExist(err)
}
}
return false
}
// Ext returns the file extension.
func (f *File) Ext() String { return String(filepath.Ext(f.name.Std())) }
// Guard sets a lock on the file to protect it from concurrent access.
// It returns the File instance with the guard enabled.
func (f *File) Guard() *File {
f.guard = true
return f
}
// MimeType returns the MIME type of the file as an String.
func (f *File) MimeType() Result[String] {
if r := f.Open(); r.IsErr() {
return Err[String](r.Err())
}
defer f.Close()
const bufferSize = 512
buff := make([]byte, bufferSize)
bytesRead, err := f.file.ReadAt(buff, 0)
if err != nil && err != io.EOF {
return Err[String](err)
}
buff = buff[:bytesRead]
return Ok(String(http.DetectContentType(buff)))
}
// Move function simply calls [File.Rename]
func (f *File) Move(newpath String) Result[*File] { return f.Rename(newpath) }
// Name returns the name of the file.
func (f *File) Name() String {
if f.file != nil {
return String(filepath.Base(f.file.Name()))
}
return String(filepath.Base(f.name.Std()))
}
// Open is like os.Open, but returns a read-locked file.
// Don't forget to close the file!
func (f *File) Open() Result[*File] { return f.OpenFile(os.O_RDONLY, 0) }
// OpenFile is like os.OpenFile, but returns a locked file.
// If flag includes os.O_WRONLY or os.O_RDWR, the file is write-locked
// otherwise, it is read-locked.
// Don't forget to close the file!
func (f *File) OpenFile(flag int, perm fs.FileMode) Result[*File] {
file, err := os.OpenFile(f.name.Std(), flag&^os.O_TRUNC, perm)
if err != nil {
return Err[*File](err)
}
if f.guard {
switch flag & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR) {
case os.O_WRONLY, os.O_RDWR:
err = filelock.Lock(file)
default:
err = filelock.RLock(file)
}
if err != nil {
file.Close()
return Err[*File](err)
}
}
if flag&os.O_TRUNC == os.O_TRUNC {
if err := file.Truncate(0); err != nil {
if fi, statErr := file.Stat(); statErr != nil || fi.Mode().IsRegular() {
if f.guard {
filelock.Unlock(file)
}
file.Close()
return Err[*File](err)
}
}
}
f.file = file
return Ok(f)
}
// Path returns the absolute path of the file.
func (f *File) Path() Result[String] { return f.filePath() }
// Print prints the content of the File to the standard output (console)
// and returns the File unchanged.
func (f *File) Print() *File { fmt.Println(f); return f }
// Read opens the named file with a read-lock and returns its contents.
func (f *File) Read() Result[String] {
if r := f.Open(); r.IsErr() {
return Err[String](r.Err())
}
defer f.Close()
content, err := io.ReadAll(f.file)
if err != nil {
return Err[String](err)
}
return Ok(String(content))
}
// Remove removes the file.
func (f *File) Remove() Result[*File] {
if err := os.Remove(f.name.Std()); err != nil {
return Err[*File](err)
}
return Ok(f)
}
// Rename renames the file to the specified new path.
func (f *File) Rename(newpath String) Result[*File] {
if !f.Exist() {
return Err[*File](&ErrFileNotExist{f.name.Std()})
}
nf := NewFile(newpath).createAll()
if err := os.Rename(f.name.Std(), newpath.Std()); err != nil {
return Err[*File](err)
}
return nf
}
// Split splits the file path into its directory and file components.
func (f *File) Split() (*Dir, *File) {
path := f.Path()
if path.IsErr() {
return nil, nil
}
dir, file := filepath.Split(path.Ok().Std())
return NewDir(String(dir)), NewFile(String(file))
}
// Stat returns the fs.FileInfo of the file.
// It calls the file's Stat method if the file is open, or os.Stat otherwise.
func (f *File) Stat() Result[fs.FileInfo] {
if f.file != nil {
return ResultOf(f.file.Stat())
}
return ResultOf(os.Stat(f.name.Std()))
}
// Lstat retrieves information about the symbolic link represented by the *File instance.
// It returns a Result[fs.FileInfo] containing details about the symbolic link's metadata.
// Unlike Stat, Lstat does not follow the link and provides information about the link itself.
func (f *File) Lstat() Result[fs.FileInfo] {
return ResultOf(os.Lstat(f.name.Std()))
}
// IsDir checks if the file is a directory.
func (f *File) IsDir() bool {
stat := f.Stat()
return stat.IsOk() && stat.Ok().IsDir()
}
// IsLink checks if the file is a symbolic link.
func (f *File) IsLink() bool {
stat := f.Lstat()
return stat.IsOk() && stat.Ok().Mode()&os.ModeSymlink != 0
}
// Std returns the underlying *os.File instance.
// Don't forget to close the file with g.File().Close()!
func (f *File) Std() *os.File { return f.file }
// CreateTemp creates a new temporary file in the specified directory with the
// specified name pattern and returns a Result, which contains a pointer to the File
// or an error if the operation fails.
// If no directory is specified, the default directory for temporary files is used.
// If no name pattern is specified, the default pattern "*" is used.
//
// Parameters:
//
// - args ...String: A variadic parameter specifying the directory and/or name
// pattern for the temporary file.
//
// Returns:
//
// - *File: A pointer to the File representing the temporary file.
//
// Example usage:
//
// f := g.NewFile("")
// tmpfile := f.CreateTemp() // Creates a temporary file with default settings
// tmpfileWithDir := f.CreateTemp("mydir") // Creates a temporary file in "mydir" directory
// tmpfileWithPattern := f.CreateTemp("", "tmp") // Creates a temporary file with "tmp" pattern
func (*File) CreateTemp(args ...String) Result[*File] {
dir := ""
pattern := "*"
if len(args) != 0 {
if len(args) > 1 {
pattern = args[1].Std()
}
dir = args[0].Std()
}
tmpfile, err := os.CreateTemp(dir, pattern)
if err != nil {
return Err[*File](err)
}
ntmpfile := NewFile(String(tmpfile.Name()))
ntmpfile.file = tmpfile
defer ntmpfile.Close()
return Ok(ntmpfile)
}
// Write opens the named file (creating it with the given permissions if needed),
// then write-locks it and overwrites it with the given content.
func (f *File) Write(content String, mode ...os.FileMode) Result[*File] {
return f.WriteFromReader(content.Reader(), mode...)
}
// WriteFromReader takes an io.Reader (scr) as input and writes the data from the reader into the file.
// If no FileMode is provided, the default FileMode (0644) is used.
func (f *File) WriteFromReader(scr io.Reader, mode ...os.FileMode) Result[*File] {
if f.file == nil {
if r := f.createAll(); r.IsErr() {
return r
}
}
fmode := FileDefault
if len(mode) != 0 {
fmode = mode[0]
}
filePath := f.filePath()
if filePath.IsErr() {
return Err[*File](filePath.Err())
}
f = NewFile(filePath.Ok())
if r := f.OpenFile(os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fmode); r.IsErr() {
return Err[*File](r.Err())
}
defer f.Close()
_, err := io.Copy(f.file, scr)
if err != nil {
return Err[*File](err)
}
err = f.file.Sync()
if err != nil {
return Err[*File](err)
}
return Ok(f)
}
// dirPath returns the absolute path of the directory containing the file.
func (f *File) dirPath() Result[String] {
var (
path string
err error
)
if f.IsDir() {
path, err = filepath.Abs(f.name.Std())
} else {
path, err = filepath.Abs(filepath.Dir(f.name.Std()))
}
if err != nil {
return Err[String](err)
}
return Ok(String(path))
}
// filePath returns the full file path, including the directory and file name.
func (f *File) filePath() Result[String] {
dirPath := f.dirPath()
if dirPath.IsErr() {
return Err[String](dirPath.Err())
}
if f.IsDir() {
return dirPath
}
return Ok(String(filepath.Join(dirPath.Ok().Std(), filepath.Base(f.name.Std()))))
}
func (f *File) createAll() Result[*File] {
dirPath := f.dirPath()
if dirPath.IsErr() {
return Err[*File](dirPath.Err())
}
if !f.Exist() {
if err := os.MkdirAll(dirPath.Ok().Std(), DirDefault); err != nil {
return Err[*File](err)
}
}
return Ok(f)
}