/
file.go
442 lines (377 loc) · 9.87 KB
/
file.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// file.go will hold all the operations that have to do with
// file management.
package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
)
func SyncFiles() {
PrintHeader("Syncing files ...")
// load config
c, err := NewConfig(PathDotConfig)
if err != nil {
PrintBodyError(
"not able to load config file. Make sure the .dotconfig file is present and points to the correct location",
)
return
}
// when we have files the sync them
if len(c.Files) > 0 {
// for every file track it
copyAll := false
for name, path := range c.Files {
// get full path
fullPath := fmt.Sprintf("%s%s", HomeDir(), path)
copyAll = TrackFile(name, fullPath, false, copyAll)
}
} else {
PrintBodyError("there aren't any files being tracked. Begin doing so with: `dot add -name [name] -path [path]`")
}
}
// TrackFile will track an individual file, meaning, it will move the original
// file to either the files or backup folder. It will the create a symlink of
// the file in the original location. `name` will be used as the name of the
// folder and key in the config file. `fullPath` has to be the absolute path
// to the file to be tracked.
//
// TrackFile can be called from two contexes:
//
// 1. From SyncFiles, it will read all the tracked files from the config and
// make track files if necessary.
//
// 2. From CommandAdd, this will add a new file for tracking
//
// TrackFile will make a distinction between a new file and a file that is
// already been tracked:
//
// 1. TrackFile can't find the symlink, but the file is present in the
// dot_path (the folder that holds all the original files). Then we need to
// relink it, thus creating a symlink at the correct location. This happens
// we you run dot on a new 'additional machine'.
//
// 2. TrackFile can't find the symlink, and the file is also not present in
// the dot_path folder. This will mean that it is a new file were are going
// to track. So we copy the file to the files folder, create a symlink, and
// add an entry to the config file.
func TrackFile(name string, fullPath string, push bool, copyAll bool) bool {
// load config
c, err := NewConfig(PathDotConfig)
if err != nil {
PrintBodyError("not able to find .dotconfig")
return copyAll
}
// Base
base := path.Base(fullPath)
// get relative path
relPath, err := GetRelativePath(fullPath)
if err != nil {
PrintBodyError(err.Error())
return copyAll
}
// check if path is present
_, err = os.Stat(fullPath)
if err != nil {
PrintBodyError(fmt.Sprintf("file not present on system: %s", fullPath))
if copyAll {
src := fmt.Sprintf("%s%s/files/%s/%s", HomeDir(), c.DotPath, name, base)
MakeAndCopyToDir(src, fullPath)
return TrackFile(name, fullPath, push, copyAll)
}
PrintBody("Copy file(s) to its destination? [All/Y/N]")
var input string
_, err := fmt.Scan(&input)
if err != nil {
log.Fatal(err)
}
switch input {
case "All":
copyAll = true
src := fmt.Sprintf("%s%s/files/%s/%s", HomeDir(), c.DotPath, name, base)
err := MakeAndCopyToDir(src, fullPath)
if err != nil {
PrintBodyError(err.Error())
return copyAll
}
return TrackFile(name, fullPath, push, copyAll)
case "Y":
src := fmt.Sprintf("%s%s/files/%s/%s", HomeDir(), c.DotPath, name, base)
err := MakeAndCopyToDir(src, fullPath)
if err != nil {
PrintBodyError(err.Error())
return copyAll
}
return TrackFile(name, fullPath, push, copyAll)
case "N":
PrintBodyError(fmt.Sprintf("Ignoring %s", name))
return copyAll
default:
PrintBodyError("Invalid input")
return copyAll
}
}
// check if path is already symlinked
s, err := os.Lstat(fullPath)
if err != nil {
return copyAll
}
if s.Mode()&os.ModeSymlink == os.ModeSymlink {
PrintBody(fmt.Sprintf("%s is already symlinked", name))
return copyAll
}
repoPath := fmt.Sprintf("%s%s/files/%s/", HomeDir(), c.DotPath, name)
if _, err := os.Stat(repoPath); err == nil {
// no symlink found, already in repo => additional machine
PrintBody(fmt.Sprintf("Symlinking: %s", name))
// put in backup folder, set named folder based on `name`, e.g.:
// `/home/jpbruinsslot/dotfiles/backup/[name]/[base]`
dst := fmt.Sprintf("%s%s/backup/%s/%s", HomeDir(), c.DotPath, name, base)
err = MakeAndMoveToDir(fullPath, dst)
if err != nil {
msg := fmt.Sprintf("not able to move files to %s (%s)", dst, err)
PrintBodyError(msg)
prompt := fmt.Sprintf("Remove %s ? [Y/N]", dst)
PrintBody(prompt)
var input string
_, err := fmt.Scan(&input)
if err != nil {
log.Fatal(err)
}
if input == "Y" {
err := os.RemoveAll(dst)
if err != nil {
log.Fatal(err)
}
err = MakeAndMoveToDir(fullPath, dst)
if err != nil {
log.Fatal(err)
}
} else {
msg := fmt.Sprintf("ignoring %s", name)
PrintBodyError(msg)
return copyAll
}
}
// trim potential trailing slash for symlink
fullPath = strings.TrimRight(fullPath, "/")
// create symlink (os.Symlink(oldname, newname))
dst = fmt.Sprintf("%s%s/files/%s/%s", HomeDir(), c.DotPath, name, base)
err = os.Symlink(dst, fullPath)
if err != nil {
log.Fatal(err)
}
} else {
// no symlink found, not in repo => new entry
PrintBody(fmt.Sprintf("Symlinking: %s", name))
// put in files folder, set named folder based on `name`, e.g.:
// `/home/jpbruinsslot/dotfiles/files/[name]/[base]`
dst := fmt.Sprintf("%s%s/files/%s/%s", HomeDir(), c.DotPath, name, base)
err = MakeAndMoveToDir(fullPath, dst)
if err != nil {
log.Fatal(err)
}
// trim potential trailing slash for symlink
fullPath = strings.TrimRight(fullPath, "/")
// create symlink (os.Symlink(oldname, newname))
err = os.Symlink(dst, fullPath)
if err != nil {
log.Fatal(err)
}
// create entry in .dotconfig file
c.Files[name] = relPath
c.Save()
// push changes to repository
if push {
GitCommitPush(name, "add")
}
}
return copyAll
}
// UntrackFile will remove a file from tracking. `name` will be the key
// in the config file that points to the initial location of the file
func UntrackFile(name string, push bool) {
// open config file
c, err := NewConfig(fmt.Sprintf("%s/%s", HomeDir(), ConfigFileName))
if err != nil {
PrintBodyError("not able to find .dotconfig")
return
}
// check if `name` is present in c.Files
path := c.Files[name]
if path == "" {
PrintBodyError(
fmt.Sprintf(
"'%s' is not being tracked. Get the list of tracked files with `dot list`",
name,
),
)
return
}
// check if path (the symlink) is present
pathSymlink := fmt.Sprintf("%s%s", HomeDir(), path)
f, err := os.Lstat(pathSymlink)
if err != nil {
PrintBodyError(fmt.Sprintf("not able to find: %s", path))
return
}
// check if path is symlink
if f.Mode()&os.ModeSymlink != os.ModeSymlink {
PrintBodyError(fmt.Sprintf("%s is not a symlink", path))
return
}
// check if src is present
src := fmt.Sprintf("%s%s/files/%s%s", HomeDir(), c.DotPath, name, path)
if _, err = os.Stat(src); err != nil {
PrintBodyError(fmt.Sprintf("not able to find %s", src))
return
}
// remove symlink
err = os.Remove(pathSymlink)
if err != nil {
PrintBodyError(fmt.Sprintf("not able to remove %s", pathSymlink))
return
}
// move the file or directory
dst := fmt.Sprintf("%s%s", HomeDir(), path)
PrintBody(fmt.Sprintf("Moving %s back to %s", name, dst))
err = MakeAndCopyToDir(src, dst)
if err != nil {
log.Fatal(err)
}
// remove tracked files from repo dir
entry := fmt.Sprintf("%s%s/files/%s", HomeDir(), c.DotPath, name)
err = os.RemoveAll(entry)
if err != nil {
log.Fatal(err)
}
// remove entry from config and save config
delete(c.Files, name)
c.Save()
// push changes to repository
if push {
GitCommitPush(name, "rm")
}
}
// MakeAndMoveToDir will move the source file/folder `src` to the destination
// `dst` (`dst` will be absolute path to the destination).
func MakeAndMoveToDir(src string, dst string) error {
err := MakeAndCopyToDir(src, dst)
if err != nil {
return err
}
err = os.RemoveAll(src)
if err != nil {
return err
}
return nil
}
func MakeAndCopyToDir(src string, dst string) error {
// folder or file
f, err := os.Stat(src)
if err != nil {
return err
}
if f.IsDir() {
err = CopyDir(src, dst)
if err != nil {
return err
}
} else {
// get directory
dir, _ := filepath.Split(dst)
// create destination dir
// err = os.MkdirAll(dir, f.Mode())
err = os.MkdirAll(dir, 0755)
if err != nil {
return err
}
// rename the file
err = CopyFile(src, dst)
if err != nil {
return err
}
}
return nil
}
func CopyDir(src string, dst string) error {
src = filepath.Clean(src)
dst = filepath.Clean(dst)
// Check src
f, err := os.Stat(src)
if err != nil {
return err
}
if !f.IsDir() {
return errors.New("source is not a directory")
}
// Check dst
_, err = os.Stat(dst)
if err != nil && !os.IsNotExist(err) {
return nil
}
if err == nil {
return errors.New("dst already exist")
}
files, err := ioutil.ReadDir(src)
if err != nil {
return err
}
os.MkdirAll(dst, f.Mode())
if err != nil {
return err
}
for _, file := range files {
srcPath := filepath.Join(src, file.Name())
dstPath := filepath.Join(dst, file.Name())
if file.IsDir() {
err = CopyDir(srcPath, dstPath)
if err != nil {
return err
}
} else {
if file.Mode()&os.ModeSymlink != 0 {
continue
}
err = CopyFile(srcPath, dstPath)
if err != nil {
return err
}
}
}
return nil
}
func CopyFile(src string, dst string) error {
inFile, err := os.Open(src)
if err != nil {
return err
}
defer inFile.Close()
outFile, err := os.Create(dst)
if err != nil {
return err
}
defer outFile.Close()
_, err = io.Copy(outFile, inFile)
if err != nil {
return err
}
err = outFile.Sync()
if err != nil {
return err
}
f, err := os.Stat(src)
if err != nil {
return err
}
err = os.Chmod(dst, f.Mode())
if err != nil {
return err
}
return nil
}