forked from jonssonyan/h-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
88 lines (78 loc) · 1.78 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
package util
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
)
func Exists(path string) bool {
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
func RemoveFile(fileName string) error {
if Exists(fileName) {
if err := os.Remove(fileName); err != nil {
return errors.New("failed to delete file")
}
}
return nil
}
// ReadLinesFromBottom Read the file contents sequentially from bottom to top and return the specified number of lines
func ReadLinesFromBottom(filePath string, numLines int) ([]string, int, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, 0, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
// Read the file contents line by line and reverse the order of the lines
total := 0
for scanner.Scan() {
lines = append(lines, scanner.Text())
total++
}
if err := scanner.Err(); err != nil {
return nil, 0, err
}
// Reverse row order
for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {
lines[i], lines[j] = lines[j], lines[i]
}
// Returns the specified number of rows
if len(lines) < numLines {
numLines = len(lines)
}
return lines[:numLines], total, nil
}
func FindFile(dir, filename string) (string, error) {
var result string
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && info.Name() == filename {
absPath, err := filepath.Abs(path)
if err != nil {
return err
}
result = absPath
return errors.New("file found")
}
return nil
})
if err != nil && err.Error() != "file found" {
return "", err
}
if result == "" {
return "", fmt.Errorf("file %s not found in directory %s", filename, dir)
}
return result, nil
}