/
data.go
290 lines (271 loc) · 6.23 KB
/
data.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
// Package data are various functions for the shrink package.
package data
import (
"database/sql"
"errors"
"fmt"
"io"
"log"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"github.com/Defacto2/df2/pkg/archive"
"github.com/Defacto2/df2/pkg/database"
"github.com/Defacto2/df2/pkg/str"
"github.com/dustin/go-humanize"
"github.com/gookit/color"
)
var (
ErrApprove = errors.New("cannot shrink files as there are database records waiting for public approval")
ErrDel = errors.New("delete errors")
ErrArcStore = errors.New("archive store error")
ErrUnknown = errors.New("unknown command")
)
// Months of the year.
type Months uint
const (
non Months = iota // Unknown or a non month.
jan
feb
mar
apr
may
jun
jul
aug
sep
oct
nov
dec
)
// Month returns the Months value of s, which should be a three letter English abbreviation.
func Month(s string) Months {
const monthPrefix = 3
if len(s) < monthPrefix {
return non
}
months := map[string]Months{
"jan": jan,
"feb": feb,
"mar": mar,
"apr": apr,
"may": may,
"jun": jun,
"jul": jul,
"aug": aug,
"sep": sep,
"oct": oct,
"nov": nov,
"dec": dec,
}
for prefix, val := range months {
if strings.ToLower(s)[:monthPrefix] == prefix {
return val
}
}
return non
}
type Approvals string
const (
Preview Approvals = "previews"
Incoming Approvals = "incoming"
)
// Approve prints the number of records waiting for approval for public display.
func (cmd Approvals) Approve(db *sql.DB) error {
if db == nil {
return database.ErrDB
}
switch cmd {
case Preview, Incoming:
default:
return ErrUnknown
}
wait, err := database.Waiting(db)
if err != nil {
return fmt.Errorf("approve count: %w", err)
}
if wait > 0 {
return fmt.Errorf("%d %s files waiting approval: %w", wait, cmd, ErrApprove)
}
return nil
}
// Init SQL directory.
func Init(w io.Writer, directory string) error { //nolint:funlen
if w == nil {
w = io.Discard
}
const (
layout = "2-1-2006"
minDash = 2
oneMonth = 730
)
s := directory
color.Primary.Printf("SQL directory: %s\n", s)
entries, err := os.ReadDir(s)
if err != nil {
return fmt.Errorf("sql read directory: %w", err)
}
cnt, freed, inUse := 0, 0, 0
files := []string{}
var create time.Time
for _, entry := range entries {
if entry.IsDir() {
continue
}
f, err := entry.Info()
if err != nil {
fmt.Fprintf(w, "error with file info: %s\n", err)
continue
}
exts := strings.Split(f.Name(), ".")
dashes := strings.Split(exts[0], "-")
if len(dashes) < minDash {
continue
}
m := dashes[len(dashes)-minDash]
if Month(m) == non {
continue
}
cnt++
inUse += int(f.Size())
create, err = time.Parse(layout,
fmt.Sprintf("1-%d-%s", Month(m), dashes[len(dashes)-1]))
if err != nil {
log.Printf("error parsing date from %s: %s\n", f.Name(), err)
continue
}
const expire = time.Hour * oneMonth * 2
if time.Since(create) > expire {
if filepath.Ext(f.Name()) == ".sql" {
fmt.Fprintf(w, "%s is to be moved.\n", f.Name())
}
files = append(files, filepath.Join(s, f.Name()))
freed += int(f.Size())
}
}
fmt.Fprintf(w, "SQL found %d files using %s", cnt, humanize.Bytes(uint64(inUse)))
if len(files) == 0 {
fmt.Fprintf(w, "%s%s\n", str.PrePad, str.NothingToDo)
return nil
}
fmt.Fprintln(w, ".")
fmt.Fprintf(w, "SQL will move %d items totaling %s, leaving %s used.\n",
len(files), humanize.Bytes(uint64(freed)), humanize.Bytes(uint64(inUse-freed)))
return sqlProcess(w, files)
}
// SaveDir returns a usable path to store backups.
func SaveDir() (string, error) {
usr, err := user.Current()
if err == nil {
return usr.HomeDir, nil
}
dir, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("save directory failed to find a path: %w", err)
}
return dir, nil
}
// Store incoming or preview files as a tar archive.
func (cmd Approvals) Store(w io.Writer, path, partial string, deleteSrc bool) (string, error) {
if w == nil {
w = io.Discard
}
switch cmd {
case Preview, Incoming:
default:
return "", ErrUnknown
}
entries, err := os.ReadDir(path)
if err != nil {
return "", fmt.Errorf("store read: %w", err)
}
cnt, inUse := 0, 0
files := []string{}
for _, entry := range entries {
if entry.IsDir() {
continue
}
f, err := entry.Info()
if err != nil {
return "", fmt.Errorf("store entry info: %w", err)
}
files = append(files, filepath.Join(path, f.Name()))
cnt++
inUse += int(f.Size())
}
if len(files) == 0 {
return "", nil
}
fmt.Fprintf(w, "%s found %d files using %s for backup.\n", cmd, cnt, humanize.Bytes(uint64(inUse)))
n := time.Now()
dir, err := SaveDir()
if err != nil {
return "", err
}
filename := filepath.Join(dir,
fmt.Sprintf("d2-%s_%d-%02d-%02d.tar", partial, n.Year(), n.Month(), n.Day()))
if err := storer(files, filename, partial, deleteSrc); err != nil {
return "", err
}
fmt.Fprintf(w, "%s freeing up space is complete.\n", cmd)
return filename, nil
}
func storer(files []string, filename, partial string, deleteSrc bool) error {
store, err := os.Create(filename)
if err != nil {
return fmt.Errorf("store create: %w", err)
}
defer store.Close()
if err := archive.Store(store, files); err != nil {
return fmt.Errorf("%w: %s", ErrArcStore, partial)
}
if deleteSrc {
return archive.Delete(files)
}
return nil
}
// Compress the collection of files into a named archive.
func Compress(w io.Writer, files []string, name string) error {
if w == nil {
w = io.Discard
}
f, err := os.Create(name)
if err != nil {
return fmt.Errorf("sql create: %w", err)
}
defer f.Close()
if err := archive.Compress(f, files); err != nil {
return err
}
fmt.Fprintln(w, "SQL archiving is complete.")
return nil
}
func sqlProcess(w io.Writer, files []string) error {
if w == nil {
w = io.Discard
}
n := time.Now()
dir, err := SaveDir()
if err != nil {
return err
}
name := filepath.Join(dir, fmt.Sprintf("d2-sql_%d-%02d-%02d.tar.gz",
n.Year(), n.Month(), n.Day()))
if err := Compress(w, files, name); err != nil {
return err
}
return Remove(w, files)
}
// Remove files from the host file system.
func Remove(w io.Writer, files []string) error {
if w == nil {
w = io.Discard
}
if err := archive.Delete(files); err != nil {
return err
}
fmt.Fprintln(w, "SQL freeing up space is complete.")
return nil
}