-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
328 lines (258 loc) · 8.57 KB
/
main.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package main
import (
"flag"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
)
//#region Define CLI flags
type forceIncludedFiles []string
func (fileNames *forceIncludedFiles) String() string {
return fmt.Sprintf("%s", *fileNames)
}
func (fileNames *forceIncludedFiles) Set(value string) error {
*fileNames = append(*fileNames, filepath.FromSlash(value))
return nil
}
var (
projectsPath = flag.String("projects-dir", "", "Path to the projects directory (required)")
backupPath = flag.String("backup-dir", "", "Path to an empty backup directory (required)\nOtherwise, existing files may be removed from that directory.")
remoteBranch = flag.String("remote-branch", "origin", "Remote name")
dryRun = flag.Bool("dry-run", false, "Preview changes without modifying the backup directory")
forceIncludedRelPaths forceIncludedFiles
)
func init() {
flag.Var(&forceIncludedRelPaths, "force-include", "Always include a git ignored `file/directory` like \".git\".\nCan be specified multiple times to include multiple items.")
flag.Usage = func() {
message := `Git Local Backup v1.0
A tool for copying local files from Git projects to a cloud drive or a backup disk for safekeeping.
It copies only the files that have been modified since the last backup, including:
- Committed files that are not yet pushed to the remote repository
- Working and staged files that are not yet committed
- Files that are not yet tracked by "git add"
- Any .gitignored file included via "--force-include" flag
… basically every unpushed file that can be lost during an incident.
Usage: %v [FLAGS] --projects-dir "<path>" --backup-dir "<path>"
> Use either - or -- for flags. They are equivalent.
Flags:
`
w := flag.CommandLine.Output()
fmt.Fprintf(w, message, filepath.Base(os.Args[0]))
flag.PrintDefaults()
fmt.Fprintf(w, "\nVisit https://github.com/ni554n/git-local-backup for scheduling instructions.\n")
}
}
//#endregion Define CLI flags
func main() {
//#region Parse flags
flag.Parse()
if *projectsPath == "" || *backupPath == "" {
flag.Usage()
os.Exit(2)
}
if strings.HasPrefix(*projectsPath, "~") {
homeDir, err := os.UserHomeDir()
panicIf(err)
*projectsPath = filepath.Join(homeDir, (*projectsPath)[1:])
}
if strings.HasPrefix(*backupPath, "~") {
homeDir, err := os.UserHomeDir()
panicIf(err)
*backupPath = filepath.Join(homeDir, (*backupPath)[1:])
}
//#endregion Parse flags
// Check if git is installed
_, err := exec.LookPath("git")
panicIf(err)
//#region Read the full backup directory
backedUpDirRelPaths := []string{}
type StringSet map[string]struct{}
backedUpFileRelPaths := make(StringSet)
err = filepath.WalkDir(*backupPath, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
entryRelPath, err := filepath.Rel(*backupPath, path)
if entry.IsDir() {
backedUpDirRelPaths = append(backedUpDirRelPaths, entryRelPath)
} else {
backedUpFileRelPaths[entryRelPath] = struct{}{}
}
return nil
})
panicIf(err)
//#endregion Read the full backup directory
//#region Visit each project directory and make a list of files to backup
projectDirEntries, err := os.ReadDir(*projectsPath)
panicIf(err)
projectFiles := []string{}
for _, projectDir := range projectDirEntries {
if !projectDir.IsDir() {
continue
}
projectDirPath := filepath.Join(*projectsPath, projectDir.Name())
// Skip over non-git projects
if _, err := os.Stat(filepath.Join(projectDirPath, ".git")); os.IsNotExist(err) {
continue
}
// `cd` into the project directory
err := os.Chdir(projectDirPath)
panicIf(err)
// --exclude-standard: Ignore .gitignore and other git excluded files
// --others: Untracked files not yet added by `git add`
// --full-name: Output relative paths
untrackedFilesStdout, err := exec.Command(
"git", "--no-pager", "ls-files", "--exclude-standard", "--others", "--full-name",
).Output()
panicIf(err)
includedFiles := strings.Split(filepath.FromSlash(string(untrackedFilesStdout)), "\n")
branchNameStdout, err := exec.Command(
"git", "--no-pager", "branch", "--show-current",
).Output()
panicIf(err)
branchName := strings.TrimSpace(string(branchNameStdout))
// Current branch name can be empty when a specific commit is checked out
if branchName != "" {
// Files that are in local commits but not yet pushed to the remote
unpushedFilesStdout, _ := exec.Command(
"git", "--no-pager", "diff", "--name-only", *remoteBranch+"/"+branchName,
).Output()
unpushedFiles := strings.Split(filepath.FromSlash(string(unpushedFilesStdout)), "\n")
includedFiles = append(includedFiles, unpushedFiles...)
}
for _, forceIncludedRelPath := range forceIncludedRelPaths {
forceIncludedPath := filepath.Join(projectDirPath, forceIncludedRelPath)
info, err := os.Stat(forceIncludedPath)
if os.IsNotExist(err) {
continue
}
panicIf(err)
if info.IsDir() {
err = filepath.WalkDir(forceIncludedPath, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if !entry.IsDir() {
entryRelPath, err := filepath.Rel(projectDirPath, path)
panicIf(err)
includedFiles = append(includedFiles, entryRelPath)
}
return nil
})
panicIf(err)
} else {
includedFiles = append(includedFiles, forceIncludedRelPath)
}
}
// Add current project dir to the each element in the includedFiles
for _, includedFile := range includedFiles {
if strings.TrimSpace(includedFile) == "" {
continue
}
projectFiles = append(projectFiles, filepath.Join(projectDir.Name(), includedFile))
}
}
//#endregion Visit each project directory and make a list of files to backup
if *dryRun {
fmt.Println("Simulating changes to backup directory:")
fmt.Println()
}
//#region Make the necessary changes to the backup directory
for _, projectFileRelPath := range projectFiles {
projectFilePath := filepath.Join(*projectsPath, projectFileRelPath)
// Deleted files can appear in the git change list. Will be removed later.
if _, err := os.Stat(projectFilePath); os.IsNotExist(err) {
continue
}
if _, ok := backedUpFileRelPaths[projectFileRelPath]; ok {
delete(backedUpFileRelPaths, projectFileRelPath)
diffStdout, _ := exec.Command(
"git", "--no-pager", "diff", "--no-index", "--name-only",
projectFilePath,
filepath.Join(*backupPath, projectFileRelPath),
).Output()
// No diff output means the file hasn't changed
if len(diffStdout) == 0 {
continue
}
}
// Copy files that are changed or newly added
if *dryRun {
fmt.Println("+", projectFileRelPath)
} else {
err := copyFile(projectFilePath, filepath.Join(*backupPath, projectFileRelPath))
if err != nil {
fmt.Println(err)
}
}
}
// Removing files from backup folder that are no longer in the project
for backupFileRelPath := range backedUpFileRelPaths {
if *dryRun {
fmt.Println("-", backupFileRelPath)
} else {
err := os.Remove(filepath.Join(*backupPath, backupFileRelPath))
if err != nil {
fmt.Println(err)
}
}
}
// Removing empty dirs recursively. Skipping 0th item as it's the backup dir path itself.
if !*dryRun {
for i := len(backedUpDirRelPaths) - 1; i > 0; i-- {
// Attempting to remove every backup dir. If it's not empty then it will fail expectedly.
err := os.Remove(filepath.Join(*backupPath, backedUpDirRelPaths[i]))
// If the error wasn't due to the dir not being empty then it's a real error.
if err != nil && !os.IsNotExist(err) {
fmt.Println(err)
}
}
}
//#endregion Make the necessary changes to the backup directory
}
func copyFile(srcPath, dstPath string) error {
// Create the destination directory if it doesn't exist
dstDir := filepath.Dir(dstPath)
_, err := os.Stat(dstDir)
if err != nil && os.IsNotExist(err) {
err := os.MkdirAll(dstDir, 0755)
if err != nil {
return err
}
}
// Open the source file for reading
sourceFile, err := os.Open(srcPath)
if err != nil {
return err
}
defer sourceFile.Close()
// Create the destination file if it doesn't exist
destinationFile, err := os.Create(dstPath)
if err != nil {
return err
}
defer destinationFile.Close()
// Copy the contents of the source file to the destination file
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
return err
}
// Preserve the file permissions of the source file
srcInfo, err := os.Stat(srcPath)
if err != nil {
return err
}
if err := os.Chmod(dstPath, srcInfo.Mode()); err != nil {
return err
}
return nil
}
func panicIf(err error) {
if err != nil {
panic(err)
}
}