-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.go
216 lines (185 loc) · 5.75 KB
/
lib.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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"strings"
"sync"
"time"
)
const OneK = 1024
const OneM = 1024 * 1024
const OneG = 1024 * 1024 * 1024
// FileExists returns true is given file exists, otherwise false.
func FileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
// FolderExists returns true is given folder exists, otherwise false.
func FolderExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return info.IsDir()
}
// GetCurrentDateTime gets current date time in "YYYYMMDD hhmmss" format.
func GetCurrentDateTime() string {
return time.Now().Format("20060102 150405")
}
// GetCurrentDate gets current date time in "YYYYMM" format.
func GetCurrentDate() string {
return time.Now().Format("200601")
}
// Compress compresses given folder to archive using 7z method, and optionally protects archive
// with a password.
func Compress(folderToCompress string, excludes []string, targetFolder string, archiveName string, password string, protectWithPassword bool, dryRun bool) string {
args := []string{"a", "-t7z"}
if protectWithPassword && len(password) > 0 {
args = append(args, "-p"+password)
}
folderToCompress = strings.Replace(folderToCompress, "\\", "/", -1)
if strings.HasSuffix(folderToCompress, "/") {
folderToCompress = folderToCompress[0 : len(folderToCompress)-1]
}
var targetFolderForCurrentMonth = strings.Replace(targetFolder, "\\", "/", -1)
if !(strings.HasSuffix(targetFolderForCurrentMonth, "/")) {
targetFolderForCurrentMonth += "/"
}
targetFolderForCurrentMonth += GetCurrentDate() + "/"
var archivePath = targetFolderForCurrentMonth + archiveName + " " + GetCurrentDateTime() + ".7z"
if !dryRun {
if !FolderExists(targetFolderForCurrentMonth) {
mkdirErr := os.MkdirAll(targetFolderForCurrentMonth, 0755)
if mkdirErr != nil {
log.Fatal(mkdirErr)
}
}
if FileExists(archivePath) {
_ = os.Remove(archivePath)
}
}
args = append(args, archivePath, folderToCompress,
"-ssw", /* compress files open for writing */
"-mx3", /* set level of compression */
"-bd" /* disable progress indicator */)
var firstFolder = folderToCompress[strings.LastIndex(folderToCompress, "/")+1:]
for i := 0; i < len(excludes); i++ {
args = append(args, "-xr!"+firstFolder+"/"+excludes[i])
}
//fmt.Println("Will run 7z with args:", args)
if dryRun {
return "Everything is Ok"
}
out, err := exec.Command("7z.exe", args...).Output()
if err != nil {
fmt.Println(err)
}
var compressionResult = string(out[:])
if validate7zOutput(compressionResult) {
if FileExists(archivePath) {
fmt.Println("Generated archive file " + archivePath + " (approx. " + GetFileSize(archivePath) + ")")
PrintBackupSizeEvolutionOverTime(targetFolderForCurrentMonth, archiveName, archivePath)
}
} else {
if FileExists(archivePath) {
_ = os.Remove(archivePath)
fmt.Println("Compression failed, deleted bad archive file " + archivePath)
}
}
return compressionResult
}
func PrintBackupSizeEvolutionOverTime(archivesBaseFolder string, archivesBaseName string, lastFilePath string) {
//
}
func GetFileSize(filePath string) string {
fi, err := os.Stat(filePath)
if err != nil {
log.Fatal("Error when evaluating file's size:", err)
}
var fiSize = fi.Size()
var sizeUnit = "B"
if fiSize > OneG {
fiSize = fiSize / OneG
sizeUnit = "GB"
} else if fiSize > OneM {
fiSize = fiSize / OneM
sizeUnit = "MB"
} else if fiSize > OneK {
fiSize = fiSize / OneK
sizeUnit = "KB"
}
return fmt.Sprintf("%d%s", fiSize, sizeUnit)
}
func RotateLogs(logsFolder string, dryRun bool) {
var prevReportFilePath = logsFolder + "simple-backup-go-logs_prev.txt"
var reportFilePath = logsFolder + "simple-backup-go-logs.txt"
fmt.Println("🧾 Report rotation: move " + reportFilePath + " to " + prevReportFilePath)
if !dryRun {
_ = os.Remove(prevReportFilePath)
_ = os.Rename(reportFilePath, prevReportFilePath)
}
}
func SaveLogs(report string, logsFolder string, dryRun bool) {
if !dryRun {
f, err := os.OpenFile(logsFolder+"simple-backup-go-logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal("Error when opening log file:", err)
}
if _, err := f.WriteString("\n##########\n" + report); err != nil {
log.Fatal("Error when writing log file:", err)
}
if err := f.Close(); err != nil {
log.Fatal("Error when closing log file:", err)
}
}
}
func validate7zOutput(output string) bool {
return strings.Contains(strings.ToUpper(output), "EVERYTHING IS OK")
}
// Parallelize runs given functions in parallel.
func Parallelize(functions ...func()) {
var waitGroup sync.WaitGroup
waitGroup.Add(len(functions))
defer waitGroup.Wait()
for _, function := range functions {
go func(copy func()) {
defer waitGroup.Done()
copy()
}(function)
}
}
// BackupTaskConfigs backup tasks. Generated with https://mholt.github.io/json-to-go/
type BackupTaskConfigs []struct {
TaskName string `json:"task-name"`
Source string `json:"source"`
ProtectWithPassword string `json:"protect-with-password,omitempty"`
Excludes []string `json:"excludes,omitempty"`
}
// LoadBackupTaskConfigs loads given config file then returns configured backup tasks.
func LoadBackupTaskConfigs(configFile string) BackupTaskConfigs {
content, err := os.ReadFile(configFile)
if err != nil {
log.Fatal("Error when opening file:", err)
}
// Now let's unmarshall the data into `config`
var config BackupTaskConfigs
err = json.Unmarshal(content, &config)
if err != nil {
log.Fatal("Error during Unmarshal():", err)
}
return config
}
func IsElementExist(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}