-
Notifications
You must be signed in to change notification settings - Fork 224
/
fs.go
100 lines (83 loc) · 1.98 KB
/
fs.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
package logfile
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/superfly/flyctl/helpers"
)
func logDir() (string, error) {
configDir, err := helpers.GetConfigDirectory()
if err != nil {
return "", err
}
dir := filepath.Join(configDir, "logs")
dirStat, err := os.Stat(dir)
if err == nil && !dirStat.IsDir() {
return "", fmt.Errorf("%s is not a directory", dir)
} else if err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
} else {
return "", err
}
}
return dir, nil
}
// retainLogs ensures that the number of logs in the logs directory is less than or equal to keepLogs.
func retainLogs(logsDir string) error {
type logEntry struct {
path string
time time.Time
}
var matchingLogs []logEntry
// Iterate through the log directory, and take note of all log files fitting the flyctl-*.log pattern.
err := filepath.Walk(logsDir, func(path string, info os.FileInfo, err error) error {
if filepath.Ext(path) == ".log" && strings.HasPrefix(info.Name(), "flyctl-") {
date, err := parseLogName(info.Name())
if err != nil {
return err
}
matchingLogs = append(matchingLogs, logEntry{
path: path,
time: date,
})
}
return nil
})
if err != nil {
return err
}
// Sort logs by timestamp
sort.Slice(matchingLogs, func(i, j int) bool {
return matchingLogs[i].time.After(matchingLogs[j].time)
})
// Delete all but the most recent [keepLogs] logs
var lastErr error
for i := keepLogs; i < len(matchingLogs); i++ {
if err := os.Remove(matchingLogs[i].path); err != nil {
lastErr = err
}
}
return lastErr
}
func CreateLogFile() (*os.File, error) {
logsDir, err := logDir()
if err != nil {
return nil, err
}
fileName := formatLogName(time.Now())
filePath := filepath.Join(logsDir, fileName)
rawFile, err := os.Create(filePath)
if err != nil {
return nil, err
}
if err := retainLogs(logsDir); err != nil {
return nil, err
}
return rawFile, nil
}