-
Notifications
You must be signed in to change notification settings - Fork 501
/
Copy pathconfig.go
2093 lines (1932 loc) · 63.9 KB
/
config.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"go/build"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"os/user"
"path/filepath"
"reflect"
"regexp"
"runtime"
"runtime/pprof"
"sort"
"strconv"
"strings"
"text/template"
"time"
"unicode"
"github.com/Masterminds/sprig/v3"
"github.com/coreos/go-semver/semver"
gogit "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/format/diff"
"github.com/google/gops/agent"
"github.com/gregjones/httpcache"
"github.com/gregjones/httpcache/diskcache"
"github.com/mitchellh/mapstructure"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/twpayne/go-shell"
"github.com/twpayne/go-vfs/v4"
"github.com/twpayne/go-xdg/v6"
"go.uber.org/multierr"
"golang.org/x/term"
"github.com/twpayne/chezmoi/v2/assets/templates"
"github.com/twpayne/chezmoi/v2/internal/chezmoi"
"github.com/twpayne/chezmoi/v2/internal/git"
)
const (
logComponentKey = "component"
logComponentValueEncryption = "encryption"
logComponentValuePersistentState = "persistentState"
logComponentValueSourceState = "sourceState"
logComponentValueSystem = "system"
)
type purgeOptions struct {
binary bool
}
type templateConfig struct {
Options []string `mapstructure:"options"`
}
// A Config represents a configuration.
type Config struct {
// Global configuration, settable in the config file.
CacheDirAbsPath chezmoi.AbsPath `mapstructure:"cacheDir"`
Color autoBool `mapstructure:"color"`
Data map[string]interface{} `mapstructure:"data"`
DestDirAbsPath chezmoi.AbsPath `mapstructure:"destDir"`
Interpreters map[string]*chezmoi.Interpreter `mapstructure:"interpreters"`
Mode chezmoi.Mode `mapstructure:"mode"`
Pager string `mapstructure:"pager"`
PINEntry pinEntryConfig `mapstructure:"pinentry"`
Safe bool `mapstructure:"safe"`
SourceDirAbsPath chezmoi.AbsPath `mapstructure:"sourceDir"`
Template templateConfig `mapstructure:"template"`
Umask fs.FileMode `mapstructure:"umask"`
UseBuiltinAge autoBool `mapstructure:"useBuiltinAge"`
UseBuiltinGit autoBool `mapstructure:"useBuiltinGit"`
Verbose bool `mapstructure:"verbose"`
WorkingTreeAbsPath chezmoi.AbsPath `mapstructure:"workingTree"`
// Global configuration, not settable in the config file.
configFormat readDataFormat
cpuProfile chezmoi.AbsPath
debug bool
dryRun bool
force bool
gops bool
homeDir string
keepGoing bool
noPager bool
noTTY bool
outputAbsPath chezmoi.AbsPath
refreshExternals bool
sourcePath bool
templateFuncs template.FuncMap
// Password manager configurations, settable in the config file.
Bitwarden bitwardenConfig `mapstructure:"bitwarden"`
Gopass gopassConfig `mapstructure:"gopass"`
Keepassxc keepassxcConfig `mapstructure:"keepassxc"`
Lastpass lastpassConfig `mapstructure:"lastpass"`
Onepassword onepasswordConfig `mapstructure:"onepassword"`
Pass passConfig `mapstructure:"pass"`
Secret secretConfig `mapstructure:"secret"`
Vault vaultConfig `mapstructure:"vault"`
// Encryption configurations, settable in the config file.
Encryption string `mapstructure:"encryption"`
Age chezmoi.AgeEncryption `mapstructure:"age"`
GPG chezmoi.GPGEncryption `mapstructure:"gpg"`
// Password manager data.
gitHub gitHubData
keyring keyringData
// Command configurations, settable in the config file.
Add addCmdConfig `mapstructure:"add"`
CD cdCmdConfig `mapstructure:"cd"`
Diff diffCmdConfig `mapstructure:"diff"`
Docs docsCmdConfig `mapstructure:"docs"`
Edit editCmdConfig `mapstructure:"edit"`
Git gitCmdConfig `mapstructure:"git"`
Merge mergeCmdConfig `mapstructure:"merge"`
// Command configurations, not settable in the config file.
apply applyCmdConfig
archive archiveCmdConfig
data dataCmdConfig
dump dumpCmdConfig
executeTemplate executeTemplateCmdConfig
_import importCmdConfig
init initCmdConfig
managed managedCmdConfig
mergeAll mergeAllCmdConfig
purge purgeCmdConfig
reAdd reAddCmdConfig
remove removeCmdConfig
secret secretCmdConfig
state stateCmdConfig
status statusCmdConfig
update updateCmdConfig
upgrade upgradeCmdConfig
verify verifyCmdConfig
// Version information.
version semver.Version
versionInfo VersionInfo
versionStr string
// Configuration.
fileSystem vfs.FS
bds *xdg.BaseDirectorySpecification
configFileAbsPath chezmoi.AbsPath
baseSystem chezmoi.System
sourceSystem chezmoi.System
destSystem chezmoi.System
persistentStateAbsPath chezmoi.AbsPath
persistentState chezmoi.PersistentState
httpClient *http.Client
logger *zerolog.Logger
// Computed configuration.
homeDirAbsPath chezmoi.AbsPath
encryption chezmoi.Encryption
stdin io.Reader
stdout io.Writer
stderr io.Writer
tempDirs map[string]chezmoi.AbsPath
ioregData ioregData
}
// A configOption sets and option on a Config.
type configOption func(*Config) error
type configState struct {
ConfigTemplateContentsSHA256 chezmoi.HexBytes `json:"configTemplateContentsSHA256" yaml:"configTemplateContentsSHA256"` //nolint:lll,tagliatelle
}
var (
chezmoiRelPath = chezmoi.NewRelPath("chezmoi")
persistentStateFileRelPath = chezmoi.NewRelPath("chezmoistate.boltdb")
httpCacheDirRelPath = chezmoi.NewRelPath("httpcache")
configStateKey = []byte("configState")
defaultAgeEncryptionConfig = chezmoi.AgeEncryption{
Command: "age",
Suffix: ".age",
}
defaultGPGEncryptionConfig = chezmoi.GPGEncryption{
Command: "gpg",
Suffix: ".asc",
}
identifierRx = regexp.MustCompile(`\A[\pL_][\pL\p{Nd}_]*\z`)
whitespaceRx = regexp.MustCompile(`\s+`)
viperDecodeConfigOptions = []viper.DecoderConfigOption{
viper.DecodeHook(
mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
chezmoi.StringSliceToEntryTypeSetHookFunc(),
chezmoi.StringToAbsPathHookFunc(),
StringOrBoolToAutoBoolHookFunc(),
),
),
}
)
// newConfig creates a new Config with the given options.
func newConfig(options ...configOption) (*Config, error) {
userHomeDir, err := os.UserHomeDir()
if err != nil {
return nil, err
}
homeDirAbsPath, err := chezmoi.NormalizePath(userHomeDir)
if err != nil {
return nil, err
}
bds, err := xdg.NewBaseDirectorySpecification()
if err != nil {
return nil, err
}
cacheDirAbsPath := chezmoi.NewAbsPath(bds.CacheHome).Join(chezmoiRelPath)
c := &Config{
// Global configuration, settable in the config file.
CacheDirAbsPath: cacheDirAbsPath,
Color: autoBool{
auto: true,
},
Interpreters: defaultInterpreters,
Pager: os.Getenv("PAGER"),
PINEntry: pinEntryConfig{
Options: pinEntryDefaultOptions,
},
Safe: true,
Template: templateConfig{
Options: chezmoi.DefaultTemplateOptions,
},
Umask: chezmoi.Umask,
UseBuiltinAge: autoBool{
auto: true,
},
UseBuiltinGit: autoBool{
auto: true,
},
// Global configuration, not settable in the config file.
homeDir: userHomeDir,
templateFuncs: sprig.TxtFuncMap(),
// Password manager configurations, settable in the config file.
Bitwarden: bitwardenConfig{
Command: "bw",
},
Gopass: gopassConfig{
Command: "gopass",
},
Keepassxc: keepassxcConfig{
Command: "keepassxc-cli",
},
Lastpass: lastpassConfig{
Command: "lpass",
},
Onepassword: onepasswordConfig{
Command: "op",
Prompt: true,
},
Pass: passConfig{
Command: "pass",
},
Vault: vaultConfig{
Command: "vault",
},
// Encryption configurations, settable in the config file.
Age: defaultAgeEncryptionConfig,
GPG: defaultGPGEncryptionConfig,
// Password manager data.
// Command configurations, settable in the config file.
Add: addCmdConfig{
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
recursive: true,
},
Diff: diffCmdConfig{
Exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
},
Docs: docsCmdConfig{
MaxWidth: 80,
},
Edit: editCmdConfig{
Hardlink: true,
MinDuration: 1 * time.Second,
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(
chezmoi.EntryTypeDirs | chezmoi.EntryTypeFiles | chezmoi.EntryTypeSymlinks | chezmoi.EntryTypeEncrypted,
),
},
Git: gitCmdConfig{
Command: "git",
},
Merge: mergeCmdConfig{
Command: "vimdiff",
},
// Command configurations, not settable in the config file.
apply: applyCmdConfig{
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
recursive: true,
},
archive: archiveCmdConfig{
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
recursive: true,
},
data: dataCmdConfig{
format: defaultWriteDataFormat,
},
dump: dumpCmdConfig{
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
format: defaultWriteDataFormat,
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
recursive: true,
},
executeTemplate: executeTemplateCmdConfig{
stdinIsATTY: true,
},
_import: importCmdConfig{
destination: homeDirAbsPath,
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
},
init: initCmdConfig{
data: true,
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
},
managed: managedCmdConfig{
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(
chezmoi.EntryTypeDirs | chezmoi.EntryTypeFiles | chezmoi.EntryTypeSymlinks | chezmoi.EntryTypeEncrypted,
),
},
mergeAll: mergeAllCmdConfig{
recursive: true,
},
reAdd: reAddCmdConfig{
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
recursive: true,
},
state: stateCmdConfig{
data: stateDataCmdConfig{
format: defaultWriteDataFormat,
},
dump: stateDumpCmdConfig{
format: defaultWriteDataFormat,
},
getBucket: stateGetBucketCmdConfig{
format: defaultWriteDataFormat,
},
},
status: statusCmdConfig{
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
recursive: true,
},
update: updateCmdConfig{
apply: true,
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll),
recursive: true,
},
upgrade: upgradeCmdConfig{
owner: "twpayne",
repo: "chezmoi",
},
verify: verifyCmdConfig{
exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone),
include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll &^ chezmoi.EntryTypeScripts),
recursive: true,
},
// Configuration.
fileSystem: vfs.OSFS,
bds: bds,
// Computed configuration.
homeDirAbsPath: homeDirAbsPath,
tempDirs: make(map[string]chezmoi.AbsPath),
stdin: os.Stdin,
stdout: os.Stdout,
stderr: os.Stderr,
}
for key, value := range map[string]interface{}{
"bitwarden": c.bitwardenTemplateFunc,
"bitwardenAttachment": c.bitwardenAttachmentTemplateFunc,
"bitwardenFields": c.bitwardenFieldsTemplateFunc,
"decrypt": c.decryptTemplateFunc,
"encrypt": c.encryptTemplateFunc,
"fromYaml": c.fromYamlTemplateFunc,
"gitHubKeys": c.gitHubKeysTemplateFunc,
"gitHubLatestRelease": c.gitHubLatestReleaseTemplateFunc,
"gopass": c.gopassTemplateFunc,
"gopassRaw": c.gopassRawTemplateFunc,
"include": c.includeTemplateFunc,
"ioreg": c.ioregTemplateFunc,
"joinPath": c.joinPathTemplateFunc,
"keepassxc": c.keepassxcTemplateFunc,
"keepassxcAttribute": c.keepassxcAttributeTemplateFunc,
"keyring": c.keyringTemplateFunc,
"lastpass": c.lastpassTemplateFunc,
"lastpassRaw": c.lastpassRawTemplateFunc,
"lookPath": c.lookPathTemplateFunc,
"mozillaInstallHash": c.mozillaInstallHashTemplateFunc,
"onepassword": c.onepasswordTemplateFunc,
"onepasswordDetailsFields": c.onepasswordDetailsFieldsTemplateFunc,
"onepasswordDocument": c.onepasswordDocumentTemplateFunc,
"onepasswordItemFields": c.onepasswordItemFieldsTemplateFunc,
"output": c.outputTemplateFunc,
"pass": c.passTemplateFunc,
"passFields": c.passFieldsTemplateFunc,
"passRaw": c.passRawTemplateFunc,
"secret": c.secretTemplateFunc,
"secretJSON": c.secretJSONTemplateFunc,
"stat": c.statTemplateFunc,
"toYaml": c.toYamlTemplateFunc,
"vault": c.vaultTemplateFunc,
} {
c.addTemplateFunc(key, value)
}
for _, option := range options {
if err := option(c); err != nil {
return nil, err
}
}
c.homeDirAbsPath, err = chezmoi.NormalizePath(c.homeDir)
if err != nil {
return nil, err
}
c.configFileAbsPath, err = c.defaultConfigFile(c.fileSystem, c.bds)
if err != nil {
return nil, err
}
c.SourceDirAbsPath, err = c.defaultSourceDir(c.fileSystem, c.bds)
if err != nil {
return nil, err
}
c.DestDirAbsPath = c.homeDirAbsPath
c._import.destination = c.homeDirAbsPath
return c, nil
}
// addTemplateFunc adds the template function with the key key and value value
// to c. It panics if there is already an existing template function with the
// same key.
func (c *Config) addTemplateFunc(key string, value interface{}) {
if _, ok := c.templateFuncs[key]; ok {
panic(fmt.Sprintf("%s: already defined", key))
}
c.templateFuncs[key] = value
}
type applyArgsOptions struct {
include *chezmoi.EntryTypeSet
init bool
exclude *chezmoi.EntryTypeSet
recursive bool
umask fs.FileMode
preApplyFunc chezmoi.PreApplyFunc
}
// applyArgs is the core of all commands that make changes to a target system.
// It checks config file freshness, reads the source state, and then applies the
// source state for each target entry in args. If args is empty then the source
// state is applied to all target entries.
func (c *Config) applyArgs(
ctx context.Context, targetSystem chezmoi.System, targetDirAbsPath chezmoi.AbsPath, args []string,
options applyArgsOptions,
) error {
if options.init {
if err := c.createAndReloadConfigFile(); err != nil {
return err
}
}
var currentConfigTemplateContentsSHA256 []byte
configTemplateRelPath, _, configTemplateContents, err := c.findFirstConfigTemplate()
if err != nil {
return err
}
if configTemplateRelPath != chezmoi.EmptyRelPath {
currentConfigTemplateContentsSHA256 = chezmoi.SHA256Sum(configTemplateContents)
}
var previousConfigTemplateContentsSHA256 []byte
if configStateData, err := c.persistentState.Get(chezmoi.ConfigStateBucket, configStateKey); err != nil {
return err
} else if configStateData != nil {
var configState configState
if err := json.Unmarshal(configStateData, &configState); err != nil {
return err
}
previousConfigTemplateContentsSHA256 = []byte(configState.ConfigTemplateContentsSHA256)
}
configTemplatesEmpty := currentConfigTemplateContentsSHA256 == nil && previousConfigTemplateContentsSHA256 == nil
configTemplateContentsUnchanged := configTemplatesEmpty ||
bytes.Equal(currentConfigTemplateContentsSHA256, previousConfigTemplateContentsSHA256)
if !configTemplateContentsUnchanged {
if c.force {
if configTemplateRelPath == chezmoi.EmptyRelPath {
if err := c.persistentState.Delete(chezmoi.ConfigStateBucket, configStateKey); err != nil {
return err
}
} else {
configStateValue, err := json.Marshal(configState{
ConfigTemplateContentsSHA256: chezmoi.HexBytes(currentConfigTemplateContentsSHA256),
})
if err != nil {
return err
}
if err := c.persistentState.Set(chezmoi.ConfigStateBucket, configStateKey, configStateValue); err != nil {
return err
}
}
} else {
c.errorf("warning: config file template has changed, run chezmoi init to regenerate config file\n")
}
}
sourceState, err := c.newSourceState(ctx)
if err != nil {
return err
}
var targetRelPaths chezmoi.RelPaths
switch {
case len(args) == 0:
targetRelPaths = sourceState.TargetRelPaths()
case c.sourcePath:
targetRelPaths, err = c.targetRelPathsBySourcePath(sourceState, args)
if err != nil {
return err
}
default:
targetRelPaths, err = c.targetRelPaths(sourceState, args, targetRelPathsOptions{
mustBeInSourceState: true,
recursive: options.recursive,
})
if err != nil {
return err
}
}
applyOptions := chezmoi.ApplyOptions{
Include: options.include.Sub(options.exclude),
PreApplyFunc: options.preApplyFunc,
Umask: options.umask,
}
keptGoingAfterErr := false
for _, targetRelPath := range targetRelPaths {
switch err := sourceState.Apply(
targetSystem, c.destSystem, c.persistentState, targetDirAbsPath, targetRelPath, applyOptions,
); {
case errors.Is(err, chezmoi.Skip):
continue
case err != nil && c.keepGoing:
c.errorf("%v\n", err)
keptGoingAfterErr = true
case err != nil:
return err
}
}
if keptGoingAfterErr {
return chezmoi.ExitCodeError(1)
}
return nil
}
// close closes resources associated with c.
func (c *Config) close() error {
var err error
for _, tempDirAbsPath := range c.tempDirs {
err2 := os.RemoveAll(tempDirAbsPath.String())
c.logger.Err(err2).
Stringer("tempDir", tempDirAbsPath).
Msg("RemoveAll")
err = multierr.Append(err, err2)
}
pprof.StopCPUProfile()
agent.Close()
return err
}
// cmdOutput returns the of running the command name with args in dirAbsPath.
func (c *Config) cmdOutput(dirAbsPath chezmoi.AbsPath, name string, args []string) ([]byte, error) {
cmd := exec.Command(name, args...)
if !dirAbsPath.Empty() {
dirRawAbsPath, err := c.baseSystem.RawPath(dirAbsPath)
if err != nil {
return nil, err
}
cmd.Dir = dirRawAbsPath.String()
}
return c.baseSystem.IdempotentCmdOutput(cmd)
}
// colorAutoFunc detects whether color should be used.
func (c *Config) colorAutoFunc() bool {
if _, ok := os.LookupEnv("NO_COLOR"); ok {
return false
}
if stdout, ok := c.stdout.(*os.File); ok {
return term.IsTerminal(int(stdout.Fd()))
}
return false
}
// createAndReloadConfigFile creates a config file if it there is a config file
// template and reloads it.
func (c *Config) createAndReloadConfigFile() error {
// Find config template, execute it, and create config file.
configTemplateRelPath, ext, configTemplateContents, err := c.findFirstConfigTemplate()
if err != nil {
return err
}
var configFileContents []byte
if configTemplateRelPath == chezmoi.EmptyRelPath {
if err := c.persistentState.Delete(chezmoi.ConfigStateBucket, configStateKey); err != nil {
return err
}
} else {
configFileContents, err = c.createConfigFile(configTemplateRelPath, configTemplateContents)
if err != nil {
return err
}
// Validate the config.
v := viper.New()
v.SetConfigType(ext)
if err := v.ReadConfig(bytes.NewBuffer(configFileContents)); err != nil {
return err
}
if err := v.Unmarshal(&Config{}, viperDecodeConfigOptions...); err != nil {
return err
}
// Write the config.
configPath := c.init.configPath
if c.init.configPath.Empty() {
configPath = chezmoi.NewAbsPath(c.bds.ConfigHome).Join(chezmoiRelPath, configTemplateRelPath)
}
if err := chezmoi.MkdirAll(c.baseSystem, configPath.Dir(), 0o777); err != nil {
return err
}
if err := c.baseSystem.WriteFile(configPath, configFileContents, 0o600); err != nil {
return err
}
configStateValue, err := json.Marshal(configState{
ConfigTemplateContentsSHA256: chezmoi.HexBytes(chezmoi.SHA256Sum(configTemplateContents)),
})
if err != nil {
return err
}
if err := c.persistentState.Set(chezmoi.ConfigStateBucket, configStateKey, configStateValue); err != nil {
return err
}
}
// Reload config if it was created.
if configTemplateRelPath != chezmoi.EmptyRelPath {
viper.SetConfigType(ext)
if err := viper.ReadConfig(bytes.NewBuffer(configFileContents)); err != nil {
return err
}
if err := viper.Unmarshal(c, viperDecodeConfigOptions...); err != nil {
return err
}
}
return nil
}
// createConfigFile creates a config file using a template and returns its
// contents.
func (c *Config) createConfigFile(filename chezmoi.RelPath, data []byte) ([]byte, error) {
funcMap := make(template.FuncMap)
chezmoi.RecursiveMerge(funcMap, c.templateFuncs)
initTemplateFuncs := map[string]interface{}{
"promptBool": c.promptBoolInitTemplateFunc,
"promptInt": c.promptIntInitTemplateFunc,
"promptString": c.promptStringInitTemplateFunc,
"stdinIsATTY": c.stdinIsATTYInitTemplateFunc,
"writeToStdout": c.writeToStdout,
}
for _, releaseTag := range build.Default.ReleaseTags {
if releaseTag == "go1.17" {
initTemplateFuncs["exit"] = c.exitInitTemplateFunc
break
}
}
chezmoi.RecursiveMerge(funcMap, initTemplateFuncs)
t, err := template.New(filename.String()).Funcs(funcMap).Parse(string(data))
if err != nil {
return nil, err
}
builder := strings.Builder{}
templateData := c.defaultTemplateData()
if c.init.data {
chezmoi.RecursiveMerge(templateData, c.Data)
}
if err = t.Execute(&builder, templateData); err != nil {
return nil, err
}
return []byte(builder.String()), nil
}
// defaultConfigFile returns the default config file according to the XDG Base
// Directory Specification.
func (c *Config) defaultConfigFile(
fileSystem vfs.Stater, bds *xdg.BaseDirectorySpecification,
) (chezmoi.AbsPath, error) {
// Search XDG Base Directory Specification config directories first.
for _, configDir := range bds.ConfigDirs {
configDirAbsPath, err := chezmoi.NewAbsPathFromExtPath(configDir, c.homeDirAbsPath)
if err != nil {
return chezmoi.EmptyAbsPath, err
}
for _, extension := range viper.SupportedExts {
configFileAbsPath := configDirAbsPath.JoinString("chezmoi", "chezmoi."+extension)
if _, err := fileSystem.Stat(configFileAbsPath.String()); err == nil {
return configFileAbsPath, nil
}
}
}
// Fallback to XDG Base Directory Specification default.
configHomeAbsPath, err := chezmoi.NewAbsPathFromExtPath(bds.ConfigHome, c.homeDirAbsPath)
if err != nil {
return chezmoi.EmptyAbsPath, err
}
return configHomeAbsPath.JoinString("chezmoi", "chezmoi.toml"), nil
}
// defaultPreApplyFunc is the default pre-apply function. If the target entry
// has changed since chezmoi last wrote it then it prompts the user for the
// action to take.
func (c *Config) defaultPreApplyFunc(
targetRelPath chezmoi.RelPath, targetEntryState, lastWrittenEntryState, actualEntryState *chezmoi.EntryState,
) error {
c.logger.Info().
Stringer("targetRelPath", targetRelPath).
Object("targetEntryState", targetEntryState).
Object("lastWrittenEntryState", lastWrittenEntryState).
Object("actualEntryState", actualEntryState).
Msg("defaultPreApplyFunc")
switch {
case targetEntryState.Overwrite():
return nil
case targetEntryState.Type == chezmoi.EntryStateTypeScript:
return nil
case c.force:
return nil
case lastWrittenEntryState == nil:
return nil
case lastWrittenEntryState.Equivalent(actualEntryState):
return nil
}
prompt := fmt.Sprintf("%s has changed since chezmoi last wrote it", targetRelPath)
var choices []string
actualContents := actualEntryState.Contents()
targetContents := targetEntryState.Contents()
if actualContents != nil || targetContents != nil {
choices = append(choices, "diff")
}
choices = append(choices, "overwrite", "all-overwrite", "skip", "quit")
for {
switch choice, err := c.promptChoice(prompt, choices); {
case err != nil:
return err
case choice == "diff":
if err := c.diffFile(
targetRelPath,
actualContents, actualEntryState.Mode,
targetContents, targetEntryState.Mode,
); err != nil {
return err
}
case choice == "overwrite":
return nil
case choice == "all-overwrite":
c.force = true
return nil
case choice == "skip":
return chezmoi.Skip
case choice == "quit":
return chezmoi.ExitCodeError(1)
default:
return nil
}
}
}
// defaultSourceDir returns the default source directory according to the XDG
// Base Directory Specification.
func (c *Config) defaultSourceDir(fileSystem vfs.Stater, bds *xdg.BaseDirectorySpecification) (chezmoi.AbsPath, error) {
// Check for XDG Base Directory Specification data directories first.
for _, dataDir := range bds.DataDirs {
dataDirAbsPath, err := chezmoi.NewAbsPathFromExtPath(dataDir, c.homeDirAbsPath)
if err != nil {
return chezmoi.EmptyAbsPath, err
}
sourceDirAbsPath := dataDirAbsPath.Join(chezmoiRelPath)
if _, err := fileSystem.Stat(sourceDirAbsPath.String()); err == nil {
return sourceDirAbsPath, nil
}
}
// Fallback to XDG Base Directory Specification default.
dataHomeAbsPath, err := chezmoi.NewAbsPathFromExtPath(bds.DataHome, c.homeDirAbsPath)
if err != nil {
return chezmoi.EmptyAbsPath, err
}
return dataHomeAbsPath.Join(chezmoiRelPath), nil
}
// defaultTemplateData returns the default template data.
func (c *Config) defaultTemplateData() map[string]interface{} {
// Determine the user's username and group, if possible.
//
// user.Current and user.LookupGroupId in Go's standard library are
// generally unreliable, so work around errors if possible, or ignore them.
//
// If CGO is disabled, then the Go standard library falls back to parsing
// /etc/passwd and /etc/group, which will return incorrect results without
// error if the system uses an alternative password database such as NIS or
// LDAP.
//
// If CGO is enabled then user.Current and user.LookupGroupId will use the
// underlying libc functions, namely getpwuid_r and getgrnam_r. If linked
// with glibc this will return the correct result. If linked with musl then
// they will use musl's implementation which, like Go's non-CGO
// implementation, also only parses /etc/passwd and /etc/group and so also
// returns incorrect results without error if NIS or LDAP are being used.
//
// On Windows, the user's group ID returned by user.Current() is an SID and
// no further useful lookup is possible with Go's standard library.
//
// Since neither the username nor the group are likely widely used in
// templates, leave these variables unset if their values cannot be
// determined. Unset variables will trigger template errors if used,
// alerting the user to the problem and allowing them to find alternative
// solutions.
var username, group string
if currentUser, err := user.Current(); err == nil {
username = currentUser.Username
if runtime.GOOS != "windows" {
if rawGroup, err := user.LookupGroupId(currentUser.Gid); err == nil {
group = rawGroup.Name
} else {
c.logger.Info().
Str("gid", currentUser.Gid).
Err(err).
Msg("user.LookupGroupId")
}
}
} else {
c.logger.Info().
Err(err).
Msg("user.Current")
var ok bool
username, ok = os.LookupEnv("USER")
if !ok {
c.logger.Info().
Str("key", "USER").
Bool("ok", ok).
Msg("os.LookupEnv")
}
}
fqdnHostname := chezmoi.FQDNHostname(c.fileSystem)
var hostname string
if rawHostname, err := os.Hostname(); err == nil {
hostname, _, _ = chezmoi.CutString(rawHostname, "=")
} else {
c.logger.Info().
Err(err).
Msg("os.Hostname")
}
kernel, err := chezmoi.Kernel(c.fileSystem)
if err != nil {
c.logger.Info().
Err(err).
Msg("chezmoi.Kernel")
}
var osRelease map[string]interface{}
if rawOSRelease, err := chezmoi.OSRelease(c.baseSystem); err == nil {
osRelease = upperSnakeCaseToCamelCaseMap(rawOSRelease)
} else {
c.logger.Info().
Err(err).
Msg("chezmoi.OSRelease")
}
executable, _ := os.Executable()
return map[string]interface{}{
"chezmoi": map[string]interface{}{
"arch": runtime.GOARCH,
"args": os.Args,
"cacheDir": c.CacheDirAbsPath.String(),
"configFile": c.configFileAbsPath.String(),
"executable": executable,
"fqdnHostname": fqdnHostname,
"group": group,
"homeDir": c.homeDir,
"hostname": hostname,
"kernel": kernel,
"os": runtime.GOOS,
"osRelease": osRelease,
"sourceDir": c.SourceDirAbsPath.String(),
"username": username,
"version": map[string]interface{}{
"builtBy": c.versionInfo.BuiltBy,
"commit": c.versionInfo.Commit,
"date": c.versionInfo.Date,
"version": c.versionInfo.Version,
},
"workingTree": c.WorkingTreeAbsPath.String(),
},
}
}
type destAbsPathInfosOptions struct {
follow bool
ignoreNotExist bool
recursive bool
}
// destAbsPathInfos returns the os/fs.FileInfos for each destination entry in
// args, recursing into subdirectories and following symlinks if configured in
// options.
func (c *Config) destAbsPathInfos(
sourceState *chezmoi.SourceState, args []string, options destAbsPathInfosOptions,
) (map[chezmoi.AbsPath]fs.FileInfo, error) {
destAbsPathInfos := make(map[chezmoi.AbsPath]fs.FileInfo)
for _, arg := range args {
arg = filepath.Clean(arg)
destAbsPath, err := chezmoi.NewAbsPathFromExtPath(arg, c.homeDirAbsPath)
if err != nil {
return nil, err
}
if _, err := destAbsPath.TrimDirPrefix(c.DestDirAbsPath); err != nil {
return nil, err
}
if options.recursive {
walkFunc := func(destAbsPath chezmoi.AbsPath, fileInfo fs.FileInfo, err error) error {
switch {
case options.ignoreNotExist && errors.Is(err, fs.ErrNotExist):
return nil
case err != nil:
return err
}
if options.follow && fileInfo.Mode().Type() == fs.ModeSymlink {
fileInfo, err = c.destSystem.Stat(destAbsPath)
if err != nil {
return err
}