-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
509 lines (440 loc) · 10.2 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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"strings"
goversion "github.com/caarlos0/go-version"
"github.com/go-git/go-git/v5"
"gopkg.in/yaml.v3"
"text/template"
)
/*
* initialization and flags
*/
var logger *log.Logger
var (
flagValidateOnly bool
flagDotFile string
flagVerbose bool
flagRmOnly bool
flagRm bool
flagV bool
)
var (
version = "dev"
treeState = ""
commit = ""
date = ""
builtBy = ""
)
func initFlags() {
flag.StringVar(&flagDotFile, "dot", "dot.yml", "the dots config file")
flag.BoolVar(&flagVerbose, "verbose", false, "verbose output")
flag.BoolVar(&flagRm, "rm", true, "remove targets before creating")
flag.BoolVar(&flagRmOnly, "rm-only", false, "only remove targets, do not create")
flag.BoolVar(&flagValidateOnly, "validate-only", false, "only read and validate dots file")
flag.BoolVar(&flagV, "v", false, "print version info")
}
func init() {
initFlags()
logger = log.New(os.Stderr, "", 0)
}
func printVersionInfo() {
art := `
|
__| __ _|_
/ | / \_|
o\_/|_/\__/ |_/
`
logger.Print(goversion.GetVersionInfo(
goversion.WithAppDetails("dot", "a simple dot file manager", ""),
goversion.WithASCIIName(art),
func(i *goversion.Info) {
i.GitCommit = commit
i.GitTreeState = treeState
i.BuildDate = date
i.GitVersion = version
i.BuiltBy = builtBy
},
))
}
/*
* core data structures and operations
*/
type FileMapping struct {
From string
To string
As string
Os string
With map[string]string
}
func (m FileMapping) doLink() error {
err := os.Symlink(m.From, m.To)
if err != nil {
return err
}
return nil
}
func (m FileMapping) doCopy() error {
var inReader io.Reader
if len(m.With) > 0 {
in, err := os.ReadFile(m.From)
if err != nil {
panic(err)
}
inReader = strings.NewReader(evalTemplateString(string(in), m.With))
} else {
fin, err := os.Open(m.From)
if err != nil {
return err
}
defer fin.Close()
inReader = fin
}
fout, err := os.Create(m.To)
if err != nil {
return err
}
defer fout.Close()
_, err = io.Copy(fout, inReader)
if err != nil {
return err
}
return nil
}
func unmapPath(path string) {
if pathExists := pathExists(path); !pathExists {
if flagVerbose {
logger.Printf("rm %s: skipping, file not there\n", path)
}
} else {
err := os.Remove(path)
if err != nil {
logger.Printf("failed removing file %s, %v\n", path, err)
}
if flagVerbose {
logger.Printf("rm %s: success\n", path)
}
}
}
func (m FileMapping) domap() {
handleDoMapRes := func(m FileMapping, err error) {
if err != nil {
logger.Fatalf("failed %s %s -> %s: %v", m.As+"ing", m.From, m.To, err)
}
if flagVerbose {
logger.Printf("%s %s -> %s\n", m.As+"ing", m.From, m.To)
}
}
// ensure destination path exists
if err := createPath(m.To); err != nil {
logger.Fatalf("failed creating path %s, %v", m.To, err)
}
switch typ := m.As; typ {
case "link":
err := m.doLink()
handleDoMapRes(m, err)
case "copy":
err := m.doCopy()
handleDoMapRes(m, err)
}
}
func (m FileMapping) isMatchingOs() bool {
osMap := map[string]string{
"linux": "linux",
"macos": "darwin",
"darwin": "darwin",
"all": runtime.GOOS,
"": runtime.GOOS,
}
return osMap[m.Os] == runtime.GOOS
}
type Opts struct {
Cd string
}
type Dots struct {
Opts Opts `yaml:"opt"`
FileMappings []FileMapping `yaml:"map"`
Resources []Resource `yaml:"fetch"`
}
type YamlURL struct {
*url.URL
}
type Resource struct {
Url string `yaml:"url"`
To string `yaml:"to"`
As string `yaml:"as"`
}
func (d *Dots) UnmarshalYAML(unmarshal func(interface{}) error) error {
var tmpDots struct {
Opts Opts `yaml:"opt"`
Mappings map[string]FileMapping `yaml:"map"`
Resources []Resource `yaml:"fetch"`
}
err := unmarshal(&tmpDots)
if err != nil {
return err
}
d.Opts = tmpDots.Opts
for file, mapping := range tmpDots.Mappings {
mapping.From = file
d.FileMappings = append(d.FileMappings, mapping)
}
d.Resources = tmpDots.Resources
return nil
}
func (dots Dots) validate() []error {
var errs []error
for _, mapping := range dots.FileMappings {
if !pathExists(mapping.From) {
errs = append(errs, fmt.Errorf("%s: path does not exist", mapping.From))
} else if isDirectory(mapping.From) && mapping.As == "copy" {
errs = append(errs, fmt.Errorf("%s: cannot use copy type with directory", mapping.From))
}
if mapping.As != "copy" && len(mapping.With) > 0 {
errs = append(errs, fmt.Errorf("%s: templating is only supported in `copy` mode ]", mapping.From))
}
}
for _, resource := range dots.Resources {
if len(resource.To) == 0 {
errs = append(errs, fmt.Errorf("%s: resource destination (`to`) cannot be empty", resource.Url))
}
if len(resource.As) == 0 {
errs = append(errs, fmt.Errorf("%s: resource type (`as`) cannot be empty", resource.Url))
}
}
return errs
}
func inferDestination(file string) string {
if strings.HasPrefix(file, ".") {
return getHomeDir() + "/" + file
} else {
return getHomeDir() + "/." + file
}
}
func evalTemplateString(templStr string, env map[string]string) string {
templ, err := template.New("template").Parse(templStr)
if err != nil {
logger.Fatalf("failed creating template from %s, %v", templStr, err)
}
var templOut bytes.Buffer
err = templ.Execute(&templOut, env)
if err != nil {
logger.Fatalf("failed executing template, %v", err)
}
return templOut.String()
}
func evalTemplate(with map[string]string) map[string]string {
newMap := make(map[string]string, len(with))
for variable, templ := range with {
env := map[string]string{"Os": runtime.GOOS}
newMap[variable] = evalTemplateString(templ, env)
}
return newMap
}
func (dots Dots) transform() Dots {
opts := dots.Opts
mappings := dots.FileMappings
var newDots Dots
newDots.Opts = opts
for _, mapping := range mappings {
// To is expanded / inferred first: it's value is based off of
// `from` before prefix or cwd are added to it
if len(mapping.To) > 0 {
// expand destination ~
mapping.To = expandTilde(mapping.To)
} else {
// infer destination based on From
mapping.To = inferDestination(mapping.From)
}
if len(mapping.With) > 0 {
mapping.With = evalTemplate(mapping.With)
}
if len(opts.Cd) > 0 {
// Cd set: add prefix to From
mapping.From = path.Join(opts.Cd, mapping.From)
}
if !strings.HasPrefix(mapping.From, "/") {
cwd, _ := os.Getwd()
mapping.From = cwd + "/" + mapping.From
}
// default As to symlink
if len(mapping.As) == 0 {
mapping.As = "link"
}
newDots.FileMappings = append(newDots.FileMappings, mapping)
}
for _, resource := range dots.Resources {
if len(resource.To) > 0 {
resource.To = expandTilde(resource.To)
}
newDots.Resources = append(newDots.Resources, resource)
}
return newDots
}
func fetchGitResource(resource Resource) error {
if err := createPath(resource.To); err != nil {
return err
}
_, err := git.PlainClone(resource.To, false, &git.CloneOptions{
URL: resource.Url,
Progress: os.Stdout,
})
return err
}
func fetchHttpResource(resource Resource) error {
req, err := http.NewRequest("GET", resource.Url, nil)
if err != nil {
return err
}
httpClient := http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if !pathExists(resource.To) {
if err := createPath(resource.To); err != nil {
return err
}
}
if strings.HasSuffix(resource.To, "/") {
resource.To = filepath.Join(resource.To, path.Base(resource.Url))
}
fout, err := os.Create(resource.To)
if err != nil {
return err
}
defer fout.Close()
if _, err := io.Copy(fout, resp.Body); err != nil {
return err
}
return nil
}
func fetchResource(resource Resource) error {
switch resource.As {
case "git":
return fetchGitResource(resource)
case "file":
return fetchHttpResource(resource)
}
return nil
}
func (dots Dots) iterateFileMappings() {
for _, mapping := range dots.FileMappings {
if !mapping.isMatchingOs() {
if flagVerbose {
logger.Printf("not on %s, skipping %s\n", mapping.Os, mapping.From)
}
continue
}
if flagRm { // remove before mapping by default
unmapPath(mapping.To)
if flagRmOnly {
continue
}
}
mapping.domap()
}
}
func (dots Dots) iterateResources() {
for _, resource := range dots.Resources {
if flagRm { // remove before mapping by default
unmapPath(resource.To)
if flagRmOnly {
continue
}
}
err := fetchResource(resource)
if err != nil {
logger.Printf("error fetching resource %s, %v", resource.Url, err)
}
}
}
func (dots Dots) iterate() {
dots.iterateFileMappings()
dots.iterateResources()
}
/*
* Helpers
*/
func createPath(p string) error {
dstDir := path.Dir(p)
if !pathExists(dstDir) {
err := os.MkdirAll(dstDir, 0750)
if err != nil {
return err
}
}
return nil
}
func pathExists(path string) bool {
if _, err := os.Lstat(path); os.IsNotExist(err) {
return false
}
return true
}
func isDirectory(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return false
}
logger.Fatalf("failed reading path %s, %v", path, err)
}
return fileInfo.IsDir()
}
func getHomeDir() string {
return os.Getenv("HOME")
}
func expandTilde(path string) string {
if strings.HasPrefix(path, "~") {
homeDir := getHomeDir()
path = strings.Replace(path, "~", homeDir, 1)
}
return path
}
func readDotFile(file string) Dots {
rcFileData, err := os.ReadFile(file)
if err != nil {
logger.Fatalf("error reading config data: %v", err)
}
var dots Dots
decoder := yaml.NewDecoder(bytes.NewReader(rcFileData))
decoder.KnownFields(true)
if err := decoder.Decode(&dots); err != nil {
logger.Fatalf("cannot decode data: %v", err)
}
newDots := dots.transform()
errs := newDots.validate()
if len(errs) > 0 {
for _, err := range errs {
logger.Printf("failed validating dots file: %v", err)
}
os.Exit(1)
}
if flagValidateOnly {
logger.Printf("yay, dots file valid!")
os.Exit(0)
}
return newDots
}
func main() {
flag.Parse()
if flagV {
printVersionInfo()
os.Exit(0)
}
dots := readDotFile(flagDotFile)
dots.iterate()
}