-
Notifications
You must be signed in to change notification settings - Fork 464
/
sourcestate.go
2856 lines (2645 loc) · 89.5 KB
/
sourcestate.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 chezmoi
// FIXME implement externals in chezmoi source state format
import (
"bufio"
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"slices"
"sort"
"strings"
"sync"
"syscall"
"text/template"
"time"
"github.com/coreos/go-semver/semver"
"github.com/mitchellh/copystructure"
"github.com/twpayne/chezmoi/v2/internal/chezmoierrors"
"github.com/twpayne/chezmoi/v2/internal/chezmoilog"
"github.com/twpayne/chezmoi/v2/internal/chezmoimaps"
"github.com/twpayne/chezmoi/v2/internal/chezmoiset"
)
// An ExternalType is a type of external source.
type ExternalType string
// ExternalTypes.
const (
ExternalTypeArchive ExternalType = "archive"
ExternalTypeArchiveFile ExternalType = "archive-file"
ExternalTypeFile ExternalType = "file"
ExternalTypeGitRepo ExternalType = "git-repo"
)
var (
lineEndingRx = regexp.MustCompile(`(?m)(?:\r\n|\r|\n)`)
modifyTemplateRx = regexp.MustCompile(`(?m)^.*chezmoi:modify-template.*$(?:\r?\n)?`)
templateDirectiveRx = regexp.MustCompile(`(?m)^.*?chezmoi:template:(.*)$(?:\r?\n)?`)
templateDirectiveKeyValuePairRx = regexp.MustCompile(`\s*(\S+)=("(?:[^"]|\\")*"|\S+)`)
// AppleDouble constants.
appleDoubleNamePrefix = "._"
appleDoubleContentsPrefix = []byte{0x00, 0x05, 0x16, 0x07, 0x00, 0x02, 0x00, 0x00}
)
type externalArchive struct {
ExtractAppleDoubleFiles bool `json:"extractAppleDoubleFiles" toml:"extractAppleDoubleFiles" yaml:"extractAppleDoubleFiles"`
}
type externalChecksum struct {
MD5 HexBytes `json:"md5" toml:"md5" yaml:"md5"`
RIPEMD160 HexBytes `json:"ripemd160" toml:"ripemd160" yaml:"ripemd160"`
SHA1 HexBytes `json:"sha1" toml:"sha1" yaml:"sha1"`
SHA256 HexBytes `json:"sha256" toml:"sha256" yaml:"sha256"`
SHA384 HexBytes `json:"sha384" toml:"sha384" yaml:"sha384"`
SHA512 HexBytes `json:"sha512" toml:"sha512" yaml:"sha512"`
Size int `json:"size" toml:"size" yaml:"size"`
}
type externalClone struct {
Args []string `json:"args" toml:"args" yaml:"args"`
}
type externalFilter struct {
Command string `json:"command" toml:"command" yaml:"command"`
Args []string `json:"args" toml:"args" yaml:"args"`
}
type externalPull struct {
Args []string `json:"args" toml:"args" yaml:"args"`
}
// An External is an external source.
type External struct {
Type ExternalType `json:"type" toml:"type" yaml:"type"`
Encrypted bool `json:"encrypted" toml:"encrypted" yaml:"encrypted"`
Exact bool `json:"exact" toml:"exact" yaml:"exact"`
Executable bool `json:"executable" toml:"executable" yaml:"executable"`
Checksum externalChecksum `json:"checksum" toml:"checksum" yaml:"checksum"`
Clone externalClone `json:"clone" toml:"clone" yaml:"clone"`
Exclude []string `json:"exclude" toml:"exclude" yaml:"exclude"`
Filter externalFilter `json:"filter" toml:"filter" yaml:"filter"`
Format ArchiveFormat `json:"format" toml:"format" yaml:"format"`
Archive externalArchive `json:"archive" toml:"archive" yaml:"archive"`
Include []string `json:"include" toml:"include" yaml:"include"`
ArchivePath string `json:"path" toml:"path" yaml:"path"`
Pull externalPull `json:"pull" toml:"pull" yaml:"pull"`
RefreshPeriod Duration `json:"refreshPeriod" toml:"refreshPeriod" yaml:"refreshPeriod"`
StripComponents int `json:"stripComponents" toml:"stripComponents" yaml:"stripComponents"`
URL string `json:"url" toml:"url" yaml:"url"`
sourceAbsPath AbsPath
}
// A SourceState is a source state.
type SourceState struct {
sync.Mutex
root sourceStateEntryTreeNode
removeDirs chezmoiset.Set[RelPath]
baseSystem System
system System
sourceDirAbsPath AbsPath
destDirAbsPath AbsPath
cacheDirAbsPath AbsPath
umask fs.FileMode
encryption Encryption
ignore *patternSet
remove *patternSet
interpreters map[string]Interpreter
httpClient *http.Client
logger *slog.Logger
version semver.Version
mode Mode
defaultTemplateDataFunc func() map[string]any
templateDataOnly bool
readTemplateData bool
readTemplates bool
defaultTemplateData map[string]any
userTemplateData map[string]any
priorityTemplateData map[string]any
templateData map[string]any
templateFuncs template.FuncMap
templateOptions []string
templates map[string]*Template
externals map[RelPath][]*External
ignoredRelPaths chezmoiset.Set[RelPath]
}
// A SourceStateOption sets an option on a source state.
type SourceStateOption func(*SourceState)
// WithBaseSystem sets the base system.
func WithBaseSystem(baseSystem System) SourceStateOption {
return func(s *SourceState) {
s.baseSystem = baseSystem
}
}
// WithCacheDir sets the cache directory.
func WithCacheDir(cacheDirAbsPath AbsPath) SourceStateOption {
return func(s *SourceState) {
s.cacheDirAbsPath = cacheDirAbsPath
}
}
// WithDefaultTemplateDataFunc sets the default template data function.
func WithDefaultTemplateDataFunc(defaultTemplateDataFunc func() map[string]any) SourceStateOption {
return func(s *SourceState) {
s.defaultTemplateDataFunc = defaultTemplateDataFunc
}
}
// WithDestDir sets the destination directory.
func WithDestDir(destDirAbsPath AbsPath) SourceStateOption {
return func(s *SourceState) {
s.destDirAbsPath = destDirAbsPath
}
}
// WithEncryption sets the encryption.
func WithEncryption(encryption Encryption) SourceStateOption {
return func(s *SourceState) {
s.encryption = encryption
}
}
// WithHTTPClient sets the HTTP client.
func WithHTTPClient(httpClient *http.Client) SourceStateOption {
return func(s *SourceState) {
s.httpClient = httpClient
}
}
// WithInterpreters sets the interpreters.
func WithInterpreters(interpreters map[string]Interpreter) SourceStateOption {
return func(s *SourceState) {
s.interpreters = interpreters
}
}
// WithLogger sets the logger.
func WithLogger(logger *slog.Logger) SourceStateOption {
return func(s *SourceState) {
s.logger = logger
}
}
// WithMode sets the mode.
func WithMode(mode Mode) SourceStateOption {
return func(s *SourceState) {
s.mode = mode
}
}
// WithPriorityTemplateData adds priority template data.
func WithPriorityTemplateData(priorityTemplateData map[string]any) SourceStateOption {
return func(s *SourceState) {
RecursiveMerge(s.priorityTemplateData, priorityTemplateData)
}
}
// WithReadTemplateData sets whether to read .chezmoidata.<format> files.
func WithReadTemplateData(readTemplateData bool) SourceStateOption {
return func(s *SourceState) {
s.readTemplateData = readTemplateData
}
}
// WithReadTemplates sets whether to read .chezmoitemplates directories.
func WithReadTemplates(readTemplates bool) SourceStateOption {
return func(s *SourceState) {
s.readTemplates = readTemplates
}
}
// WithSourceDir sets the source directory.
func WithSourceDir(sourceDirAbsPath AbsPath) SourceStateOption {
return func(s *SourceState) {
s.sourceDirAbsPath = sourceDirAbsPath
}
}
// WithSystem sets the system.
func WithSystem(system System) SourceStateOption {
return func(s *SourceState) {
s.system = system
}
}
// WithTemplateDataOnly sets whether only template data should be read.
func WithTemplateDataOnly(templateDataOnly bool) SourceStateOption {
return func(s *SourceState) {
s.templateDataOnly = templateDataOnly
}
}
// WithTemplateFuncs sets the template functions.
func WithTemplateFuncs(templateFuncs template.FuncMap) SourceStateOption {
return func(s *SourceState) {
s.templateFuncs = templateFuncs
}
}
// WithTemplateOptions sets the template options.
func WithTemplateOptions(templateOptions []string) SourceStateOption {
return func(s *SourceState) {
s.templateOptions = templateOptions
}
}
// WithUmask sets the umask.
func WithUmask(umask fs.FileMode) SourceStateOption {
return func(s *SourceState) {
s.umask = umask
}
}
// WithVersion sets the version.
func WithVersion(version semver.Version) SourceStateOption {
return func(s *SourceState) {
s.version = version
}
}
// A targetStateEntryFunc returns a TargetStateEntry based on reading an AbsPath
// on a System.
type targetStateEntryFunc func(System, AbsPath) (TargetStateEntry, error)
// NewSourceState creates a new source state with the given options.
func NewSourceState(options ...SourceStateOption) *SourceState {
s := &SourceState{
removeDirs: chezmoiset.New[RelPath](),
umask: Umask,
encryption: NoEncryption{},
ignore: newPatternSet(),
remove: newPatternSet(),
httpClient: http.DefaultClient,
logger: slog.Default(),
readTemplateData: true,
readTemplates: true,
priorityTemplateData: make(map[string]any),
userTemplateData: make(map[string]any),
templateOptions: DefaultTemplateOptions,
templates: make(map[string]*Template),
externals: make(map[RelPath][]*External),
ignoredRelPaths: chezmoiset.New[RelPath](),
}
for _, option := range options {
option(s)
}
return s
}
// A PreAddFunc is called before a new source state entry is added.
type PreAddFunc func(targetRelPath RelPath, fileInfo fs.FileInfo) error
// A ReplaceFunc is called before a source state entry is replaced.
type ReplaceFunc func(targetRelPath RelPath, newSourceStateEntry, oldSourceStateEntry SourceStateEntry) error
// AddOptions are options to SourceState.Add.
type AddOptions struct {
AutoTemplate bool // Automatically create templates, if possible.
Create bool // Add create_ entries instead of normal entries.
Encrypt bool // Encrypt files.
EncryptedSuffix string // Suffix for encrypted files.
Errorf func(string, ...any) // Function to print errors.
Exact bool // Add the exact_ attribute to added directories.
Filter *EntryTypeFilter // Entry type filter.
OnIgnoreFunc func(RelPath) // Function to call when a target is ignored.
PreAddFunc PreAddFunc // Function to be called before a source entry is added.
ConfigFileAbsPath AbsPath // Path to config file.
ProtectedAbsPaths []AbsPath // Paths that must not be added.
RemoveDir RelPath // Directory to remove before adding.
ReplaceFunc ReplaceFunc // Function to be called before a source entry is replaced.
Template bool // Add the .tmpl attribute to added files.
TemplateSymlinks bool // Add symlinks with targets in the source or home directories as templates.
}
// Add adds destAbsPathInfos to s.
func (s *SourceState) Add(
sourceSystem System,
persistentState PersistentState,
destSystem System,
destAbsPathInfos map[AbsPath]fs.FileInfo,
options *AddOptions,
) error {
// Filter out excluded and ignored paths.
destAbsPaths := AbsPaths(chezmoimaps.Keys(destAbsPathInfos))
sort.Sort(destAbsPaths)
n := 0
for _, destAbsPath := range destAbsPaths {
destAbsPathInfo := destAbsPathInfos[destAbsPath]
if !options.Filter.IncludeFileInfo(destAbsPathInfo) {
continue
}
targetRelPath := destAbsPath.MustTrimDirPrefix(s.destDirAbsPath)
if s.Ignore(targetRelPath) {
if options.OnIgnoreFunc != nil {
options.OnIgnoreFunc(targetRelPath)
}
continue
}
destAbsPaths[n] = destAbsPath
n++
}
destAbsPaths = destAbsPaths[:n]
// Check for protected paths.
for _, destAbsPath := range destAbsPaths {
if destAbsPath == options.ConfigFileAbsPath {
format := "%s: cannot add chezmoi's config file to chezmoi, use a config file template instead"
return fmt.Errorf(format, destAbsPath)
}
}
for _, destAbsPath := range destAbsPaths {
for _, protectedAbsPath := range options.ProtectedAbsPaths {
switch {
case protectedAbsPath.Empty():
// Do nothing.
case strings.HasPrefix(destAbsPath.String(), protectedAbsPath.String()):
format := "%s: cannot add chezmoi file to chezmoi (%s is protected)"
return fmt.Errorf(format, destAbsPath, protectedAbsPath)
}
}
}
type sourceUpdate struct {
destAbsPath AbsPath
entryState *EntryState
sourceRelPaths []SourceRelPath
}
sourceUpdates := make([]sourceUpdate, 0, len(destAbsPaths))
newSourceStateEntries := make(map[SourceRelPath]SourceStateEntry)
newSourceStateEntriesByTargetRelPath := make(map[RelPath]SourceStateEntry)
nonEmptyDirs := chezmoiset.New[SourceRelPath]()
externalDirRelPaths := chezmoiset.New[RelPath]()
dirRenames := make(map[AbsPath]AbsPath)
DEST_ABS_PATH:
for _, destAbsPath := range destAbsPaths {
targetRelPath := destAbsPath.MustTrimDirPrefix(s.destDirAbsPath)
// Skip any entries in known external dirs.
for externalDir := range externalDirRelPaths {
if targetRelPath.HasDirPrefix(externalDir) {
continue DEST_ABS_PATH
}
}
// Find the target's parent directory in the source state.
var parentSourceRelPath SourceRelPath
if targetParentRelPath := targetRelPath.Dir(); targetParentRelPath == DotRelPath {
parentSourceRelPath = SourceRelPath{}
} else if parentEntry, ok := newSourceStateEntriesByTargetRelPath[targetParentRelPath]; ok {
parentSourceRelPath = parentEntry.SourceRelPath()
} else if nodes := s.root.getNodes(targetParentRelPath); nodes != nil {
for i, node := range nodes {
if i == 0 {
// nodes[0].sourceStateEntry should always be nil because it
// refers to the destination directory, which is not manged.
// chezmoi manages the destination directory's contents, not
// the destination directory itself. For example, chezmoi
// does not set the name or permissions of the user's home
// directory.
if node.sourceStateEntry != nil {
panic(fmt.Errorf("nodes[0]: expected nil, got %+v", node.sourceStateEntry))
}
continue
}
switch sourceStateDir, ok := node.sourceStateEntry.(*SourceStateDir); {
case i != len(nodes)-1 && !ok:
panic(fmt.Errorf("nodes[%d]: unexpected non-terminal source state entry, got %T", i, node.sourceStateEntry))
case ok && sourceStateDir.Attr.External:
targetRelPathComponents := targetRelPath.SplitAll()
externalDirRelPath := EmptyRelPath.Join(targetRelPathComponents[:i]...)
externalDirRelPaths.Add(externalDirRelPath)
if options.Errorf != nil {
options.Errorf("%s: skipping entries in external_ directory\n", externalDirRelPath)
}
continue DEST_ABS_PATH
}
}
parentSourceRelPath = nodes[len(nodes)-1].sourceStateEntry.SourceRelPath()
} else {
return fmt.Errorf("%s: parent directory not in source state", destAbsPath)
}
nonEmptyDirs.Add(parentSourceRelPath)
destAbsPathInfo := destAbsPathInfos[destAbsPath]
actualStateEntry, err := NewActualStateEntry(destSystem, destAbsPath, destAbsPathInfo, nil)
if err != nil {
return err
}
newSourceStateEntry, err := s.sourceStateEntry(actualStateEntry, destAbsPath, destAbsPathInfo, parentSourceRelPath, options)
if err != nil {
return err
}
if newSourceStateEntry == nil {
continue
}
if options.PreAddFunc != nil {
switch err := options.PreAddFunc(targetRelPath, destAbsPathInfo); {
case errors.Is(err, fs.SkipDir):
continue DEST_ABS_PATH
case err != nil:
return err
}
}
sourceEntryRelPath := newSourceStateEntry.SourceRelPath()
entryState, err := actualStateEntry.EntryState()
if err != nil {
return err
}
update := sourceUpdate{
destAbsPath: destAbsPath,
entryState: entryState,
sourceRelPaths: []SourceRelPath{sourceEntryRelPath},
}
if oldSourceStateEntry := s.root.get(targetRelPath); oldSourceStateEntry != nil {
oldSourceEntryRelPath := oldSourceStateEntry.SourceRelPath()
if !oldSourceEntryRelPath.Empty() && oldSourceEntryRelPath != sourceEntryRelPath {
if options.ReplaceFunc != nil {
switch err := options.ReplaceFunc(targetRelPath, newSourceStateEntry, oldSourceStateEntry); {
case errors.Is(err, fs.SkipDir):
continue DEST_ABS_PATH
case err != nil:
return err
}
}
// If both the new and old source state entries are directories
// but the name has changed, rename to avoid losing the
// directory's contents.
_, newIsDir := newSourceStateEntry.(*SourceStateDir)
_, oldIsDir := oldSourceStateEntry.(*SourceStateDir)
if newIsDir && oldIsDir {
oldSourceAbsPath := s.sourceDirAbsPath.Join(oldSourceEntryRelPath.RelPath())
newSourceAbsPath := s.sourceDirAbsPath.Join(sourceEntryRelPath.RelPath())
dirRenames[oldSourceAbsPath] = newSourceAbsPath
continue DEST_ABS_PATH
}
// Otherwise, remove the old entry.
newSourceStateEntries[oldSourceEntryRelPath] = &SourceStateRemove{
origin: SourceStateOriginRemove{},
}
update.sourceRelPaths = append(update.sourceRelPaths, oldSourceEntryRelPath)
}
}
newSourceStateEntries[sourceEntryRelPath] = newSourceStateEntry
newSourceStateEntriesByTargetRelPath[targetRelPath] = newSourceStateEntry
sourceUpdates = append(sourceUpdates, update)
}
// Create .keep files in empty added directories.
for sourceEntryRelPath, sourceStateEntry := range newSourceStateEntries {
if _, ok := sourceStateEntry.(*SourceStateDir); !ok {
continue
}
if nonEmptyDirs.Contains(sourceEntryRelPath) {
continue
}
dotKeepFileRelPath := sourceEntryRelPath.Join(NewSourceRelPath(".keep"))
dotKeepFileSourceUpdate := sourceUpdate{
entryState: &EntryState{
Type: EntryStateTypeFile,
Mode: 0o666 &^ s.umask,
},
sourceRelPaths: []SourceRelPath{dotKeepFileRelPath},
}
sourceUpdates = append(sourceUpdates, dotKeepFileSourceUpdate)
newSourceStateEntries[dotKeepFileRelPath] = &SourceStateFile{
targetStateEntry: &TargetStateFile{
empty: true,
perm: 0o666 &^ s.umask,
},
}
}
var sourceRoot sourceStateEntryTreeNode
for sourceRelPath, sourceStateEntry := range newSourceStateEntries {
sourceRoot.set(sourceRelPath.RelPath(), sourceStateEntry)
}
// Simulate removing a directory by creating SourceStateRemove entries for
// all existing source state entries that are in options.RemoveDir and not
// in the new source state.
if options.RemoveDir != EmptyRelPath {
_ = s.root.forEach(EmptyRelPath, func(targetRelPath RelPath, sourceStateEntry SourceStateEntry) error {
if !targetRelPath.HasDirPrefix(options.RemoveDir) {
return nil
}
if _, ok := newSourceStateEntriesByTargetRelPath[targetRelPath]; ok {
return nil
}
sourceRelPath := sourceStateEntry.SourceRelPath()
sourceRoot.set(sourceRelPath.RelPath(), &SourceStateRemove{
sourceRelPath: sourceRelPath,
targetRelPath: targetRelPath,
})
update := sourceUpdate{
destAbsPath: s.destDirAbsPath.Join(targetRelPath),
entryState: &EntryState{
Type: EntryStateTypeRemove,
},
sourceRelPaths: []SourceRelPath{sourceRelPath},
}
sourceUpdates = append(sourceUpdates, update)
return nil
})
}
targetSourceState := &SourceState{
root: sourceRoot,
}
for _, sourceUpdate := range sourceUpdates {
for _, sourceRelPath := range sourceUpdate.sourceRelPaths {
err := targetSourceState.Apply(
sourceSystem,
sourceSystem,
NullPersistentState{},
s.sourceDirAbsPath,
sourceRelPath.RelPath(),
ApplyOptions{
Filter: options.Filter,
Umask: s.umask,
},
)
if err != nil {
return err
}
}
if !sourceUpdate.destAbsPath.Empty() {
if err := PersistentStateSet(persistentState, EntryStateBucket, sourceUpdate.destAbsPath.Bytes(), sourceUpdate.entryState); err != nil {
return err
}
}
}
// Rename directories last because updates assume that directory names have
// not changed. Rename directories in reverse order so children are renamed
// before their parents.
oldDirAbsPaths := make([]AbsPath, 0, len(dirRenames))
for oldDirAbsPath := range dirRenames {
oldDirAbsPaths = append(oldDirAbsPaths, oldDirAbsPath)
}
sort.Slice(oldDirAbsPaths, func(i, j int) bool {
return oldDirAbsPaths[j].Less(oldDirAbsPaths[i])
})
for _, oldDirAbsPath := range oldDirAbsPaths {
newDirAbsPath := dirRenames[oldDirAbsPath]
if err := sourceSystem.Rename(oldDirAbsPath, newDirAbsPath); err != nil {
return err
}
}
return nil
}
// AddDestAbsPathInfos adds an fs.FileInfo to destAbsPathInfos for destAbsPath
// and any of its parents which are not already known.
func (s *SourceState) AddDestAbsPathInfos(
destAbsPathInfos map[AbsPath]fs.FileInfo,
system System,
destAbsPath AbsPath,
fileInfo fs.FileInfo,
) error {
for {
if _, err := destAbsPath.TrimDirPrefix(s.destDirAbsPath); err != nil {
return err
}
if _, ok := destAbsPathInfos[destAbsPath]; ok {
return nil
}
if fileInfo == nil {
var err error
fileInfo, err = system.Lstat(destAbsPath)
if err != nil {
return err
}
}
destAbsPathInfos[destAbsPath] = fileInfo
parentAbsPath := destAbsPath.Dir()
if parentAbsPath == s.destDirAbsPath {
return nil
}
parentRelPath := parentAbsPath.MustTrimDirPrefix(s.destDirAbsPath)
if _, ok := s.root.get(parentRelPath).(*SourceStateDir); ok {
return nil
}
destAbsPath = parentAbsPath
fileInfo = nil
}
}
// A PreApplyFunc is called before a target is applied.
type PreApplyFunc func(targetRelPath RelPath, targetEntryState, lastWrittenEntryState, actualEntryState *EntryState) error
// ApplyOptions are options to SourceState.ApplyAll and SourceState.ApplyOne.
type ApplyOptions struct {
Filter *EntryTypeFilter
PreApplyFunc PreApplyFunc
Umask fs.FileMode
}
// Apply updates targetRelPath in targetDirAbsPath in destSystem to match s.
func (s *SourceState) Apply(
targetSystem, destSystem System,
persistentState PersistentState,
targetDirAbsPath AbsPath,
targetRelPath RelPath,
options ApplyOptions,
) error {
sourceStateEntry := s.root.get(targetRelPath)
if !options.Filter.IncludeSourceStateEntry(sourceStateEntry) {
return nil
}
destAbsPath := s.destDirAbsPath.Join(targetRelPath)
targetStateEntry, err := sourceStateEntry.TargetStateEntry(destSystem, destAbsPath)
if err != nil {
return err
}
if !options.Filter.IncludeTargetStateEntry(targetStateEntry) {
return nil
}
targetAbsPath := targetDirAbsPath.Join(targetRelPath)
targetEntryState, err := targetStateEntry.EntryState(options.Umask)
if err != nil {
return err
}
switch skip, err := targetStateEntry.SkipApply(persistentState, targetAbsPath); {
case err != nil:
return err
case skip:
return nil
}
actualStateEntry, err := NewActualStateEntry(targetSystem, targetAbsPath, nil, nil)
if err != nil {
return err
}
if options.PreApplyFunc != nil {
var lastWrittenEntryState *EntryState
var entryState EntryState
ok, err := PersistentStateGet(persistentState, EntryStateBucket, targetAbsPath.Bytes(), &entryState)
if err != nil {
return err
}
if ok {
lastWrittenEntryState = &entryState
}
actualEntryState, err := actualStateEntry.EntryState()
if err != nil {
return err
}
// If the target entry state matches the actual entry state, but not the
// last written entry state then silently update the last written entry
// state. This handles the case where the user makes identical edits to
// the source and target states: instead of reporting a diff with
// respect to the last written state, we record the effect of the last
// apply as the last written state.
if targetEntryState.Equivalent(actualEntryState) && !lastWrittenEntryState.Equivalent(actualEntryState) {
err := PersistentStateSet(persistentState, EntryStateBucket, targetAbsPath.Bytes(), targetEntryState)
if err != nil {
return err
}
lastWrittenEntryState = targetEntryState
}
err = options.PreApplyFunc(targetRelPath, targetEntryState, lastWrittenEntryState, actualEntryState)
if err != nil {
return err
}
}
if changed, err := targetStateEntry.Apply(targetSystem, persistentState, actualStateEntry); err != nil {
return err
} else if !changed {
return nil
}
return PersistentStateSet(persistentState, EntryStateBucket, targetAbsPath.Bytes(), targetEntryState)
}
// Encryption returns s's encryption.
func (s *SourceState) Encryption() Encryption {
return s.encryption
}
// ExecuteTemplateDataOptions are options to SourceState.ExecuteTemplateData.
type ExecuteTemplateDataOptions struct {
Name string
Destination string
Data []byte
TemplateOptions TemplateOptions
}
// ExecuteTemplateData returns the result of executing template data.
func (s *SourceState) ExecuteTemplateData(options ExecuteTemplateDataOptions) ([]byte, error) {
templateOptions := options.TemplateOptions
templateOptions.Options = slices.Clone(s.templateOptions)
tmpl, err := ParseTemplate(options.Name, options.Data, s.templateFuncs, templateOptions)
if err != nil {
return nil, err
}
for _, t := range s.templates {
tmpl, err = tmpl.AddParseTree(t)
if err != nil {
return nil, err
}
}
// Set .chezmoi.sourceFile to the name of the template.
templateData := s.TemplateData()
if chezmoiTemplateData, ok := templateData["chezmoi"].(map[string]any); ok {
chezmoiTemplateData["sourceFile"] = options.Name
chezmoiTemplateData["targetFile"] = options.Destination
}
return tmpl.Execute(templateData)
}
// ForEach calls f for each source state entry.
func (s *SourceState) ForEach(f func(RelPath, SourceStateEntry) error) error {
return s.root.forEach(EmptyRelPath, func(targetRelPath RelPath, entry SourceStateEntry) error {
return f(targetRelPath, entry)
})
}
// Get returns the source state entry for targetRelPath.
func (s *SourceState) Get(targetRelPath RelPath) SourceStateEntry {
return s.root.get(targetRelPath)
}
// Ignore returns if targetRelPath should be ignored.
func (s *SourceState) Ignore(targetRelPath RelPath) bool {
s.Lock()
defer s.Unlock()
ignore := s.ignore.match(targetRelPath.String()) == patternSetMatchInclude
if ignore {
s.ignoredRelPaths.Add(targetRelPath)
}
return ignore
}
// Ignored returns all ignored RelPaths.
func (s *SourceState) Ignored() RelPaths {
relPaths := RelPaths(s.ignoredRelPaths.Elements())
sort.Sort(relPaths)
return relPaths
}
// MustEntry returns the source state entry associated with targetRelPath, and
// panics if it does not exist.
func (s *SourceState) MustEntry(targetRelPath RelPath) SourceStateEntry {
sourceStateEntry := s.root.get(targetRelPath)
if sourceStateEntry == nil {
panic(fmt.Sprintf("%s: not in source state", targetRelPath))
}
return sourceStateEntry
}
// PostApply performs all updates required after s.Apply.
func (s *SourceState) PostApply(
targetSystem System,
persistentState PersistentState,
targetDirAbsPath AbsPath,
targetRelPaths RelPaths,
) error {
// Remove empty directories with the remove_ attribute. This assumes that
// targetRelPaths is already sorted and iterates in reverse order so that
// children are removed before their parents.
TARGET:
for i := len(targetRelPaths) - 1; i >= 0; i-- {
targetRelPath := targetRelPaths[i]
if !s.removeDirs.Contains(targetRelPath) {
continue
}
// Ensure that we are attempting to remove a directory, not any other entry type.
targetAbsPath := targetDirAbsPath.Join(targetRelPath)
switch fileInfo, err := targetSystem.Stat(targetAbsPath); {
case errors.Is(err, fs.ErrNotExist):
continue TARGET
case err != nil:
return err
case !fileInfo.IsDir():
return fmt.Errorf("%s: not a directory", targetAbsPath)
}
// Attempt to remove the directory, but ignore any "not exist" or "not
// empty" errors.
switch err := targetSystem.Remove(targetAbsPath); {
case err == nil:
// Do nothing.
case errors.Is(err, fs.ErrExist):
// Do nothing.
case errors.Is(err, fs.ErrNotExist):
// Do nothing.
default:
return err
}
entryState := &EntryState{
Type: EntryStateTypeRemove,
}
if err := PersistentStateSet(persistentState, EntryStateBucket, targetAbsPath.Bytes(), entryState); err != nil {
return err
}
}
return nil
}
// ReadOptions are options to SourceState.Read.
type ReadOptions struct {
ReadHTTPResponse func(*http.Response) ([]byte, error)
RefreshExternals RefreshExternals
TimeNow func() time.Time
}
// Read reads the source state from the source directory.
func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error {
switch fileInfo, err := s.system.Stat(s.sourceDirAbsPath); {
case errors.Is(err, fs.ErrNotExist):
return nil
case err != nil:
return err
case !fileInfo.IsDir():
return fmt.Errorf("%s: not a directory", s.sourceDirAbsPath)
}
// Read all source entries.
var allSourceStateEntriesMu sync.Mutex
allSourceStateEntries := make(map[RelPath][]SourceStateEntry)
addSourceStateEntries := func(relPath RelPath, sourceStateEntries ...SourceStateEntry) {
allSourceStateEntriesMu.Lock()
defer allSourceStateEntriesMu.Unlock()
allSourceStateEntries[relPath] = append(allSourceStateEntries[relPath], sourceStateEntries...)
}
walkFunc := func(sourceAbsPath AbsPath, fileInfo fs.FileInfo, err error) error {
if err != nil {
return err
}
if sourceAbsPath == s.sourceDirAbsPath {
return nil
}
// Follow symlinks in the source directory.
if fileInfo.Mode().Type() == fs.ModeSymlink {
// Some programs (notably emacs) use invalid symlinks as lockfiles.
// To avoid following them and getting an ENOENT error, check first
// if this is an entry that we will ignore anyway.
if strings.HasPrefix(fileInfo.Name(), ignorePrefix) && !strings.HasPrefix(fileInfo.Name(), Prefix) {
return nil
}
fileInfo, err = s.system.Stat(sourceAbsPath)
if err != nil {
return err
}
}
sourceRelPath := SourceRelPath{
relPath: sourceAbsPath.MustTrimDirPrefix(s.sourceDirAbsPath),
isDir: fileInfo.IsDir(),
}
parentSourceRelPath, sourceName := sourceRelPath.Split()
switch {
case fileInfo.Name() == dataName:
if !s.readTemplateData {
return nil
}
if err := s.addTemplateDataDir(sourceAbsPath, fileInfo); err != nil {
return err
}
return fs.SkipDir
case isPrefixDotFormat(fileInfo.Name(), dataName):
if !s.readTemplateData {
return nil
}
return s.addTemplateData(sourceAbsPath)
case fileInfo.Name() == TemplatesDirName:
if s.readTemplates {
if err := s.addTemplatesDir(ctx, sourceAbsPath); err != nil {
return err
}
}
return fs.SkipDir
case s.templateDataOnly:
return nil
case isPrefixDotFormat(fileInfo.Name(), externalName) || isPrefixDotFormatDotTmpl(fileInfo.Name(), externalName):
parentAbsPath, _ := sourceAbsPath.Split()
return s.addExternal(sourceAbsPath, parentAbsPath)
case fileInfo.Name() == externalsDirName:
if err := s.addExternalDir(ctx, sourceAbsPath); err != nil {
return err
}
return fs.SkipDir
case fileInfo.Name() == ignoreName || fileInfo.Name() == ignoreName+TemplateSuffix:
return s.addPatterns(s.ignore, sourceAbsPath, parentSourceRelPath)
case fileInfo.Name() == removeName || fileInfo.Name() == removeName+TemplateSuffix:
return s.addPatterns(s.remove, sourceAbsPath, parentSourceRelPath)
case fileInfo.Name() == scriptsDirName:
scriptsDirSourceStateEntries, err := s.readScriptsDir(ctx, sourceAbsPath)
if err != nil {
return err
}
for relPath, scriptSourceStateEntries := range scriptsDirSourceStateEntries {
addSourceStateEntries(relPath, scriptSourceStateEntries...)
}
return fs.SkipDir
case fileInfo.Name() == VersionName:
return s.readVersionFile(sourceAbsPath)
case strings.HasPrefix(fileInfo.Name(), Prefix):
fallthrough
case strings.HasPrefix(fileInfo.Name(), ignorePrefix):
if fileInfo.IsDir() {
return fs.SkipDir