generated from bilalcaliskan/golang-cli-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleaner.go
69 lines (53 loc) · 1.87 KB
/
cleaner.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
package cleaner
import (
"bytes"
"strings"
"github.com/bilalcaliskan/s3-manager/internal/constants"
"github.com/bilalcaliskan/s3-manager/internal/prompt"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
start "github.com/bilalcaliskan/s3-manager/cmd/clean/options"
"github.com/bilalcaliskan/s3-manager/internal/aws"
"github.com/bilalcaliskan/s3-manager/internal/utils"
"github.com/rs/zerolog"
)
func StartCleaning(svc s3iface.S3API, runner prompt.PromptRunner, cleanOpts *start.CleanOptions, logger zerolog.Logger) error {
allFiles, err := aws.GetAllFiles(svc, cleanOpts.RootOptions, cleanOpts.FileNamePrefix)
if err != nil {
return err
}
res := getProperObjects(cleanOpts, allFiles, logger)
sortObjects(res, cleanOpts)
border := len(res) - cleanOpts.KeepLastNFiles
if border <= 0 {
logger.Warn().
Int("arrayLength", len(res)).
Int("keepLastNFiles", cleanOpts.KeepLastNFiles).
Msg("not enough file, length of array is smaller than --keepLastNFiles flag")
return nil
}
targetObjects := res[:len(res)-cleanOpts.KeepLastNFiles]
keys := utils.GetKeysOnly(targetObjects)
var buffer bytes.Buffer
for _, v := range keys {
buffer.WriteString(v)
}
logger.Info().Any("files", keys).Msg("will attempt to delete these files")
if cleanOpts.DryRun {
logger.Info().Msg("skipping object deletion since --dryRun flag is passed")
return nil
}
if !cleanOpts.AutoApprove {
logger.Info().Any("files", keys).Msg("these files will be removed if you approve:")
if res, err := runner.Run(); err != nil {
if strings.ToLower(res) == "n" {
return constants.ErrUserTerminated
}
return constants.ErrInvalidInput
}
}
if err := aws.DeleteFiles(svc, cleanOpts.RootOptions.BucketName, targetObjects, cleanOpts.DryRun, logger); err != nil {
logger.Error().Str("error", err.Error()).Msg("an error occurred while deleting target files")
return err
}
return nil
}